babylon.no-module.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060
  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. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  153. */
  154. this.onCompileObservable = new BABYLON.Observable();
  155. /**
  156. * Observable that will be called if an error occurs during shader compilation.
  157. */
  158. this.onErrorObservable = new BABYLON.Observable();
  159. /** @hidden */
  160. this._bonesComputationForcedToCPU = false;
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "onBindObservable", {
  240. /**
  241. * Observable that will be called when effect is bound.
  242. */
  243. get: function () {
  244. if (!this._onBindObservable) {
  245. this._onBindObservable = new BABYLON.Observable();
  246. }
  247. return this._onBindObservable;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. Object.defineProperty(Effect.prototype, "key", {
  253. /**
  254. * Unique key for this effect
  255. */
  256. get: function () {
  257. return this._key;
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. /**
  263. * If the effect has been compiled and prepared.
  264. * @returns if the effect is compiled and prepared.
  265. */
  266. Effect.prototype.isReady = function () {
  267. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  268. return this._engine._isProgramCompiled(this._program);
  269. }
  270. return this._isReady;
  271. };
  272. /**
  273. * The engine the effect was initialized with.
  274. * @returns the engine.
  275. */
  276. Effect.prototype.getEngine = function () {
  277. return this._engine;
  278. };
  279. /**
  280. * The compiled webGL program for the effect
  281. * @returns the webGL program.
  282. */
  283. Effect.prototype.getProgram = function () {
  284. return this._program;
  285. };
  286. /**
  287. * The set of names of attribute variables for the shader.
  288. * @returns An array of attribute names.
  289. */
  290. Effect.prototype.getAttributesNames = function () {
  291. return this._attributesNames;
  292. };
  293. /**
  294. * Returns the attribute at the given index.
  295. * @param index The index of the attribute.
  296. * @returns The location of the attribute.
  297. */
  298. Effect.prototype.getAttributeLocation = function (index) {
  299. return this._attributes[index];
  300. };
  301. /**
  302. * Returns the attribute based on the name of the variable.
  303. * @param name of the attribute to look up.
  304. * @returns the attribute location.
  305. */
  306. Effect.prototype.getAttributeLocationByName = function (name) {
  307. var index = this._attributesNames.indexOf(name);
  308. return this._attributes[index];
  309. };
  310. /**
  311. * The number of attributes.
  312. * @returns the numnber of attributes.
  313. */
  314. Effect.prototype.getAttributesCount = function () {
  315. return this._attributes.length;
  316. };
  317. /**
  318. * Gets the index of a uniform variable.
  319. * @param uniformName of the uniform to look up.
  320. * @returns the index.
  321. */
  322. Effect.prototype.getUniformIndex = function (uniformName) {
  323. return this._uniformsNames.indexOf(uniformName);
  324. };
  325. /**
  326. * Returns the attribute based on the name of the variable.
  327. * @param uniformName of the uniform to look up.
  328. * @returns the location of the uniform.
  329. */
  330. Effect.prototype.getUniform = function (uniformName) {
  331. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  332. };
  333. /**
  334. * Returns an array of sampler variable names
  335. * @returns The array of sampler variable neames.
  336. */
  337. Effect.prototype.getSamplers = function () {
  338. return this._samplers;
  339. };
  340. /**
  341. * The error from the last compilation.
  342. * @returns the error string.
  343. */
  344. Effect.prototype.getCompilationError = function () {
  345. return this._compilationError;
  346. };
  347. /**
  348. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  349. * @param func The callback to be used.
  350. */
  351. Effect.prototype.executeWhenCompiled = function (func) {
  352. var _this = this;
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. if (!this._program || this._program.isParallelCompiled) {
  361. setTimeout(function () {
  362. _this._checkIsReady();
  363. }, 16);
  364. }
  365. };
  366. Effect.prototype._checkIsReady = function () {
  367. var _this = this;
  368. if (this.isReady()) {
  369. return;
  370. }
  371. setTimeout(function () {
  372. _this._checkIsReady();
  373. }, 16);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadVertexShader = function (vertex, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (vertex instanceof HTMLElement) {
  380. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  381. callback(vertexCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (vertex.substr(0, 7) === "base64:") {
  387. var vertexBinary = window.atob(vertex.substr(7));
  388. callback(vertexBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  393. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  394. return;
  395. }
  396. var vertexShaderUrl;
  397. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  398. vertexShaderUrl = vertex;
  399. }
  400. else {
  401. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  402. }
  403. // Vertex shader
  404. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  405. };
  406. /** @hidden */
  407. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  408. if (BABYLON.Tools.IsWindowObjectExist()) {
  409. // DOM element ?
  410. if (fragment instanceof HTMLElement) {
  411. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  412. callback(fragmentCode);
  413. return;
  414. }
  415. }
  416. // Base64 encoded ?
  417. if (fragment.substr(0, 7) === "base64:") {
  418. var fragmentBinary = window.atob(fragment.substr(7));
  419. callback(fragmentBinary);
  420. return;
  421. }
  422. // Is in local store ?
  423. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  424. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  425. return;
  426. }
  427. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  428. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  429. return;
  430. }
  431. var fragmentShaderUrl;
  432. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  433. fragmentShaderUrl = fragment;
  434. }
  435. else {
  436. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  437. }
  438. // Fragment shader
  439. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  440. };
  441. /** @hidden */
  442. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  443. // Rebuild shaders source code
  444. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  445. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  446. vertexCode = prefix + vertexCode;
  447. fragmentCode = prefix + fragmentCode;
  448. // Number lines of shaders source code
  449. var i = 2;
  450. var regex = /\n/gm;
  451. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. i = 2;
  453. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  454. // Dump shaders name and formatted source code
  455. if (this.name.vertexElement) {
  456. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  457. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  458. }
  459. else if (this.name.vertex) {
  460. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  461. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  462. }
  463. else {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  466. }
  467. };
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. result = result.replace(/texture2D\s*\(/g, "texture(");
  492. if (isFragment) {
  493. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. * @hidden
  599. */
  600. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  601. var _this = this;
  602. this._isReady = false;
  603. this._vertexSourceCodeOverride = vertexSourceCode;
  604. this._fragmentSourceCodeOverride = fragmentSourceCode;
  605. this.onError = function (effect, error) {
  606. if (onError) {
  607. onError(error);
  608. }
  609. };
  610. this.onCompiled = function () {
  611. var scenes = _this.getEngine().scenes;
  612. for (var i = 0; i < scenes.length; i++) {
  613. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  614. }
  615. if (onCompiled) {
  616. onCompiled(_this._program);
  617. }
  618. };
  619. this._fallbacks = null;
  620. this._prepareEffect();
  621. };
  622. /**
  623. * Gets the uniform locations of the the specified variable names
  624. * @param names THe names of the variables to lookup.
  625. * @returns Array of locations in the same order as variable names.
  626. */
  627. Effect.prototype.getSpecificUniformLocations = function (names) {
  628. var engine = this._engine;
  629. return engine.getUniforms(this._program, names);
  630. };
  631. /**
  632. * Prepares the effect
  633. * @hidden
  634. */
  635. Effect.prototype._prepareEffect = function () {
  636. var _this = this;
  637. var attributesNames = this._attributesNames;
  638. var defines = this.defines;
  639. var fallbacks = this._fallbacks;
  640. this._valueCache = {};
  641. var previousProgram = this._program;
  642. try {
  643. var engine_1 = this._engine;
  644. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  645. this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  646. }
  647. else {
  648. this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  649. }
  650. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  651. engine_1._executeWhenProgramIsCompiled(this._program, function () {
  652. if (engine_1.supportsUniformBuffers) {
  653. for (var name in _this._uniformBuffersNames) {
  654. _this.bindUniformBlock(name, _this._uniformBuffersNames[name]);
  655. }
  656. }
  657. _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames);
  658. _this._attributes = engine_1.getAttributes(_this._program, attributesNames);
  659. var index;
  660. for (index = 0; index < _this._samplers.length; index++) {
  661. var sampler = _this.getUniform(_this._samplers[index]);
  662. if (sampler == null) {
  663. _this._samplers.splice(index, 1);
  664. index--;
  665. }
  666. }
  667. engine_1.bindSamplers(_this);
  668. _this._compilationError = "";
  669. _this._isReady = true;
  670. if (_this.onCompiled) {
  671. _this.onCompiled(_this);
  672. }
  673. _this.onCompileObservable.notifyObservers(_this);
  674. _this.onCompileObservable.clear();
  675. // Unbind mesh reference in fallbacks
  676. if (_this._fallbacks) {
  677. _this._fallbacks.unBindMesh();
  678. }
  679. if (previousProgram) {
  680. _this.getEngine()._deleteProgram(previousProgram);
  681. }
  682. });
  683. if (this._program.isParallelCompiled) {
  684. this._checkIsReady();
  685. }
  686. }
  687. catch (e) {
  688. this._compilationError = e.message;
  689. // Let's go through fallbacks then
  690. BABYLON.Tools.Error("Unable to compile effect:");
  691. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  692. return " " + uniform;
  693. }));
  694. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  695. return " " + attribute;
  696. }));
  697. BABYLON.Tools.Error("Error: " + this._compilationError);
  698. if (previousProgram) {
  699. this._program = previousProgram;
  700. this._isReady = true;
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. }
  706. if (fallbacks && fallbacks.isMoreFallbacks) {
  707. BABYLON.Tools.Error("Trying next fallback.");
  708. this.defines = fallbacks.reduce(this.defines, this);
  709. this._prepareEffect();
  710. }
  711. else { // Sorry we did everything we can
  712. if (this.onError) {
  713. this.onError(this, this._compilationError);
  714. }
  715. this.onErrorObservable.notifyObservers(this);
  716. this.onErrorObservable.clear();
  717. // Unbind mesh reference in fallbacks
  718. if (this._fallbacks) {
  719. this._fallbacks.unBindMesh();
  720. }
  721. }
  722. }
  723. };
  724. Object.defineProperty(Effect.prototype, "isSupported", {
  725. /**
  726. * Checks if the effect is supported. (Must be called after compilation)
  727. */
  728. get: function () {
  729. return this._compilationError === "";
  730. },
  731. enumerable: true,
  732. configurable: true
  733. });
  734. /**
  735. * Binds a texture to the engine to be used as output of the shader.
  736. * @param channel Name of the output variable.
  737. * @param texture Texture to bind.
  738. * @hidden
  739. */
  740. Effect.prototype._bindTexture = function (channel, texture) {
  741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  742. };
  743. /**
  744. * Sets a texture on the engine to be used in the shader.
  745. * @param channel Name of the sampler variable.
  746. * @param texture Texture to set.
  747. */
  748. Effect.prototype.setTexture = function (channel, texture) {
  749. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  750. };
  751. /**
  752. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  753. * @param channel Name of the sampler variable.
  754. * @param texture Texture to set.
  755. */
  756. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  757. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  758. };
  759. /**
  760. * Sets an array of textures on the engine to be used in the shader.
  761. * @param channel Name of the variable.
  762. * @param textures Textures to set.
  763. */
  764. Effect.prototype.setTextureArray = function (channel, textures) {
  765. if (this._samplers.indexOf(channel + "Ex") === -1) {
  766. var initialPos = this._samplers.indexOf(channel);
  767. for (var index = 1; index < textures.length; index++) {
  768. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  769. }
  770. }
  771. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  772. };
  773. /**
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the input texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /**
  782. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  783. * 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)
  784. * @param channel Name of the sampler variable.
  785. * @param postProcess Post process to get the output texture from.
  786. */
  787. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  788. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  789. };
  790. /** @hidden */
  791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  792. var cache = this._valueCache[uniformName];
  793. var flag = matrix.updateFlag;
  794. if (cache !== undefined && cache === flag) {
  795. return false;
  796. }
  797. this._valueCache[uniformName] = flag;
  798. return true;
  799. };
  800. /** @hidden */
  801. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. return changed;
  818. };
  819. /** @hidden */
  820. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y, z];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. if (cache[2] !== z) {
  837. cache[2] = z;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /** @hidden */
  843. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  844. var cache = this._valueCache[uniformName];
  845. if (!cache) {
  846. cache = [x, y, z, w];
  847. this._valueCache[uniformName] = cache;
  848. return true;
  849. }
  850. var changed = false;
  851. if (cache[0] !== x) {
  852. cache[0] = x;
  853. changed = true;
  854. }
  855. if (cache[1] !== y) {
  856. cache[1] = y;
  857. changed = true;
  858. }
  859. if (cache[2] !== z) {
  860. cache[2] = z;
  861. changed = true;
  862. }
  863. if (cache[3] !== w) {
  864. cache[3] = w;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /**
  870. * Binds a buffer to a uniform.
  871. * @param buffer Buffer to bind.
  872. * @param name Name of the uniform variable to bind to.
  873. */
  874. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  875. var bufferName = this._uniformBuffersNames[name];
  876. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  877. return;
  878. }
  879. Effect._baseCache[bufferName] = buffer;
  880. this._engine.bindUniformBufferBase(buffer, bufferName);
  881. };
  882. /**
  883. * Binds block to a uniform.
  884. * @param blockName Name of the block to bind.
  885. * @param index Index to bind.
  886. */
  887. Effect.prototype.bindUniformBlock = function (blockName, index) {
  888. this._engine.bindUniformBlock(this._program, blockName, index);
  889. };
  890. /**
  891. * Sets an interger value on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param value Value to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setInt = function (uniformName, value) {
  897. var cache = this._valueCache[uniformName];
  898. if (cache !== undefined && cache === value) {
  899. return this;
  900. }
  901. this._valueCache[uniformName] = value;
  902. this._engine.setInt(this.getUniform(uniformName), value);
  903. return this;
  904. };
  905. /**
  906. * Sets an int array on a uniform variable.
  907. * @param uniformName Name of the variable.
  908. * @param array array to be set.
  909. * @returns this effect.
  910. */
  911. Effect.prototype.setIntArray = function (uniformName, array) {
  912. this._valueCache[uniformName] = null;
  913. this._engine.setIntArray(this.getUniform(uniformName), array);
  914. return this;
  915. };
  916. /**
  917. * 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)
  918. * @param uniformName Name of the variable.
  919. * @param array array to be set.
  920. * @returns this effect.
  921. */
  922. Effect.prototype.setIntArray2 = function (uniformName, array) {
  923. this._valueCache[uniformName] = null;
  924. this._engine.setIntArray2(this.getUniform(uniformName), array);
  925. return this;
  926. };
  927. /**
  928. * 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)
  929. * @param uniformName Name of the variable.
  930. * @param array array to be set.
  931. * @returns this effect.
  932. */
  933. Effect.prototype.setIntArray3 = function (uniformName, array) {
  934. this._valueCache[uniformName] = null;
  935. this._engine.setIntArray3(this.getUniform(uniformName), array);
  936. return this;
  937. };
  938. /**
  939. * 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)
  940. * @param uniformName Name of the variable.
  941. * @param array array to be set.
  942. * @returns this effect.
  943. */
  944. Effect.prototype.setIntArray4 = function (uniformName, array) {
  945. this._valueCache[uniformName] = null;
  946. this._engine.setIntArray4(this.getUniform(uniformName), array);
  947. return this;
  948. };
  949. /**
  950. * Sets an float array on a uniform variable.
  951. * @param uniformName Name of the variable.
  952. * @param array array to be set.
  953. * @returns this effect.
  954. */
  955. Effect.prototype.setFloatArray = function (uniformName, array) {
  956. this._valueCache[uniformName] = null;
  957. this._engine.setFloatArray(this.getUniform(uniformName), array);
  958. return this;
  959. };
  960. /**
  961. * 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)
  962. * @param uniformName Name of the variable.
  963. * @param array array to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  967. this._valueCache[uniformName] = null;
  968. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  969. return this;
  970. };
  971. /**
  972. * 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)
  973. * @param uniformName Name of the variable.
  974. * @param array array to be set.
  975. * @returns this effect.
  976. */
  977. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  978. this._valueCache[uniformName] = null;
  979. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  980. return this;
  981. };
  982. /**
  983. * 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)
  984. * @param uniformName Name of the variable.
  985. * @param array array to be set.
  986. * @returns this effect.
  987. */
  988. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  989. this._valueCache[uniformName] = null;
  990. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  991. return this;
  992. };
  993. /**
  994. * Sets an array on a uniform variable.
  995. * @param uniformName Name of the variable.
  996. * @param array array to be set.
  997. * @returns this effect.
  998. */
  999. Effect.prototype.setArray = function (uniformName, array) {
  1000. this._valueCache[uniformName] = null;
  1001. this._engine.setArray(this.getUniform(uniformName), array);
  1002. return this;
  1003. };
  1004. /**
  1005. * 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)
  1006. * @param uniformName Name of the variable.
  1007. * @param array array to be set.
  1008. * @returns this effect.
  1009. */
  1010. Effect.prototype.setArray2 = function (uniformName, array) {
  1011. this._valueCache[uniformName] = null;
  1012. this._engine.setArray2(this.getUniform(uniformName), array);
  1013. return this;
  1014. };
  1015. /**
  1016. * 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)
  1017. * @param uniformName Name of the variable.
  1018. * @param array array to be set.
  1019. * @returns this effect.
  1020. */
  1021. Effect.prototype.setArray3 = function (uniformName, array) {
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setArray3(this.getUniform(uniformName), array);
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param array array to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setArray4 = function (uniformName, array) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setArray4(this.getUniform(uniformName), array);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets matrices on a uniform variable.
  1039. * @param uniformName Name of the variable.
  1040. * @param matrices matrices to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1044. if (!matrices) {
  1045. return this;
  1046. }
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets matrix on a uniform variable.
  1053. * @param uniformName Name of the variable.
  1054. * @param matrix matrix to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1058. if (this._cacheMatrix(uniformName, matrix)) {
  1059. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1060. }
  1061. return this;
  1062. };
  1063. /**
  1064. * 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)
  1065. * @param uniformName Name of the variable.
  1066. * @param matrix matrix to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1076. * @param uniformName Name of the variable.
  1077. * @param matrix matrix to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param value value to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setFloat = function (uniformName, value) {
  1092. var cache = this._valueCache[uniformName];
  1093. if (cache !== undefined && cache === value) {
  1094. return this;
  1095. }
  1096. this._valueCache[uniformName] = value;
  1097. this._engine.setFloat(this.getUniform(uniformName), value);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a boolean on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param bool value to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setBool = function (uniformName, bool) {
  1107. var cache = this._valueCache[uniformName];
  1108. if (cache !== undefined && cache === bool) {
  1109. return this;
  1110. }
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /** Class used to store color4 gradient */
  1460. var ColorGradient = /** @class */ (function () {
  1461. function ColorGradient() {
  1462. }
  1463. /**
  1464. * Will get a color picked randomly between color1 and color2.
  1465. * If color2 is undefined then color1 will be used
  1466. * @param result defines the target Color4 to store the result in
  1467. */
  1468. ColorGradient.prototype.getColorToRef = function (result) {
  1469. if (!this.color2) {
  1470. result.copyFrom(this.color1);
  1471. return;
  1472. }
  1473. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  1474. };
  1475. return ColorGradient;
  1476. }());
  1477. BABYLON.ColorGradient = ColorGradient;
  1478. /** Class used to store color 3 gradient */
  1479. var Color3Gradient = /** @class */ (function () {
  1480. function Color3Gradient() {
  1481. }
  1482. return Color3Gradient;
  1483. }());
  1484. BABYLON.Color3Gradient = Color3Gradient;
  1485. /** Class used to store factor gradient */
  1486. var FactorGradient = /** @class */ (function () {
  1487. function FactorGradient() {
  1488. }
  1489. /**
  1490. * Will get a number picked randomly between factor1 and factor2.
  1491. * If factor2 is undefined then factor1 will be used
  1492. * @returns the picked number
  1493. */
  1494. FactorGradient.prototype.getFactor = function () {
  1495. if (this.factor2 === undefined) {
  1496. return this.factor1;
  1497. }
  1498. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  1499. };
  1500. return FactorGradient;
  1501. }());
  1502. BABYLON.FactorGradient = FactorGradient;
  1503. /**
  1504. * @ignore
  1505. * Application error to support additional information when loading a file
  1506. */
  1507. var LoadFileError = /** @class */ (function (_super) {
  1508. __extends(LoadFileError, _super);
  1509. /**
  1510. * Creates a new LoadFileError
  1511. * @param message defines the message of the error
  1512. * @param request defines the optional XHR request
  1513. */
  1514. function LoadFileError(message,
  1515. /** defines the optional XHR request */
  1516. request) {
  1517. var _this = _super.call(this, message) || this;
  1518. _this.request = request;
  1519. _this.name = "LoadFileError";
  1520. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  1521. return _this;
  1522. }
  1523. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  1524. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  1525. // Polyfill for Object.setPrototypeOf if necessary.
  1526. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  1527. return LoadFileError;
  1528. }(Error));
  1529. BABYLON.LoadFileError = LoadFileError;
  1530. /**
  1531. * Class used to define a retry strategy when error happens while loading assets
  1532. */
  1533. var RetryStrategy = /** @class */ (function () {
  1534. function RetryStrategy() {
  1535. }
  1536. /**
  1537. * Function used to defines an exponential back off strategy
  1538. * @param maxRetries defines the maximum number of retries (3 by default)
  1539. * @param baseInterval defines the interval between retries
  1540. * @returns the strategy function to use
  1541. */
  1542. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  1543. if (maxRetries === void 0) { maxRetries = 3; }
  1544. if (baseInterval === void 0) { baseInterval = 500; }
  1545. return function (url, request, retryIndex) {
  1546. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  1547. return -1;
  1548. }
  1549. return Math.pow(2, retryIndex) * baseInterval;
  1550. };
  1551. };
  1552. return RetryStrategy;
  1553. }());
  1554. BABYLON.RetryStrategy = RetryStrategy;
  1555. // Screenshots
  1556. var screenshotCanvas;
  1557. var cloneValue = function (source, destinationObject) {
  1558. if (!source) {
  1559. return null;
  1560. }
  1561. if (source instanceof BABYLON.Mesh) {
  1562. return null;
  1563. }
  1564. if (source instanceof BABYLON.SubMesh) {
  1565. return source.clone(destinationObject);
  1566. }
  1567. else if (source.clone) {
  1568. return source.clone();
  1569. }
  1570. return null;
  1571. };
  1572. /**
  1573. * Class containing a set of static utilities functions
  1574. */
  1575. var Tools = /** @class */ (function () {
  1576. function Tools() {
  1577. }
  1578. /**
  1579. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  1580. * @param u defines the coordinate on X axis
  1581. * @param v defines the coordinate on Y axis
  1582. * @param width defines the width of the source data
  1583. * @param height defines the height of the source data
  1584. * @param pixels defines the source byte array
  1585. * @param color defines the output color
  1586. */
  1587. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  1588. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  1589. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  1590. var position = (wrappedU + wrappedV * width) * 4;
  1591. color.r = pixels[position] / 255;
  1592. color.g = pixels[position + 1] / 255;
  1593. color.b = pixels[position + 2] / 255;
  1594. color.a = pixels[position + 3] / 255;
  1595. };
  1596. /**
  1597. * Interpolates between a and b via alpha
  1598. * @param a The lower value (returned when alpha = 0)
  1599. * @param b The upper value (returned when alpha = 1)
  1600. * @param alpha The interpolation-factor
  1601. * @return The mixed value
  1602. */
  1603. Tools.Mix = function (a, b, alpha) {
  1604. return a * (1 - alpha) + b * alpha;
  1605. };
  1606. /**
  1607. * Tries to instantiate a new object from a given class name
  1608. * @param className defines the class name to instantiate
  1609. * @returns the new object or null if the system was not able to do the instantiation
  1610. */
  1611. Tools.Instantiate = function (className) {
  1612. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  1613. return Tools.RegisteredExternalClasses[className];
  1614. }
  1615. var arr = className.split(".");
  1616. var fn = (window || this);
  1617. for (var i = 0, len = arr.length; i < len; i++) {
  1618. fn = fn[arr[i]];
  1619. }
  1620. if (typeof fn !== "function") {
  1621. return null;
  1622. }
  1623. return fn;
  1624. };
  1625. /**
  1626. * Provides a slice function that will work even on IE
  1627. * @param data defines the array to slice
  1628. * @param start defines the start of the data (optional)
  1629. * @param end defines the end of the data (optional)
  1630. * @returns the new sliced array
  1631. */
  1632. Tools.Slice = function (data, start, end) {
  1633. if (data.slice) {
  1634. return data.slice(start, end);
  1635. }
  1636. return Array.prototype.slice.call(data, start, end);
  1637. };
  1638. /**
  1639. * Polyfill for setImmediate
  1640. * @param action defines the action to execute after the current execution block
  1641. */
  1642. Tools.SetImmediate = function (action) {
  1643. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  1644. window.setImmediate(action);
  1645. }
  1646. else {
  1647. setTimeout(action, 1);
  1648. }
  1649. };
  1650. /**
  1651. * Function indicating if a number is an exponent of 2
  1652. * @param value defines the value to test
  1653. * @returns true if the value is an exponent of 2
  1654. */
  1655. Tools.IsExponentOfTwo = function (value) {
  1656. var count = 1;
  1657. do {
  1658. count *= 2;
  1659. } while (count < value);
  1660. return count === value;
  1661. };
  1662. /**
  1663. * Returns the nearest 32-bit single precision float representation of a Number
  1664. * @param value A Number. If the parameter is of a different type, it will get converted
  1665. * to a number or to NaN if it cannot be converted
  1666. * @returns number
  1667. */
  1668. Tools.FloatRound = function (value) {
  1669. if (Math.fround) {
  1670. return Math.fround(value);
  1671. }
  1672. return (Tools._tmpFloatArray[0] = value);
  1673. };
  1674. /**
  1675. * Find the next highest power of two.
  1676. * @param x Number to start search from.
  1677. * @return Next highest power of two.
  1678. */
  1679. Tools.CeilingPOT = function (x) {
  1680. x--;
  1681. x |= x >> 1;
  1682. x |= x >> 2;
  1683. x |= x >> 4;
  1684. x |= x >> 8;
  1685. x |= x >> 16;
  1686. x++;
  1687. return x;
  1688. };
  1689. /**
  1690. * Find the next lowest power of two.
  1691. * @param x Number to start search from.
  1692. * @return Next lowest power of two.
  1693. */
  1694. Tools.FloorPOT = function (x) {
  1695. x = x | (x >> 1);
  1696. x = x | (x >> 2);
  1697. x = x | (x >> 4);
  1698. x = x | (x >> 8);
  1699. x = x | (x >> 16);
  1700. return x - (x >> 1);
  1701. };
  1702. /**
  1703. * Find the nearest power of two.
  1704. * @param x Number to start search from.
  1705. * @return Next nearest power of two.
  1706. */
  1707. Tools.NearestPOT = function (x) {
  1708. var c = Tools.CeilingPOT(x);
  1709. var f = Tools.FloorPOT(x);
  1710. return (c - x) > (x - f) ? f : c;
  1711. };
  1712. /**
  1713. * Get the closest exponent of two
  1714. * @param value defines the value to approximate
  1715. * @param max defines the maximum value to return
  1716. * @param mode defines how to define the closest value
  1717. * @returns closest exponent of two of the given value
  1718. */
  1719. Tools.GetExponentOfTwo = function (value, max, mode) {
  1720. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  1721. var pot;
  1722. switch (mode) {
  1723. case BABYLON.Engine.SCALEMODE_FLOOR:
  1724. pot = Tools.FloorPOT(value);
  1725. break;
  1726. case BABYLON.Engine.SCALEMODE_NEAREST:
  1727. pot = Tools.NearestPOT(value);
  1728. break;
  1729. case BABYLON.Engine.SCALEMODE_CEILING:
  1730. default:
  1731. pot = Tools.CeilingPOT(value);
  1732. break;
  1733. }
  1734. return Math.min(pot, max);
  1735. };
  1736. /**
  1737. * Extracts the filename from a path
  1738. * @param path defines the path to use
  1739. * @returns the filename
  1740. */
  1741. Tools.GetFilename = function (path) {
  1742. var index = path.lastIndexOf("/");
  1743. if (index < 0) {
  1744. return path;
  1745. }
  1746. return path.substring(index + 1);
  1747. };
  1748. /**
  1749. * Extracts the "folder" part of a path (everything before the filename).
  1750. * @param uri The URI to extract the info from
  1751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  1752. * @returns The "folder" part of the path
  1753. */
  1754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  1755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  1756. var index = uri.lastIndexOf("/");
  1757. if (index < 0) {
  1758. if (returnUnchangedIfNoSlash) {
  1759. return uri;
  1760. }
  1761. return "";
  1762. }
  1763. return uri.substring(0, index + 1);
  1764. };
  1765. /**
  1766. * Extracts text content from a DOM element hierarchy
  1767. * @param element defines the root element
  1768. * @returns a string
  1769. */
  1770. Tools.GetDOMTextContent = function (element) {
  1771. var result = "";
  1772. var child = element.firstChild;
  1773. while (child) {
  1774. if (child.nodeType === 3) {
  1775. result += child.textContent;
  1776. }
  1777. child = (child.nextSibling);
  1778. }
  1779. return result;
  1780. };
  1781. /**
  1782. * Convert an angle in radians to degrees
  1783. * @param angle defines the angle to convert
  1784. * @returns the angle in degrees
  1785. */
  1786. Tools.ToDegrees = function (angle) {
  1787. return angle * 180 / Math.PI;
  1788. };
  1789. /**
  1790. * Convert an angle in degrees to radians
  1791. * @param angle defines the angle to convert
  1792. * @returns the angle in radians
  1793. */
  1794. Tools.ToRadians = function (angle) {
  1795. return angle * Math.PI / 180;
  1796. };
  1797. /**
  1798. * Encode a buffer to a base64 string
  1799. * @param buffer defines the buffer to encode
  1800. * @returns the encoded string
  1801. */
  1802. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  1803. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1804. var output = "";
  1805. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1806. var i = 0;
  1807. var bytes = new Uint8Array(buffer);
  1808. while (i < bytes.length) {
  1809. chr1 = bytes[i++];
  1810. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  1811. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  1812. enc1 = chr1 >> 2;
  1813. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1814. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1815. enc4 = chr3 & 63;
  1816. if (isNaN(chr2)) {
  1817. enc3 = enc4 = 64;
  1818. }
  1819. else if (isNaN(chr3)) {
  1820. enc4 = 64;
  1821. }
  1822. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1823. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1824. }
  1825. return "data:image/png;base64," + output;
  1826. };
  1827. /**
  1828. * Extracts minimum and maximum values from a list of indexed positions
  1829. * @param positions defines the positions to use
  1830. * @param indices defines the indices to the positions
  1831. * @param indexStart defines the start index
  1832. * @param indexCount defines the end index
  1833. * @param bias defines bias value to add to the result
  1834. * @return minimum and maximum values
  1835. */
  1836. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  1837. if (bias === void 0) { bias = null; }
  1838. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1839. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1840. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1841. var offset = indices[index] * 3;
  1842. var x = positions[offset];
  1843. var y = positions[offset + 1];
  1844. var z = positions[offset + 2];
  1845. minimum.minimizeInPlaceFromFloats(x, y, z);
  1846. maximum.maximizeInPlaceFromFloats(x, y, z);
  1847. }
  1848. if (bias) {
  1849. minimum.x -= minimum.x * bias.x + bias.y;
  1850. minimum.y -= minimum.y * bias.x + bias.y;
  1851. minimum.z -= minimum.z * bias.x + bias.y;
  1852. maximum.x += maximum.x * bias.x + bias.y;
  1853. maximum.y += maximum.y * bias.x + bias.y;
  1854. maximum.z += maximum.z * bias.x + bias.y;
  1855. }
  1856. return {
  1857. minimum: minimum,
  1858. maximum: maximum
  1859. };
  1860. };
  1861. /**
  1862. * Extracts minimum and maximum values from a list of positions
  1863. * @param positions defines the positions to use
  1864. * @param start defines the start index in the positions array
  1865. * @param count defines the number of positions to handle
  1866. * @param bias defines bias value to add to the result
  1867. * @param stride defines the stride size to use (distance between two positions in the positions array)
  1868. * @return minimum and maximum values
  1869. */
  1870. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  1871. if (bias === void 0) { bias = null; }
  1872. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1873. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1874. if (!stride) {
  1875. stride = 3;
  1876. }
  1877. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  1878. var x = positions[offset];
  1879. var y = positions[offset + 1];
  1880. var z = positions[offset + 2];
  1881. minimum.minimizeInPlaceFromFloats(x, y, z);
  1882. maximum.maximizeInPlaceFromFloats(x, y, z);
  1883. }
  1884. if (bias) {
  1885. minimum.x -= minimum.x * bias.x + bias.y;
  1886. minimum.y -= minimum.y * bias.x + bias.y;
  1887. minimum.z -= minimum.z * bias.x + bias.y;
  1888. maximum.x += maximum.x * bias.x + bias.y;
  1889. maximum.y += maximum.y * bias.x + bias.y;
  1890. maximum.z += maximum.z * bias.x + bias.y;
  1891. }
  1892. return {
  1893. minimum: minimum,
  1894. maximum: maximum
  1895. };
  1896. };
  1897. /**
  1898. * Returns an array if obj is not an array
  1899. * @param obj defines the object to evaluate as an array
  1900. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  1901. * @returns either obj directly if obj is an array or a new array containing obj
  1902. */
  1903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1904. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  1905. return null;
  1906. }
  1907. return Array.isArray(obj) ? obj : [obj];
  1908. };
  1909. /**
  1910. * Returns an array of the given size filled with element built from the given constructor and the paramters
  1911. * @param size the number of element to construct and put in the array
  1912. * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
  1913. * @returns a new array filled with new objects
  1914. */
  1915. Tools.BuildArray = function (size, itemBuilder) {
  1916. var a = [];
  1917. for (var i = 0; i < size; ++i) {
  1918. a.push(itemBuilder());
  1919. }
  1920. return a;
  1921. };
  1922. /**
  1923. * Gets the pointer prefix to use
  1924. * @returns "pointer" if touch is enabled. Else returns "mouse"
  1925. */
  1926. Tools.GetPointerPrefix = function () {
  1927. var eventPrefix = "pointer";
  1928. // Check if pointer events are supported
  1929. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  1930. eventPrefix = "mouse";
  1931. }
  1932. return eventPrefix;
  1933. };
  1934. /**
  1935. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  1936. * @param func - the function to be called
  1937. * @param requester - the object that will request the next frame. Falls back to window.
  1938. * @returns frame number
  1939. */
  1940. Tools.QueueNewFrame = function (func, requester) {
  1941. if (!Tools.IsWindowObjectExist()) {
  1942. return setTimeout(func, 16);
  1943. }
  1944. if (!requester) {
  1945. requester = window;
  1946. }
  1947. if (requester.requestAnimationFrame) {
  1948. return requester.requestAnimationFrame(func);
  1949. }
  1950. else if (requester.msRequestAnimationFrame) {
  1951. return requester.msRequestAnimationFrame(func);
  1952. }
  1953. else if (requester.webkitRequestAnimationFrame) {
  1954. return requester.webkitRequestAnimationFrame(func);
  1955. }
  1956. else if (requester.mozRequestAnimationFrame) {
  1957. return requester.mozRequestAnimationFrame(func);
  1958. }
  1959. else if (requester.oRequestAnimationFrame) {
  1960. return requester.oRequestAnimationFrame(func);
  1961. }
  1962. else {
  1963. return window.setTimeout(func, 16);
  1964. }
  1965. };
  1966. /**
  1967. * Ask the browser to promote the current element to fullscreen rendering mode
  1968. * @param element defines the DOM element to promote
  1969. */
  1970. Tools.RequestFullscreen = function (element) {
  1971. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  1972. if (!requestFunction) {
  1973. return;
  1974. }
  1975. requestFunction.call(element);
  1976. };
  1977. /**
  1978. * Asks the browser to exit fullscreen mode
  1979. */
  1980. Tools.ExitFullscreen = function () {
  1981. if (document.exitFullscreen) {
  1982. document.exitFullscreen();
  1983. }
  1984. else if (document.mozCancelFullScreen) {
  1985. document.mozCancelFullScreen();
  1986. }
  1987. else if (document.webkitCancelFullScreen) {
  1988. document.webkitCancelFullScreen();
  1989. }
  1990. else if (document.msCancelFullScreen) {
  1991. document.msCancelFullScreen();
  1992. }
  1993. };
  1994. /**
  1995. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  1996. * @param url define the url we are trying
  1997. * @param element define the dom element where to configure the cors policy
  1998. */
  1999. Tools.SetCorsBehavior = function (url, element) {
  2000. if (url && url.indexOf("data:") === 0) {
  2001. return;
  2002. }
  2003. if (Tools.CorsBehavior) {
  2004. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  2005. element.crossOrigin = Tools.CorsBehavior;
  2006. }
  2007. else {
  2008. var result = Tools.CorsBehavior(url);
  2009. if (result) {
  2010. element.crossOrigin = result;
  2011. }
  2012. }
  2013. }
  2014. };
  2015. // External files
  2016. /**
  2017. * Removes unwanted characters from an url
  2018. * @param url defines the url to clean
  2019. * @returns the cleaned url
  2020. */
  2021. Tools.CleanUrl = function (url) {
  2022. url = url.replace(/#/mg, "%23");
  2023. return url;
  2024. };
  2025. /**
  2026. * Loads an image as an HTMLImageElement.
  2027. * @param input url string, ArrayBuffer, or Blob to load
  2028. * @param onLoad callback called when the image successfully loads
  2029. * @param onError callback called when the image fails to load
  2030. * @param offlineProvider offline provider for caching
  2031. * @returns the HTMLImageElement of the loaded image
  2032. */
  2033. Tools.LoadImage = function (input, onLoad, onError, offlineProvider) {
  2034. var url;
  2035. var usingObjectURL = false;
  2036. if (input instanceof ArrayBuffer) {
  2037. url = URL.createObjectURL(new Blob([input]));
  2038. usingObjectURL = true;
  2039. }
  2040. else if (input instanceof Blob) {
  2041. url = URL.createObjectURL(input);
  2042. usingObjectURL = true;
  2043. }
  2044. else {
  2045. url = Tools.CleanUrl(input);
  2046. url = Tools.PreprocessUrl(input);
  2047. }
  2048. var img = new Image();
  2049. Tools.SetCorsBehavior(url, img);
  2050. var loadHandler = function () {
  2051. if (usingObjectURL && img.src) {
  2052. URL.revokeObjectURL(img.src);
  2053. }
  2054. img.removeEventListener("load", loadHandler);
  2055. img.removeEventListener("error", errorHandler);
  2056. onLoad(img);
  2057. };
  2058. var errorHandler = function (err) {
  2059. if (usingObjectURL && img.src) {
  2060. URL.revokeObjectURL(img.src);
  2061. }
  2062. img.removeEventListener("load", loadHandler);
  2063. img.removeEventListener("error", errorHandler);
  2064. Tools.Error("Error while trying to load image: " + input);
  2065. if (onError) {
  2066. onError("Error while trying to load image: " + input, err);
  2067. }
  2068. };
  2069. img.addEventListener("load", loadHandler);
  2070. img.addEventListener("error", errorHandler);
  2071. var noOfflineSupport = function () {
  2072. img.src = url;
  2073. };
  2074. var loadFromOfflineSupport = function () {
  2075. if (offlineProvider) {
  2076. offlineProvider.loadImage(url, img);
  2077. }
  2078. };
  2079. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  2080. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  2081. }
  2082. else {
  2083. if (url.indexOf("file:") !== -1) {
  2084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  2085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  2086. try {
  2087. var blobURL;
  2088. try {
  2089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2090. }
  2091. catch (ex) {
  2092. // Chrome doesn't support oneTimeOnly parameter
  2093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2094. }
  2095. img.src = blobURL;
  2096. usingObjectURL = true;
  2097. }
  2098. catch (e) {
  2099. img.src = "";
  2100. }
  2101. return img;
  2102. }
  2103. }
  2104. noOfflineSupport();
  2105. }
  2106. return img;
  2107. };
  2108. /**
  2109. * Loads a file
  2110. * @param url url string, ArrayBuffer, or Blob to load
  2111. * @param onSuccess callback called when the file successfully loads
  2112. * @param onProgress callback called while file is loading (if the server supports this mode)
  2113. * @param offlineProvider defines the offline provider for caching
  2114. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  2115. * @param onError callback called when the file fails to load
  2116. * @returns a file request object
  2117. */
  2118. Tools.LoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  2119. url = Tools.CleanUrl(url);
  2120. url = Tools.PreprocessUrl(url);
  2121. // If file and file input are set
  2122. if (url.indexOf("file:") !== -1) {
  2123. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  2124. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  2125. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  2126. }
  2127. }
  2128. var loadUrl = Tools.BaseUrl + url;
  2129. var aborted = false;
  2130. var fileRequest = {
  2131. onCompleteObservable: new BABYLON.Observable(),
  2132. abort: function () { return aborted = true; },
  2133. };
  2134. var requestFile = function () {
  2135. var request = new XMLHttpRequest();
  2136. var retryHandle = null;
  2137. fileRequest.abort = function () {
  2138. aborted = true;
  2139. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  2140. request.abort();
  2141. }
  2142. if (retryHandle !== null) {
  2143. clearTimeout(retryHandle);
  2144. retryHandle = null;
  2145. }
  2146. };
  2147. var retryLoop = function (retryIndex) {
  2148. request.open('GET', loadUrl, true);
  2149. if (useArrayBuffer) {
  2150. request.responseType = "arraybuffer";
  2151. }
  2152. if (onProgress) {
  2153. request.addEventListener("progress", onProgress);
  2154. }
  2155. var onLoadEnd = function () {
  2156. request.removeEventListener("loadend", onLoadEnd);
  2157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2158. fileRequest.onCompleteObservable.clear();
  2159. };
  2160. request.addEventListener("loadend", onLoadEnd);
  2161. var onReadyStateChange = function () {
  2162. if (aborted) {
  2163. return;
  2164. }
  2165. // In case of undefined state in some browsers.
  2166. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  2167. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  2168. request.removeEventListener("readystatechange", onReadyStateChange);
  2169. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  2170. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  2171. return;
  2172. }
  2173. var retryStrategy = Tools.DefaultRetryStrategy;
  2174. if (retryStrategy) {
  2175. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  2176. if (waitTime !== -1) {
  2177. // Prevent the request from completing for retry.
  2178. request.removeEventListener("loadend", onLoadEnd);
  2179. request = new XMLHttpRequest();
  2180. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  2181. return;
  2182. }
  2183. }
  2184. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  2185. if (onError) {
  2186. onError(request, e);
  2187. }
  2188. else {
  2189. throw e;
  2190. }
  2191. }
  2192. };
  2193. request.addEventListener("readystatechange", onReadyStateChange);
  2194. request.send();
  2195. };
  2196. retryLoop(0);
  2197. };
  2198. // Caching all files
  2199. if (offlineProvider && offlineProvider.enableSceneOffline) {
  2200. var noOfflineSupport_1 = function (request) {
  2201. if (request && request.status > 400) {
  2202. if (onError) {
  2203. onError(request);
  2204. }
  2205. }
  2206. else {
  2207. if (!aborted) {
  2208. requestFile();
  2209. }
  2210. }
  2211. };
  2212. var loadFromOfflineSupport = function () {
  2213. // TODO: database needs to support aborting and should return a IFileRequest
  2214. if (aborted) {
  2215. return;
  2216. }
  2217. if (offlineProvider) {
  2218. offlineProvider.loadFile(url, function (data) {
  2219. if (!aborted) {
  2220. onSuccess(data);
  2221. }
  2222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2223. }, onProgress ? function (event) {
  2224. if (!aborted) {
  2225. onProgress(event);
  2226. }
  2227. } : undefined, noOfflineSupport_1, useArrayBuffer);
  2228. }
  2229. };
  2230. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport_1);
  2231. }
  2232. else {
  2233. requestFile();
  2234. }
  2235. return fileRequest;
  2236. };
  2237. /**
  2238. * Load a script (identified by an url). When the url returns, the
  2239. * content of this file is added into a new script element, attached to the DOM (body element)
  2240. * @param scriptUrl defines the url of the script to laod
  2241. * @param onSuccess defines the callback called when the script is loaded
  2242. * @param onError defines the callback to call if an error occurs
  2243. */
  2244. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  2245. if (!Tools.IsWindowObjectExist()) {
  2246. return;
  2247. }
  2248. var head = document.getElementsByTagName('head')[0];
  2249. var script = document.createElement('script');
  2250. script.type = 'text/javascript';
  2251. script.src = scriptUrl;
  2252. script.onload = function () {
  2253. if (onSuccess) {
  2254. onSuccess();
  2255. }
  2256. };
  2257. script.onerror = function (e) {
  2258. if (onError) {
  2259. onError("Unable to load script '" + scriptUrl + "'", e);
  2260. }
  2261. };
  2262. head.appendChild(script);
  2263. };
  2264. /**
  2265. * Loads a file from a blob
  2266. * @param fileToLoad defines the blob to use
  2267. * @param callback defines the callback to call when data is loaded
  2268. * @param progressCallback defines the callback to call during loading process
  2269. * @returns a file request object
  2270. */
  2271. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2272. var reader = new FileReader();
  2273. var request = {
  2274. onCompleteObservable: new BABYLON.Observable(),
  2275. abort: function () { return reader.abort(); },
  2276. };
  2277. reader.onloadend = function (e) {
  2278. request.onCompleteObservable.notifyObservers(request);
  2279. };
  2280. reader.onload = function (e) {
  2281. //target doesn't have result from ts 1.3
  2282. callback(e.target['result']);
  2283. };
  2284. reader.onprogress = progressCallback;
  2285. reader.readAsDataURL(fileToLoad);
  2286. return request;
  2287. };
  2288. /**
  2289. * Loads a file
  2290. * @param fileToLoad defines the file to load
  2291. * @param callback defines the callback to call when data is loaded
  2292. * @param progressCallBack defines the callback to call during loading process
  2293. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  2294. * @returns a file request object
  2295. */
  2296. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2297. var reader = new FileReader();
  2298. var request = {
  2299. onCompleteObservable: new BABYLON.Observable(),
  2300. abort: function () { return reader.abort(); },
  2301. };
  2302. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  2303. reader.onerror = function (e) {
  2304. Tools.Log("Error while reading file: " + fileToLoad.name);
  2305. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  2306. };
  2307. reader.onload = function (e) {
  2308. //target doesn't have result from ts 1.3
  2309. callback(e.target['result']);
  2310. };
  2311. if (progressCallBack) {
  2312. reader.onprogress = progressCallBack;
  2313. }
  2314. if (!useArrayBuffer) {
  2315. // Asynchronous read
  2316. reader.readAsText(fileToLoad);
  2317. }
  2318. else {
  2319. reader.readAsArrayBuffer(fileToLoad);
  2320. }
  2321. return request;
  2322. };
  2323. /**
  2324. * Creates a data url from a given string content
  2325. * @param content defines the content to convert
  2326. * @returns the new data url link
  2327. */
  2328. Tools.FileAsURL = function (content) {
  2329. var fileBlob = new Blob([content]);
  2330. var url = window.URL || window.webkitURL;
  2331. var link = url.createObjectURL(fileBlob);
  2332. return link;
  2333. };
  2334. /**
  2335. * Format the given number to a specific decimal format
  2336. * @param value defines the number to format
  2337. * @param decimals defines the number of decimals to use
  2338. * @returns the formatted string
  2339. */
  2340. Tools.Format = function (value, decimals) {
  2341. if (decimals === void 0) { decimals = 2; }
  2342. return value.toFixed(decimals);
  2343. };
  2344. /**
  2345. * Checks if a given vector is inside a specific range
  2346. * @param v defines the vector to test
  2347. * @param min defines the minimum range
  2348. * @param max defines the maximum range
  2349. */
  2350. Tools.CheckExtends = function (v, min, max) {
  2351. min.minimizeInPlace(v);
  2352. max.maximizeInPlace(v);
  2353. };
  2354. /**
  2355. * Tries to copy an object by duplicating every property
  2356. * @param source defines the source object
  2357. * @param destination defines the target object
  2358. * @param doNotCopyList defines a list of properties to avoid
  2359. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  2360. */
  2361. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2362. for (var prop in source) {
  2363. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2364. continue;
  2365. }
  2366. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2367. continue;
  2368. }
  2369. var sourceValue = source[prop];
  2370. var typeOfSourceValue = typeof sourceValue;
  2371. if (typeOfSourceValue === "function") {
  2372. continue;
  2373. }
  2374. try {
  2375. if (typeOfSourceValue === "object") {
  2376. if (sourceValue instanceof Array) {
  2377. destination[prop] = [];
  2378. if (sourceValue.length > 0) {
  2379. if (typeof sourceValue[0] == "object") {
  2380. for (var index = 0; index < sourceValue.length; index++) {
  2381. var clonedValue = cloneValue(sourceValue[index], destination);
  2382. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  2383. destination[prop].push(clonedValue);
  2384. }
  2385. }
  2386. }
  2387. else {
  2388. destination[prop] = sourceValue.slice(0);
  2389. }
  2390. }
  2391. }
  2392. else {
  2393. destination[prop] = cloneValue(sourceValue, destination);
  2394. }
  2395. }
  2396. else {
  2397. destination[prop] = sourceValue;
  2398. }
  2399. }
  2400. catch (e) {
  2401. // Just ignore error (it could be because of a read-only property)
  2402. }
  2403. }
  2404. };
  2405. /**
  2406. * Gets a boolean indicating if the given object has no own property
  2407. * @param obj defines the object to test
  2408. * @returns true if object has no own property
  2409. */
  2410. Tools.IsEmpty = function (obj) {
  2411. for (var i in obj) {
  2412. if (obj.hasOwnProperty(i)) {
  2413. return false;
  2414. }
  2415. }
  2416. return true;
  2417. };
  2418. /**
  2419. * Function used to register events at window level
  2420. * @param events defines the events to register
  2421. */
  2422. Tools.RegisterTopRootEvents = function (events) {
  2423. for (var index = 0; index < events.length; index++) {
  2424. var event = events[index];
  2425. window.addEventListener(event.name, event.handler, false);
  2426. try {
  2427. if (window.parent) {
  2428. window.parent.addEventListener(event.name, event.handler, false);
  2429. }
  2430. }
  2431. catch (e) {
  2432. // Silently fails...
  2433. }
  2434. }
  2435. };
  2436. /**
  2437. * Function used to unregister events from window level
  2438. * @param events defines the events to unregister
  2439. */
  2440. Tools.UnregisterTopRootEvents = function (events) {
  2441. for (var index = 0; index < events.length; index++) {
  2442. var event = events[index];
  2443. window.removeEventListener(event.name, event.handler);
  2444. try {
  2445. if (window.parent) {
  2446. window.parent.removeEventListener(event.name, event.handler);
  2447. }
  2448. }
  2449. catch (e) {
  2450. // Silently fails...
  2451. }
  2452. }
  2453. };
  2454. /**
  2455. * Dumps the current bound framebuffer
  2456. * @param width defines the rendering width
  2457. * @param height defines the rendering height
  2458. * @param engine defines the hosting engine
  2459. * @param successCallback defines the callback triggered once the data are available
  2460. * @param mimeType defines the mime type of the result
  2461. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  2462. */
  2463. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  2464. if (mimeType === void 0) { mimeType = "image/png"; }
  2465. // Read the contents of the framebuffer
  2466. var numberOfChannelsByLine = width * 4;
  2467. var halfHeight = height / 2;
  2468. //Reading datas from WebGL
  2469. var data = engine.readPixels(0, 0, width, height);
  2470. //To flip image on Y axis.
  2471. for (var i = 0; i < halfHeight; i++) {
  2472. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2473. var currentCell = j + i * numberOfChannelsByLine;
  2474. var targetLine = height - i - 1;
  2475. var targetCell = j + targetLine * numberOfChannelsByLine;
  2476. var temp = data[currentCell];
  2477. data[currentCell] = data[targetCell];
  2478. data[targetCell] = temp;
  2479. }
  2480. }
  2481. // Create a 2D canvas to store the result
  2482. if (!screenshotCanvas) {
  2483. screenshotCanvas = document.createElement('canvas');
  2484. }
  2485. screenshotCanvas.width = width;
  2486. screenshotCanvas.height = height;
  2487. var context = screenshotCanvas.getContext('2d');
  2488. if (context) {
  2489. // Copy the pixels to a 2D canvas
  2490. var imageData = context.createImageData(width, height);
  2491. var castData = (imageData.data);
  2492. castData.set(data);
  2493. context.putImageData(imageData, 0, 0);
  2494. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  2495. }
  2496. };
  2497. /**
  2498. * Converts the canvas data to blob.
  2499. * This acts as a polyfill for browsers not supporting the to blob function.
  2500. * @param canvas Defines the canvas to extract the data from
  2501. * @param successCallback Defines the callback triggered once the data are available
  2502. * @param mimeType Defines the mime type of the result
  2503. */
  2504. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  2505. if (mimeType === void 0) { mimeType = "image/png"; }
  2506. // We need HTMLCanvasElement.toBlob for HD screenshots
  2507. if (!canvas.toBlob) {
  2508. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  2509. canvas.toBlob = function (callback, type, quality) {
  2510. var _this = this;
  2511. setTimeout(function () {
  2512. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  2513. for (var i = 0; i < len; i++) {
  2514. arr[i] = binStr.charCodeAt(i);
  2515. }
  2516. callback(new Blob([arr]));
  2517. });
  2518. };
  2519. }
  2520. canvas.toBlob(function (blob) {
  2521. successCallback(blob);
  2522. }, mimeType);
  2523. };
  2524. /**
  2525. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  2526. * @param successCallback defines the callback triggered once the data are available
  2527. * @param mimeType defines the mime type of the result
  2528. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  2529. */
  2530. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  2531. if (mimeType === void 0) { mimeType = "image/png"; }
  2532. if (successCallback) {
  2533. var base64Image = screenshotCanvas.toDataURL(mimeType);
  2534. successCallback(base64Image);
  2535. }
  2536. else {
  2537. this.ToBlob(screenshotCanvas, function (blob) {
  2538. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2539. if (("download" in document.createElement("a"))) {
  2540. if (!fileName) {
  2541. var date = new Date();
  2542. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  2543. fileName = "screenshot_" + stringDate + ".png";
  2544. }
  2545. Tools.Download(blob, fileName);
  2546. }
  2547. else {
  2548. var url = URL.createObjectURL(blob);
  2549. var newWindow = window.open("");
  2550. if (!newWindow) {
  2551. return;
  2552. }
  2553. var img = newWindow.document.createElement("img");
  2554. img.onload = function () {
  2555. // no longer need to read the blob so it's revoked
  2556. URL.revokeObjectURL(url);
  2557. };
  2558. img.src = url;
  2559. newWindow.document.body.appendChild(img);
  2560. }
  2561. }, mimeType);
  2562. }
  2563. };
  2564. /**
  2565. * Downloads a blob in the browser
  2566. * @param blob defines the blob to download
  2567. * @param fileName defines the name of the downloaded file
  2568. */
  2569. Tools.Download = function (blob, fileName) {
  2570. if (navigator && navigator.msSaveBlob) {
  2571. navigator.msSaveBlob(blob, fileName);
  2572. return;
  2573. }
  2574. var url = window.URL.createObjectURL(blob);
  2575. var a = document.createElement("a");
  2576. document.body.appendChild(a);
  2577. a.style.display = "none";
  2578. a.href = url;
  2579. a.download = fileName;
  2580. a.addEventListener("click", function () {
  2581. if (a.parentElement) {
  2582. a.parentElement.removeChild(a);
  2583. }
  2584. });
  2585. a.click();
  2586. window.URL.revokeObjectURL(url);
  2587. };
  2588. /**
  2589. * Captures a screenshot of the current rendering
  2590. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2591. * @param engine defines the rendering engine
  2592. * @param camera defines the source camera
  2593. * @param size This parameter can be set to a single number or to an object with the
  2594. * following (optional) properties: precision, width, height. If a single number is passed,
  2595. * it will be used for both width and height. If an object is passed, the screenshot size
  2596. * will be derived from the parameters. The precision property is a multiplier allowing
  2597. * rendering at a higher or lower resolution
  2598. * @param successCallback defines the callback receives a single parameter which contains the
  2599. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2600. * src parameter of an <img> to display it
  2601. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  2602. * Check your browser for supported MIME types
  2603. */
  2604. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  2605. if (mimeType === void 0) { mimeType = "image/png"; }
  2606. var width;
  2607. var height;
  2608. // If a precision value is specified
  2609. if (size.precision) {
  2610. width = Math.round(engine.getRenderWidth() * size.precision);
  2611. height = Math.round(width / engine.getAspectRatio(camera));
  2612. }
  2613. else if (size.width && size.height) {
  2614. width = size.width;
  2615. height = size.height;
  2616. }
  2617. //If passing only width, computing height to keep display canvas ratio.
  2618. else if (size.width && !size.height) {
  2619. width = size.width;
  2620. height = Math.round(width / engine.getAspectRatio(camera));
  2621. }
  2622. //If passing only height, computing width to keep display canvas ratio.
  2623. else if (size.height && !size.width) {
  2624. height = size.height;
  2625. width = Math.round(height * engine.getAspectRatio(camera));
  2626. }
  2627. //Assuming here that "size" parameter is a number
  2628. else if (!isNaN(size)) {
  2629. height = size;
  2630. width = size;
  2631. }
  2632. else {
  2633. Tools.Error("Invalid 'size' parameter !");
  2634. return;
  2635. }
  2636. if (!screenshotCanvas) {
  2637. screenshotCanvas = document.createElement('canvas');
  2638. }
  2639. screenshotCanvas.width = width;
  2640. screenshotCanvas.height = height;
  2641. var renderContext = screenshotCanvas.getContext("2d");
  2642. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  2643. var newWidth = width;
  2644. var newHeight = newWidth / ratio;
  2645. if (newHeight > height) {
  2646. newHeight = height;
  2647. newWidth = newHeight * ratio;
  2648. }
  2649. var offsetX = Math.max(0, width - newWidth) / 2;
  2650. var offsetY = Math.max(0, height - newHeight) / 2;
  2651. var renderingCanvas = engine.getRenderingCanvas();
  2652. if (renderContext && renderingCanvas) {
  2653. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  2654. }
  2655. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  2656. };
  2657. /**
  2658. * Generates an image screenshot from the specified camera.
  2659. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2660. * @param engine The engine to use for rendering
  2661. * @param camera The camera to use for rendering
  2662. * @param size This parameter can be set to a single number or to an object with the
  2663. * following (optional) properties: precision, width, height. If a single number is passed,
  2664. * it will be used for both width and height. If an object is passed, the screenshot size
  2665. * will be derived from the parameters. The precision property is a multiplier allowing
  2666. * rendering at a higher or lower resolution
  2667. * @param successCallback The callback receives a single parameter which contains the
  2668. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2669. * src parameter of an <img> to display it
  2670. * @param mimeType The MIME type of the screenshot image (default: image/png).
  2671. * Check your browser for supported MIME types
  2672. * @param samples Texture samples (default: 1)
  2673. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  2674. * @param fileName A name for for the downloaded file.
  2675. */
  2676. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  2677. if (mimeType === void 0) { mimeType = "image/png"; }
  2678. if (samples === void 0) { samples = 1; }
  2679. if (antialiasing === void 0) { antialiasing = false; }
  2680. var width;
  2681. var height;
  2682. //If a precision value is specified
  2683. if (size.precision) {
  2684. width = Math.round(engine.getRenderWidth() * size.precision);
  2685. height = Math.round(width / engine.getAspectRatio(camera));
  2686. size = { width: width, height: height };
  2687. }
  2688. else if (size.width && size.height) {
  2689. width = size.width;
  2690. height = size.height;
  2691. }
  2692. //If passing only width, computing height to keep display canvas ratio.
  2693. else if (size.width && !size.height) {
  2694. width = size.width;
  2695. height = Math.round(width / engine.getAspectRatio(camera));
  2696. size = { width: width, height: height };
  2697. }
  2698. //If passing only height, computing width to keep display canvas ratio.
  2699. else if (size.height && !size.width) {
  2700. height = size.height;
  2701. width = Math.round(height * engine.getAspectRatio(camera));
  2702. size = { width: width, height: height };
  2703. }
  2704. //Assuming here that "size" parameter is a number
  2705. else if (!isNaN(size)) {
  2706. height = size;
  2707. width = size;
  2708. }
  2709. else {
  2710. Tools.Error("Invalid 'size' parameter !");
  2711. return;
  2712. }
  2713. var scene = camera.getScene();
  2714. var previousCamera = null;
  2715. if (scene.activeCamera !== camera) {
  2716. previousCamera = scene.activeCamera;
  2717. scene.activeCamera = camera;
  2718. }
  2719. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2720. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  2721. texture.renderList = null;
  2722. texture.samples = samples;
  2723. if (antialiasing) {
  2724. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  2725. }
  2726. texture.onAfterRenderObservable.add(function () {
  2727. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  2728. });
  2729. scene.incrementRenderId();
  2730. scene.resetCachedMaterial();
  2731. texture.render(true);
  2732. texture.dispose();
  2733. if (previousCamera) {
  2734. scene.activeCamera = previousCamera;
  2735. }
  2736. camera.getProjectionMatrix(true); // Force cache refresh;
  2737. };
  2738. /**
  2739. * Validates if xhr data is correct
  2740. * @param xhr defines the request to validate
  2741. * @param dataType defines the expected data type
  2742. * @returns true if data is correct
  2743. */
  2744. Tools.ValidateXHRData = function (xhr, dataType) {
  2745. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2746. if (dataType === void 0) { dataType = 7; }
  2747. try {
  2748. if (dataType & 1) {
  2749. if (xhr.responseText && xhr.responseText.length > 0) {
  2750. return true;
  2751. }
  2752. else if (dataType === 1) {
  2753. return false;
  2754. }
  2755. }
  2756. if (dataType & 2) {
  2757. // Check header width and height since there is no "TGA" magic number
  2758. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  2759. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2760. return true;
  2761. }
  2762. else if (dataType === 2) {
  2763. return false;
  2764. }
  2765. }
  2766. if (dataType & 4) {
  2767. // Check for the "DDS" magic number
  2768. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2769. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2770. return true;
  2771. }
  2772. else {
  2773. return false;
  2774. }
  2775. }
  2776. }
  2777. catch (e) {
  2778. // Global protection
  2779. }
  2780. return false;
  2781. };
  2782. /**
  2783. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  2784. * Be aware Math.random() could cause collisions, but:
  2785. * "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"
  2786. * @returns a pseudo random id
  2787. */
  2788. Tools.RandomId = function () {
  2789. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2790. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2791. return v.toString(16);
  2792. });
  2793. };
  2794. /**
  2795. * Test if the given uri is a base64 string
  2796. * @param uri The uri to test
  2797. * @return True if the uri is a base64 string or false otherwise
  2798. */
  2799. Tools.IsBase64 = function (uri) {
  2800. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2801. };
  2802. /**
  2803. * Decode the given base64 uri.
  2804. * @param uri The uri to decode
  2805. * @return The decoded base64 data.
  2806. */
  2807. Tools.DecodeBase64 = function (uri) {
  2808. var decodedString = atob(uri.split(",")[1]);
  2809. var bufferLength = decodedString.length;
  2810. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2811. for (var i = 0; i < bufferLength; i++) {
  2812. bufferView[i] = decodedString.charCodeAt(i);
  2813. }
  2814. return bufferView.buffer;
  2815. };
  2816. Tools._AddLogEntry = function (entry) {
  2817. Tools._LogCache = entry + Tools._LogCache;
  2818. if (Tools.OnNewCacheEntry) {
  2819. Tools.OnNewCacheEntry(entry);
  2820. }
  2821. };
  2822. Tools._FormatMessage = function (message) {
  2823. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2824. var date = new Date();
  2825. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2826. };
  2827. Tools._LogDisabled = function (message) {
  2828. // nothing to do
  2829. };
  2830. Tools._LogEnabled = function (message) {
  2831. var formattedMessage = Tools._FormatMessage(message);
  2832. console.log("BJS - " + formattedMessage);
  2833. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2834. Tools._AddLogEntry(entry);
  2835. };
  2836. Tools._WarnDisabled = function (message) {
  2837. // nothing to do
  2838. };
  2839. Tools._WarnEnabled = function (message) {
  2840. var formattedMessage = Tools._FormatMessage(message);
  2841. console.warn("BJS - " + formattedMessage);
  2842. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2843. Tools._AddLogEntry(entry);
  2844. };
  2845. Tools._ErrorDisabled = function (message) {
  2846. // nothing to do
  2847. };
  2848. Tools._ErrorEnabled = function (message) {
  2849. Tools.errorsCount++;
  2850. var formattedMessage = Tools._FormatMessage(message);
  2851. console.error("BJS - " + formattedMessage);
  2852. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2853. Tools._AddLogEntry(entry);
  2854. };
  2855. Object.defineProperty(Tools, "LogCache", {
  2856. /**
  2857. * Gets current log cache (list of logs)
  2858. */
  2859. get: function () {
  2860. return Tools._LogCache;
  2861. },
  2862. enumerable: true,
  2863. configurable: true
  2864. });
  2865. /**
  2866. * Clears the log cache
  2867. */
  2868. Tools.ClearLogCache = function () {
  2869. Tools._LogCache = "";
  2870. Tools.errorsCount = 0;
  2871. };
  2872. Object.defineProperty(Tools, "LogLevels", {
  2873. /**
  2874. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  2875. */
  2876. set: function (level) {
  2877. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2878. Tools.Log = Tools._LogEnabled;
  2879. }
  2880. else {
  2881. Tools.Log = Tools._LogDisabled;
  2882. }
  2883. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2884. Tools.Warn = Tools._WarnEnabled;
  2885. }
  2886. else {
  2887. Tools.Warn = Tools._WarnDisabled;
  2888. }
  2889. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2890. Tools.Error = Tools._ErrorEnabled;
  2891. }
  2892. else {
  2893. Tools.Error = Tools._ErrorDisabled;
  2894. }
  2895. },
  2896. enumerable: true,
  2897. configurable: true
  2898. });
  2899. /**
  2900. * Checks if the loaded document was accessed via `file:`-Protocol.
  2901. * @returns boolean
  2902. */
  2903. Tools.IsFileURL = function () {
  2904. return location.protocol === "file:";
  2905. };
  2906. /**
  2907. * Checks if the window object exists
  2908. * @returns true if the window object exists
  2909. */
  2910. Tools.IsWindowObjectExist = function () {
  2911. return (typeof window) !== "undefined";
  2912. };
  2913. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2914. /**
  2915. * Sets the current performance log level
  2916. */
  2917. set: function (level) {
  2918. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2919. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2920. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2921. return;
  2922. }
  2923. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2924. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2925. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2926. return;
  2927. }
  2928. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2929. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2930. },
  2931. enumerable: true,
  2932. configurable: true
  2933. });
  2934. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2935. };
  2936. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2937. };
  2938. Tools._StartUserMark = function (counterName, condition) {
  2939. if (condition === void 0) { condition = true; }
  2940. if (!Tools._performance) {
  2941. if (!Tools.IsWindowObjectExist()) {
  2942. return;
  2943. }
  2944. Tools._performance = window.performance;
  2945. }
  2946. if (!condition || !Tools._performance.mark) {
  2947. return;
  2948. }
  2949. Tools._performance.mark(counterName + "-Begin");
  2950. };
  2951. Tools._EndUserMark = function (counterName, condition) {
  2952. if (condition === void 0) { condition = true; }
  2953. if (!condition || !Tools._performance.mark) {
  2954. return;
  2955. }
  2956. Tools._performance.mark(counterName + "-End");
  2957. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2958. };
  2959. Tools._StartPerformanceConsole = function (counterName, condition) {
  2960. if (condition === void 0) { condition = true; }
  2961. if (!condition) {
  2962. return;
  2963. }
  2964. Tools._StartUserMark(counterName, condition);
  2965. if (console.time) {
  2966. console.time(counterName);
  2967. }
  2968. };
  2969. Tools._EndPerformanceConsole = function (counterName, condition) {
  2970. if (condition === void 0) { condition = true; }
  2971. if (!condition) {
  2972. return;
  2973. }
  2974. Tools._EndUserMark(counterName, condition);
  2975. if (console.time) {
  2976. console.timeEnd(counterName);
  2977. }
  2978. };
  2979. Object.defineProperty(Tools, "Now", {
  2980. /**
  2981. * Gets either window.performance.now() if supported or Date.now() else
  2982. */
  2983. get: function () {
  2984. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  2985. return window.performance.now();
  2986. }
  2987. return Date.now();
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. /**
  2993. * This method will return the name of the class used to create the instance of the given object.
  2994. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  2995. * @param object the object to get the class name from
  2996. * @param isType defines if the object is actually a type
  2997. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  2998. */
  2999. Tools.GetClassName = function (object, isType) {
  3000. if (isType === void 0) { isType = false; }
  3001. var name = null;
  3002. if (!isType && object.getClassName) {
  3003. name = object.getClassName();
  3004. }
  3005. else {
  3006. if (object instanceof Object) {
  3007. var classObj = isType ? object : Object.getPrototypeOf(object);
  3008. name = classObj.constructor["__bjsclassName__"];
  3009. }
  3010. if (!name) {
  3011. name = typeof object;
  3012. }
  3013. }
  3014. return name;
  3015. };
  3016. /**
  3017. * Gets the first element of an array satisfying a given predicate
  3018. * @param array defines the array to browse
  3019. * @param predicate defines the predicate to use
  3020. * @returns null if not found or the element
  3021. */
  3022. Tools.First = function (array, predicate) {
  3023. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  3024. var el = array_1[_i];
  3025. if (predicate(el)) {
  3026. return el;
  3027. }
  3028. }
  3029. return null;
  3030. };
  3031. /**
  3032. * This method will return the name of the full name of the class, including its owning module (if any).
  3033. * 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).
  3034. * @param object the object to get the class name from
  3035. * @param isType defines if the object is actually a type
  3036. * @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.
  3037. * @ignorenaming
  3038. */
  3039. Tools.getFullClassName = function (object, isType) {
  3040. if (isType === void 0) { isType = false; }
  3041. var className = null;
  3042. var moduleName = null;
  3043. if (!isType && object.getClassName) {
  3044. className = object.getClassName();
  3045. }
  3046. else {
  3047. if (object instanceof Object) {
  3048. var classObj = isType ? object : Object.getPrototypeOf(object);
  3049. className = classObj.constructor["__bjsclassName__"];
  3050. moduleName = classObj.constructor["__bjsmoduleName__"];
  3051. }
  3052. if (!className) {
  3053. className = typeof object;
  3054. }
  3055. }
  3056. if (!className) {
  3057. return null;
  3058. }
  3059. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  3060. };
  3061. /**
  3062. * Returns a promise that resolves after the given amount of time.
  3063. * @param delay Number of milliseconds to delay
  3064. * @returns Promise that resolves after the given amount of time
  3065. */
  3066. Tools.DelayAsync = function (delay) {
  3067. return new Promise(function (resolve) {
  3068. setTimeout(function () {
  3069. resolve();
  3070. }, delay);
  3071. });
  3072. };
  3073. /**
  3074. * Gets the current gradient from an array of IValueGradient
  3075. * @param ratio defines the current ratio to get
  3076. * @param gradients defines the array of IValueGradient
  3077. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  3078. */
  3079. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  3080. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  3081. var currentGradient = gradients[gradientIndex];
  3082. var nextGradient = gradients[gradientIndex + 1];
  3083. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  3084. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  3085. updateFunc(currentGradient, nextGradient, scale);
  3086. return;
  3087. }
  3088. }
  3089. // Use last index if over
  3090. var lastIndex = gradients.length - 1;
  3091. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  3092. };
  3093. /**
  3094. * Gets or sets the base URL to use to load assets
  3095. */
  3096. Tools.BaseUrl = "";
  3097. /**
  3098. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  3099. */
  3100. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  3101. /**
  3102. * Default behaviour for cors in the application.
  3103. * It can be a string if the expected behavior is identical in the entire app.
  3104. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  3105. */
  3106. Tools.CorsBehavior = "anonymous";
  3107. /**
  3108. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  3109. * @ignorenaming
  3110. */
  3111. Tools.UseFallbackTexture = true;
  3112. /**
  3113. * Use this object to register external classes like custom textures or material
  3114. * to allow the laoders to instantiate them
  3115. */
  3116. Tools.RegisteredExternalClasses = {};
  3117. /**
  3118. * Texture content used if a texture cannot loaded
  3119. * @ignorenaming
  3120. */
  3121. 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";
  3122. Tools._tmpFloatArray = new Float32Array(1);
  3123. /**
  3124. * Gets or sets a function used to pre-process url before using them to load assets
  3125. */
  3126. Tools.PreprocessUrl = function (url) {
  3127. return url;
  3128. };
  3129. // Logs
  3130. /**
  3131. * No log
  3132. */
  3133. Tools.NoneLogLevel = 0;
  3134. /**
  3135. * Only message logs
  3136. */
  3137. Tools.MessageLogLevel = 1;
  3138. /**
  3139. * Only warning logs
  3140. */
  3141. Tools.WarningLogLevel = 2;
  3142. /**
  3143. * Only error logs
  3144. */
  3145. Tools.ErrorLogLevel = 4;
  3146. /**
  3147. * All logs
  3148. */
  3149. Tools.AllLogLevel = 7;
  3150. Tools._LogCache = "";
  3151. /**
  3152. * Gets a value indicating the number of loading errors
  3153. * @ignorenaming
  3154. */
  3155. Tools.errorsCount = 0;
  3156. /**
  3157. * Log a message to the console
  3158. */
  3159. Tools.Log = Tools._LogEnabled;
  3160. /**
  3161. * Write a warning message to the console
  3162. */
  3163. Tools.Warn = Tools._WarnEnabled;
  3164. /**
  3165. * Write an error message to the console
  3166. */
  3167. Tools.Error = Tools._ErrorEnabled;
  3168. // Performances
  3169. /**
  3170. * No performance log
  3171. */
  3172. Tools.PerformanceNoneLogLevel = 0;
  3173. /**
  3174. * Use user marks to log performance
  3175. */
  3176. Tools.PerformanceUserMarkLogLevel = 1;
  3177. /**
  3178. * Log performance to the console
  3179. */
  3180. Tools.PerformanceConsoleLogLevel = 2;
  3181. /**
  3182. * Starts a performance counter
  3183. */
  3184. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3185. /**
  3186. * Ends a specific performance coutner
  3187. */
  3188. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3189. return Tools;
  3190. }());
  3191. BABYLON.Tools = Tools;
  3192. /**
  3193. * This class is used to track a performance counter which is number based.
  3194. * The user has access to many properties which give statistics of different nature.
  3195. *
  3196. * The implementer can track two kinds of Performance Counter: time and count.
  3197. * 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.
  3198. * 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.
  3199. */
  3200. var PerfCounter = /** @class */ (function () {
  3201. /**
  3202. * Creates a new counter
  3203. */
  3204. function PerfCounter() {
  3205. this._startMonitoringTime = 0;
  3206. this._min = 0;
  3207. this._max = 0;
  3208. this._average = 0;
  3209. this._lastSecAverage = 0;
  3210. this._current = 0;
  3211. this._totalValueCount = 0;
  3212. this._totalAccumulated = 0;
  3213. this._lastSecAccumulated = 0;
  3214. this._lastSecTime = 0;
  3215. this._lastSecValueCount = 0;
  3216. }
  3217. Object.defineProperty(PerfCounter.prototype, "min", {
  3218. /**
  3219. * Returns the smallest value ever
  3220. */
  3221. get: function () {
  3222. return this._min;
  3223. },
  3224. enumerable: true,
  3225. configurable: true
  3226. });
  3227. Object.defineProperty(PerfCounter.prototype, "max", {
  3228. /**
  3229. * Returns the biggest value ever
  3230. */
  3231. get: function () {
  3232. return this._max;
  3233. },
  3234. enumerable: true,
  3235. configurable: true
  3236. });
  3237. Object.defineProperty(PerfCounter.prototype, "average", {
  3238. /**
  3239. * Returns the average value since the performance counter is running
  3240. */
  3241. get: function () {
  3242. return this._average;
  3243. },
  3244. enumerable: true,
  3245. configurable: true
  3246. });
  3247. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  3248. /**
  3249. * Returns the average value of the last second the counter was monitored
  3250. */
  3251. get: function () {
  3252. return this._lastSecAverage;
  3253. },
  3254. enumerable: true,
  3255. configurable: true
  3256. });
  3257. Object.defineProperty(PerfCounter.prototype, "current", {
  3258. /**
  3259. * Returns the current value
  3260. */
  3261. get: function () {
  3262. return this._current;
  3263. },
  3264. enumerable: true,
  3265. configurable: true
  3266. });
  3267. Object.defineProperty(PerfCounter.prototype, "total", {
  3268. /**
  3269. * Gets the accumulated total
  3270. */
  3271. get: function () {
  3272. return this._totalAccumulated;
  3273. },
  3274. enumerable: true,
  3275. configurable: true
  3276. });
  3277. Object.defineProperty(PerfCounter.prototype, "count", {
  3278. /**
  3279. * Gets the total value count
  3280. */
  3281. get: function () {
  3282. return this._totalValueCount;
  3283. },
  3284. enumerable: true,
  3285. configurable: true
  3286. });
  3287. /**
  3288. * Call this method to start monitoring a new frame.
  3289. * 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.
  3290. */
  3291. PerfCounter.prototype.fetchNewFrame = function () {
  3292. this._totalValueCount++;
  3293. this._current = 0;
  3294. this._lastSecValueCount++;
  3295. };
  3296. /**
  3297. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  3298. * @param newCount the count value to add to the monitored count
  3299. * @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.
  3300. */
  3301. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  3302. if (!PerfCounter.Enabled) {
  3303. return;
  3304. }
  3305. this._current += newCount;
  3306. if (fetchResult) {
  3307. this._fetchResult();
  3308. }
  3309. };
  3310. /**
  3311. * Start monitoring this performance counter
  3312. */
  3313. PerfCounter.prototype.beginMonitoring = function () {
  3314. if (!PerfCounter.Enabled) {
  3315. return;
  3316. }
  3317. this._startMonitoringTime = Tools.Now;
  3318. };
  3319. /**
  3320. * Compute the time lapsed since the previous beginMonitoring() call.
  3321. * @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
  3322. */
  3323. PerfCounter.prototype.endMonitoring = function (newFrame) {
  3324. if (newFrame === void 0) { newFrame = true; }
  3325. if (!PerfCounter.Enabled) {
  3326. return;
  3327. }
  3328. if (newFrame) {
  3329. this.fetchNewFrame();
  3330. }
  3331. var currentTime = Tools.Now;
  3332. this._current = currentTime - this._startMonitoringTime;
  3333. if (newFrame) {
  3334. this._fetchResult();
  3335. }
  3336. };
  3337. PerfCounter.prototype._fetchResult = function () {
  3338. this._totalAccumulated += this._current;
  3339. this._lastSecAccumulated += this._current;
  3340. // Min/Max update
  3341. this._min = Math.min(this._min, this._current);
  3342. this._max = Math.max(this._max, this._current);
  3343. this._average = this._totalAccumulated / this._totalValueCount;
  3344. // Reset last sec?
  3345. var now = Tools.Now;
  3346. if ((now - this._lastSecTime) > 1000) {
  3347. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  3348. this._lastSecTime = now;
  3349. this._lastSecAccumulated = 0;
  3350. this._lastSecValueCount = 0;
  3351. }
  3352. };
  3353. /**
  3354. * Gets or sets a global boolean to turn on and off all the counters
  3355. */
  3356. PerfCounter.Enabled = true;
  3357. return PerfCounter;
  3358. }());
  3359. BABYLON.PerfCounter = PerfCounter;
  3360. /**
  3361. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  3362. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  3363. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  3364. * @param name The name of the class, case should be preserved
  3365. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  3366. */
  3367. function className(name, module) {
  3368. return function (target) {
  3369. target["__bjsclassName__"] = name;
  3370. target["__bjsmoduleName__"] = (module != null) ? module : null;
  3371. };
  3372. }
  3373. BABYLON.className = className;
  3374. /**
  3375. * An implementation of a loop for asynchronous functions.
  3376. */
  3377. var AsyncLoop = /** @class */ (function () {
  3378. /**
  3379. * Constructor.
  3380. * @param iterations the number of iterations.
  3381. * @param func the function to run each iteration
  3382. * @param successCallback the callback that will be called upon succesful execution
  3383. * @param offset starting offset.
  3384. */
  3385. function AsyncLoop(
  3386. /**
  3387. * Defines the number of iterations for the loop
  3388. */
  3389. iterations, func, successCallback, offset) {
  3390. if (offset === void 0) { offset = 0; }
  3391. this.iterations = iterations;
  3392. this.index = offset - 1;
  3393. this._done = false;
  3394. this._fn = func;
  3395. this._successCallback = successCallback;
  3396. }
  3397. /**
  3398. * Execute the next iteration. Must be called after the last iteration was finished.
  3399. */
  3400. AsyncLoop.prototype.executeNext = function () {
  3401. if (!this._done) {
  3402. if (this.index + 1 < this.iterations) {
  3403. ++this.index;
  3404. this._fn(this);
  3405. }
  3406. else {
  3407. this.breakLoop();
  3408. }
  3409. }
  3410. };
  3411. /**
  3412. * Break the loop and run the success callback.
  3413. */
  3414. AsyncLoop.prototype.breakLoop = function () {
  3415. this._done = true;
  3416. this._successCallback();
  3417. };
  3418. /**
  3419. * Create and run an async loop.
  3420. * @param iterations the number of iterations.
  3421. * @param fn the function to run each iteration
  3422. * @param successCallback the callback that will be called upon succesful execution
  3423. * @param offset starting offset.
  3424. * @returns the created async loop object
  3425. */
  3426. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  3427. if (offset === void 0) { offset = 0; }
  3428. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  3429. loop.executeNext();
  3430. return loop;
  3431. };
  3432. /**
  3433. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3434. * @param iterations total number of iterations
  3435. * @param syncedIterations number of synchronous iterations in each async iteration.
  3436. * @param fn the function to call each iteration.
  3437. * @param callback a success call back that will be called when iterating stops.
  3438. * @param breakFunction a break condition (optional)
  3439. * @param timeout timeout settings for the setTimeout function. default - 0.
  3440. * @returns the created async loop object
  3441. */
  3442. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3443. if (timeout === void 0) { timeout = 0; }
  3444. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3445. if (breakFunction && breakFunction()) {
  3446. loop.breakLoop();
  3447. }
  3448. else {
  3449. setTimeout(function () {
  3450. for (var i = 0; i < syncedIterations; ++i) {
  3451. var iteration = (loop.index * syncedIterations) + i;
  3452. if (iteration >= iterations) {
  3453. break;
  3454. }
  3455. fn(iteration);
  3456. if (breakFunction && breakFunction()) {
  3457. loop.breakLoop();
  3458. break;
  3459. }
  3460. }
  3461. loop.executeNext();
  3462. }, timeout);
  3463. }
  3464. }, callback);
  3465. };
  3466. return AsyncLoop;
  3467. }());
  3468. BABYLON.AsyncLoop = AsyncLoop;
  3469. })(BABYLON || (BABYLON = {}));
  3470. //# sourceMappingURL=babylon.tools.js.map
  3471. var BABYLON;
  3472. (function (BABYLON) {
  3473. /**
  3474. * Constant used to convert a value to gamma space
  3475. * @ignorenaming
  3476. */
  3477. BABYLON.ToGammaSpace = 1 / 2.2;
  3478. /**
  3479. * Constant used to convert a value to linear space
  3480. * @ignorenaming
  3481. */
  3482. BABYLON.ToLinearSpace = 2.2;
  3483. /**
  3484. * Constant used to define the minimal number value in Babylon.js
  3485. * @ignorenaming
  3486. */
  3487. BABYLON.Epsilon = 0.001;
  3488. /**
  3489. * Class used to hold a RBG color
  3490. */
  3491. var Color3 = /** @class */ (function () {
  3492. /**
  3493. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  3494. * @param r defines the red component (between 0 and 1, default is 0)
  3495. * @param g defines the green component (between 0 and 1, default is 0)
  3496. * @param b defines the blue component (between 0 and 1, default is 0)
  3497. */
  3498. function Color3(
  3499. /**
  3500. * Defines the red component (between 0 and 1, default is 0)
  3501. */
  3502. r,
  3503. /**
  3504. * Defines the green component (between 0 and 1, default is 0)
  3505. */
  3506. g,
  3507. /**
  3508. * Defines the blue component (between 0 and 1, default is 0)
  3509. */
  3510. b) {
  3511. if (r === void 0) { r = 0; }
  3512. if (g === void 0) { g = 0; }
  3513. if (b === void 0) { b = 0; }
  3514. this.r = r;
  3515. this.g = g;
  3516. this.b = b;
  3517. }
  3518. /**
  3519. * Creates a string with the Color3 current values
  3520. * @returns the string representation of the Color3 object
  3521. */
  3522. Color3.prototype.toString = function () {
  3523. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  3524. };
  3525. /**
  3526. * Returns the string "Color3"
  3527. * @returns "Color3"
  3528. */
  3529. Color3.prototype.getClassName = function () {
  3530. return "Color3";
  3531. };
  3532. /**
  3533. * Compute the Color3 hash code
  3534. * @returns an unique number that can be used to hash Color3 objects
  3535. */
  3536. Color3.prototype.getHashCode = function () {
  3537. var hash = this.r || 0;
  3538. hash = (hash * 397) ^ (this.g || 0);
  3539. hash = (hash * 397) ^ (this.b || 0);
  3540. return hash;
  3541. };
  3542. // Operators
  3543. /**
  3544. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  3545. * @param array defines the array where to store the r,g,b components
  3546. * @param index defines an optional index in the target array to define where to start storing values
  3547. * @returns the current Color3 object
  3548. */
  3549. Color3.prototype.toArray = function (array, index) {
  3550. if (index === void 0) { index = 0; }
  3551. array[index] = this.r;
  3552. array[index + 1] = this.g;
  3553. array[index + 2] = this.b;
  3554. return this;
  3555. };
  3556. /**
  3557. * Returns a new Color4 object from the current Color3 and the given alpha
  3558. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  3559. * @returns a new Color4 object
  3560. */
  3561. Color3.prototype.toColor4 = function (alpha) {
  3562. if (alpha === void 0) { alpha = 1; }
  3563. return new Color4(this.r, this.g, this.b, alpha);
  3564. };
  3565. /**
  3566. * Returns a new array populated with 3 numeric elements : red, green and blue values
  3567. * @returns the new array
  3568. */
  3569. Color3.prototype.asArray = function () {
  3570. var result = new Array();
  3571. this.toArray(result, 0);
  3572. return result;
  3573. };
  3574. /**
  3575. * Returns the luminance value
  3576. * @returns a float value
  3577. */
  3578. Color3.prototype.toLuminance = function () {
  3579. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  3580. };
  3581. /**
  3582. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  3583. * @param otherColor defines the second operand
  3584. * @returns the new Color3 object
  3585. */
  3586. Color3.prototype.multiply = function (otherColor) {
  3587. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  3588. };
  3589. /**
  3590. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  3591. * @param otherColor defines the second operand
  3592. * @param result defines the Color3 object where to store the result
  3593. * @returns the current Color3
  3594. */
  3595. Color3.prototype.multiplyToRef = function (otherColor, result) {
  3596. result.r = this.r * otherColor.r;
  3597. result.g = this.g * otherColor.g;
  3598. result.b = this.b * otherColor.b;
  3599. return this;
  3600. };
  3601. /**
  3602. * Determines equality between Color3 objects
  3603. * @param otherColor defines the second operand
  3604. * @returns true if the rgb values are equal to the given ones
  3605. */
  3606. Color3.prototype.equals = function (otherColor) {
  3607. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  3608. };
  3609. /**
  3610. * Determines equality between the current Color3 object and a set of r,b,g values
  3611. * @param r defines the red component to check
  3612. * @param g defines the green component to check
  3613. * @param b defines the blue component to check
  3614. * @returns true if the rgb values are equal to the given ones
  3615. */
  3616. Color3.prototype.equalsFloats = function (r, g, b) {
  3617. return this.r === r && this.g === g && this.b === b;
  3618. };
  3619. /**
  3620. * Multiplies in place each rgb value by scale
  3621. * @param scale defines the scaling factor
  3622. * @returns the updated Color3
  3623. */
  3624. Color3.prototype.scale = function (scale) {
  3625. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  3626. };
  3627. /**
  3628. * Multiplies the rgb values by scale and stores the result into "result"
  3629. * @param scale defines the scaling factor
  3630. * @param result defines the Color3 object where to store the result
  3631. * @returns the unmodified current Color3
  3632. */
  3633. Color3.prototype.scaleToRef = function (scale, result) {
  3634. result.r = this.r * scale;
  3635. result.g = this.g * scale;
  3636. result.b = this.b * scale;
  3637. return this;
  3638. };
  3639. /**
  3640. * Scale the current Color3 values by a factor and add the result to a given Color3
  3641. * @param scale defines the scale factor
  3642. * @param result defines color to store the result into
  3643. * @returns the unmodified current Color3
  3644. */
  3645. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  3646. result.r += this.r * scale;
  3647. result.g += this.g * scale;
  3648. result.b += this.b * scale;
  3649. return this;
  3650. };
  3651. /**
  3652. * Clamps the rgb values by the min and max values and stores the result into "result"
  3653. * @param min defines minimum clamping value (default is 0)
  3654. * @param max defines maximum clamping value (default is 1)
  3655. * @param result defines color to store the result into
  3656. * @returns the original Color3
  3657. */
  3658. Color3.prototype.clampToRef = function (min, max, result) {
  3659. if (min === void 0) { min = 0; }
  3660. if (max === void 0) { max = 1; }
  3661. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  3662. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  3663. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  3664. return this;
  3665. };
  3666. /**
  3667. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  3668. * @param otherColor defines the second operand
  3669. * @returns the new Color3
  3670. */
  3671. Color3.prototype.add = function (otherColor) {
  3672. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  3673. };
  3674. /**
  3675. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  3676. * @param otherColor defines the second operand
  3677. * @param result defines Color3 object to store the result into
  3678. * @returns the unmodified current Color3
  3679. */
  3680. Color3.prototype.addToRef = function (otherColor, result) {
  3681. result.r = this.r + otherColor.r;
  3682. result.g = this.g + otherColor.g;
  3683. result.b = this.b + otherColor.b;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  3688. * @param otherColor defines the second operand
  3689. * @returns the new Color3
  3690. */
  3691. Color3.prototype.subtract = function (otherColor) {
  3692. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  3693. };
  3694. /**
  3695. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  3696. * @param otherColor defines the second operand
  3697. * @param result defines Color3 object to store the result into
  3698. * @returns the unmodified current Color3
  3699. */
  3700. Color3.prototype.subtractToRef = function (otherColor, result) {
  3701. result.r = this.r - otherColor.r;
  3702. result.g = this.g - otherColor.g;
  3703. result.b = this.b - otherColor.b;
  3704. return this;
  3705. };
  3706. /**
  3707. * Copy the current object
  3708. * @returns a new Color3 copied the current one
  3709. */
  3710. Color3.prototype.clone = function () {
  3711. return new Color3(this.r, this.g, this.b);
  3712. };
  3713. /**
  3714. * Copies the rgb values from the source in the current Color3
  3715. * @param source defines the source Color3 object
  3716. * @returns the updated Color3 object
  3717. */
  3718. Color3.prototype.copyFrom = function (source) {
  3719. this.r = source.r;
  3720. this.g = source.g;
  3721. this.b = source.b;
  3722. return this;
  3723. };
  3724. /**
  3725. * Updates the Color3 rgb values from the given floats
  3726. * @param r defines the red component to read from
  3727. * @param g defines the green component to read from
  3728. * @param b defines the blue component to read from
  3729. * @returns the current Color3 object
  3730. */
  3731. Color3.prototype.copyFromFloats = function (r, g, b) {
  3732. this.r = r;
  3733. this.g = g;
  3734. this.b = b;
  3735. return this;
  3736. };
  3737. /**
  3738. * Updates the Color3 rgb values from the given floats
  3739. * @param r defines the red component to read from
  3740. * @param g defines the green component to read from
  3741. * @param b defines the blue component to read from
  3742. * @returns the current Color3 object
  3743. */
  3744. Color3.prototype.set = function (r, g, b) {
  3745. return this.copyFromFloats(r, g, b);
  3746. };
  3747. /**
  3748. * Compute the Color3 hexadecimal code as a string
  3749. * @returns a string containing the hexadecimal representation of the Color3 object
  3750. */
  3751. Color3.prototype.toHexString = function () {
  3752. var intR = (this.r * 255) | 0;
  3753. var intG = (this.g * 255) | 0;
  3754. var intB = (this.b * 255) | 0;
  3755. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  3756. };
  3757. /**
  3758. * Computes a new Color3 converted from the current one to linear space
  3759. * @returns a new Color3 object
  3760. */
  3761. Color3.prototype.toLinearSpace = function () {
  3762. var convertedColor = new Color3();
  3763. this.toLinearSpaceToRef(convertedColor);
  3764. return convertedColor;
  3765. };
  3766. /**
  3767. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  3768. * @param convertedColor defines the Color3 object where to store the linear space version
  3769. * @returns the unmodified Color3
  3770. */
  3771. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  3772. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  3773. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  3774. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  3775. return this;
  3776. };
  3777. /**
  3778. * Computes a new Color3 converted from the current one to gamma space
  3779. * @returns a new Color3 object
  3780. */
  3781. Color3.prototype.toGammaSpace = function () {
  3782. var convertedColor = new Color3();
  3783. this.toGammaSpaceToRef(convertedColor);
  3784. return convertedColor;
  3785. };
  3786. /**
  3787. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  3788. * @param convertedColor defines the Color3 object where to store the gamma space version
  3789. * @returns the unmodified Color3
  3790. */
  3791. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  3792. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  3793. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  3794. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  3795. return this;
  3796. };
  3797. // Statics
  3798. /**
  3799. * Creates a new Color3 from the string containing valid hexadecimal values
  3800. * @param hex defines a string containing valid hexadecimal values
  3801. * @returns a new Color3 object
  3802. */
  3803. Color3.FromHexString = function (hex) {
  3804. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  3805. return new Color3(0, 0, 0);
  3806. }
  3807. var r = parseInt(hex.substring(1, 3), 16);
  3808. var g = parseInt(hex.substring(3, 5), 16);
  3809. var b = parseInt(hex.substring(5, 7), 16);
  3810. return Color3.FromInts(r, g, b);
  3811. };
  3812. /**
  3813. * Creates a new Vector3 from the starting index of the given array
  3814. * @param array defines the source array
  3815. * @param offset defines an offset in the source array
  3816. * @returns a new Color3 object
  3817. */
  3818. Color3.FromArray = function (array, offset) {
  3819. if (offset === void 0) { offset = 0; }
  3820. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  3821. };
  3822. /**
  3823. * Creates a new Color3 from integer values (< 256)
  3824. * @param r defines the red component to read from (value between 0 and 255)
  3825. * @param g defines the green component to read from (value between 0 and 255)
  3826. * @param b defines the blue component to read from (value between 0 and 255)
  3827. * @returns a new Color3 object
  3828. */
  3829. Color3.FromInts = function (r, g, b) {
  3830. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  3831. };
  3832. /**
  3833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3834. * @param start defines the start Color3 value
  3835. * @param end defines the end Color3 value
  3836. * @param amount defines the gradient value between start and end
  3837. * @returns a new Color3 object
  3838. */
  3839. Color3.Lerp = function (start, end, amount) {
  3840. var result = new Color3(0.0, 0.0, 0.0);
  3841. Color3.LerpToRef(start, end, amount, result);
  3842. return result;
  3843. };
  3844. /**
  3845. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3846. * @param left defines the start value
  3847. * @param right defines the end value
  3848. * @param amount defines the gradient factor
  3849. * @param result defines the Color3 object where to store the result
  3850. */
  3851. Color3.LerpToRef = function (left, right, amount, result) {
  3852. result.r = left.r + ((right.r - left.r) * amount);
  3853. result.g = left.g + ((right.g - left.g) * amount);
  3854. result.b = left.b + ((right.b - left.b) * amount);
  3855. };
  3856. /**
  3857. * Returns a Color3 value containing a red color
  3858. * @returns a new Color3 object
  3859. */
  3860. Color3.Red = function () { return new Color3(1, 0, 0); };
  3861. /**
  3862. * Returns a Color3 value containing a green color
  3863. * @returns a new Color3 object
  3864. */
  3865. Color3.Green = function () { return new Color3(0, 1, 0); };
  3866. /**
  3867. * Returns a Color3 value containing a blue color
  3868. * @returns a new Color3 object
  3869. */
  3870. Color3.Blue = function () { return new Color3(0, 0, 1); };
  3871. /**
  3872. * Returns a Color3 value containing a black color
  3873. * @returns a new Color3 object
  3874. */
  3875. Color3.Black = function () { return new Color3(0, 0, 0); };
  3876. /**
  3877. * Returns a Color3 value containing a white color
  3878. * @returns a new Color3 object
  3879. */
  3880. Color3.White = function () { return new Color3(1, 1, 1); };
  3881. /**
  3882. * Returns a Color3 value containing a purple color
  3883. * @returns a new Color3 object
  3884. */
  3885. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  3886. /**
  3887. * Returns a Color3 value containing a magenta color
  3888. * @returns a new Color3 object
  3889. */
  3890. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  3891. /**
  3892. * Returns a Color3 value containing a yellow color
  3893. * @returns a new Color3 object
  3894. */
  3895. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  3896. /**
  3897. * Returns a Color3 value containing a gray color
  3898. * @returns a new Color3 object
  3899. */
  3900. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  3901. /**
  3902. * Returns a Color3 value containing a teal color
  3903. * @returns a new Color3 object
  3904. */
  3905. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  3906. /**
  3907. * Returns a Color3 value containing a random color
  3908. * @returns a new Color3 object
  3909. */
  3910. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  3911. return Color3;
  3912. }());
  3913. BABYLON.Color3 = Color3;
  3914. /**
  3915. * Class used to hold a RBGA color
  3916. */
  3917. var Color4 = /** @class */ (function () {
  3918. /**
  3919. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  3920. * @param r defines the red component (between 0 and 1, default is 0)
  3921. * @param g defines the green component (between 0 and 1, default is 0)
  3922. * @param b defines the blue component (between 0 and 1, default is 0)
  3923. * @param a defines the alpha component (between 0 and 1, default is 1)
  3924. */
  3925. function Color4(
  3926. /**
  3927. * Defines the red component (between 0 and 1, default is 0)
  3928. */
  3929. r,
  3930. /**
  3931. * Defines the green component (between 0 and 1, default is 0)
  3932. */
  3933. g,
  3934. /**
  3935. * Defines the blue component (between 0 and 1, default is 0)
  3936. */
  3937. b,
  3938. /**
  3939. * Defines the alpha component (between 0 and 1, default is 1)
  3940. */
  3941. a) {
  3942. if (r === void 0) { r = 0; }
  3943. if (g === void 0) { g = 0; }
  3944. if (b === void 0) { b = 0; }
  3945. if (a === void 0) { a = 1; }
  3946. this.r = r;
  3947. this.g = g;
  3948. this.b = b;
  3949. this.a = a;
  3950. }
  3951. // Operators
  3952. /**
  3953. * Adds in place the given Color4 values to the current Color4 object
  3954. * @param right defines the second operand
  3955. * @returns the current updated Color4 object
  3956. */
  3957. Color4.prototype.addInPlace = function (right) {
  3958. this.r += right.r;
  3959. this.g += right.g;
  3960. this.b += right.b;
  3961. this.a += right.a;
  3962. return this;
  3963. };
  3964. /**
  3965. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  3966. * @returns the new array
  3967. */
  3968. Color4.prototype.asArray = function () {
  3969. var result = new Array();
  3970. this.toArray(result, 0);
  3971. return result;
  3972. };
  3973. /**
  3974. * Stores from the starting index in the given array the Color4 successive values
  3975. * @param array defines the array where to store the r,g,b components
  3976. * @param index defines an optional index in the target array to define where to start storing values
  3977. * @returns the current Color4 object
  3978. */
  3979. Color4.prototype.toArray = function (array, index) {
  3980. if (index === void 0) { index = 0; }
  3981. array[index] = this.r;
  3982. array[index + 1] = this.g;
  3983. array[index + 2] = this.b;
  3984. array[index + 3] = this.a;
  3985. return this;
  3986. };
  3987. /**
  3988. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  3989. * @param right defines the second operand
  3990. * @returns a new Color4 object
  3991. */
  3992. Color4.prototype.add = function (right) {
  3993. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  3994. };
  3995. /**
  3996. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  3997. * @param right defines the second operand
  3998. * @returns a new Color4 object
  3999. */
  4000. Color4.prototype.subtract = function (right) {
  4001. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  4002. };
  4003. /**
  4004. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  4005. * @param right defines the second operand
  4006. * @param result defines the Color4 object where to store the result
  4007. * @returns the current Color4 object
  4008. */
  4009. Color4.prototype.subtractToRef = function (right, result) {
  4010. result.r = this.r - right.r;
  4011. result.g = this.g - right.g;
  4012. result.b = this.b - right.b;
  4013. result.a = this.a - right.a;
  4014. return this;
  4015. };
  4016. /**
  4017. * Creates a new Color4 with the current Color4 values multiplied by scale
  4018. * @param scale defines the scaling factor to apply
  4019. * @returns a new Color4 object
  4020. */
  4021. Color4.prototype.scale = function (scale) {
  4022. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  4023. };
  4024. /**
  4025. * Multiplies the current Color4 values by scale and stores the result in "result"
  4026. * @param scale defines the scaling factor to apply
  4027. * @param result defines the Color4 object where to store the result
  4028. * @returns the current unmodified Color4
  4029. */
  4030. Color4.prototype.scaleToRef = function (scale, result) {
  4031. result.r = this.r * scale;
  4032. result.g = this.g * scale;
  4033. result.b = this.b * scale;
  4034. result.a = this.a * scale;
  4035. return this;
  4036. };
  4037. /**
  4038. * Scale the current Color4 values by a factor and add the result to a given Color4
  4039. * @param scale defines the scale factor
  4040. * @param result defines the Color4 object where to store the result
  4041. * @returns the unmodified current Color4
  4042. */
  4043. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  4044. result.r += this.r * scale;
  4045. result.g += this.g * scale;
  4046. result.b += this.b * scale;
  4047. result.a += this.a * scale;
  4048. return this;
  4049. };
  4050. /**
  4051. * Clamps the rgb values by the min and max values and stores the result into "result"
  4052. * @param min defines minimum clamping value (default is 0)
  4053. * @param max defines maximum clamping value (default is 1)
  4054. * @param result defines color to store the result into.
  4055. * @returns the cuurent Color4
  4056. */
  4057. Color4.prototype.clampToRef = function (min, max, result) {
  4058. if (min === void 0) { min = 0; }
  4059. if (max === void 0) { max = 1; }
  4060. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  4061. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  4062. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  4063. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  4064. return this;
  4065. };
  4066. /**
  4067. * Multipy an Color4 value by another and return a new Color4 object
  4068. * @param color defines the Color4 value to multiply by
  4069. * @returns a new Color4 object
  4070. */
  4071. Color4.prototype.multiply = function (color) {
  4072. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  4073. };
  4074. /**
  4075. * Multipy a Color4 value by another and push the result in a reference value
  4076. * @param color defines the Color4 value to multiply by
  4077. * @param result defines the Color4 to fill the result in
  4078. * @returns the result Color4
  4079. */
  4080. Color4.prototype.multiplyToRef = function (color, result) {
  4081. result.r = this.r * color.r;
  4082. result.g = this.g * color.g;
  4083. result.b = this.b * color.b;
  4084. result.a = this.a * color.a;
  4085. return result;
  4086. };
  4087. /**
  4088. * Creates a string with the Color4 current values
  4089. * @returns the string representation of the Color4 object
  4090. */
  4091. Color4.prototype.toString = function () {
  4092. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  4093. };
  4094. /**
  4095. * Returns the string "Color4"
  4096. * @returns "Color4"
  4097. */
  4098. Color4.prototype.getClassName = function () {
  4099. return "Color4";
  4100. };
  4101. /**
  4102. * Compute the Color4 hash code
  4103. * @returns an unique number that can be used to hash Color4 objects
  4104. */
  4105. Color4.prototype.getHashCode = function () {
  4106. var hash = this.r || 0;
  4107. hash = (hash * 397) ^ (this.g || 0);
  4108. hash = (hash * 397) ^ (this.b || 0);
  4109. hash = (hash * 397) ^ (this.a || 0);
  4110. return hash;
  4111. };
  4112. /**
  4113. * Creates a new Color4 copied from the current one
  4114. * @returns a new Color4 object
  4115. */
  4116. Color4.prototype.clone = function () {
  4117. return new Color4(this.r, this.g, this.b, this.a);
  4118. };
  4119. /**
  4120. * Copies the given Color4 values into the current one
  4121. * @param source defines the source Color4 object
  4122. * @returns the current updated Color4 object
  4123. */
  4124. Color4.prototype.copyFrom = function (source) {
  4125. this.r = source.r;
  4126. this.g = source.g;
  4127. this.b = source.b;
  4128. this.a = source.a;
  4129. return this;
  4130. };
  4131. /**
  4132. * Copies the given float values into the current one
  4133. * @param r defines the red component to read from
  4134. * @param g defines the green component to read from
  4135. * @param b defines the blue component to read from
  4136. * @param a defines the alpha component to read from
  4137. * @returns the current updated Color4 object
  4138. */
  4139. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  4140. this.r = r;
  4141. this.g = g;
  4142. this.b = b;
  4143. this.a = a;
  4144. return this;
  4145. };
  4146. /**
  4147. * Copies the given float values into the current one
  4148. * @param r defines the red component to read from
  4149. * @param g defines the green component to read from
  4150. * @param b defines the blue component to read from
  4151. * @param a defines the alpha component to read from
  4152. * @returns the current updated Color4 object
  4153. */
  4154. Color4.prototype.set = function (r, g, b, a) {
  4155. return this.copyFromFloats(r, g, b, a);
  4156. };
  4157. /**
  4158. * Compute the Color4 hexadecimal code as a string
  4159. * @returns a string containing the hexadecimal representation of the Color4 object
  4160. */
  4161. Color4.prototype.toHexString = function () {
  4162. var intR = (this.r * 255) | 0;
  4163. var intG = (this.g * 255) | 0;
  4164. var intB = (this.b * 255) | 0;
  4165. var intA = (this.a * 255) | 0;
  4166. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  4167. };
  4168. /**
  4169. * Computes a new Color4 converted from the current one to linear space
  4170. * @returns a new Color4 object
  4171. */
  4172. Color4.prototype.toLinearSpace = function () {
  4173. var convertedColor = new Color4();
  4174. this.toLinearSpaceToRef(convertedColor);
  4175. return convertedColor;
  4176. };
  4177. /**
  4178. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  4179. * @param convertedColor defines the Color4 object where to store the linear space version
  4180. * @returns the unmodified Color4
  4181. */
  4182. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  4183. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  4184. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  4185. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  4186. convertedColor.a = this.a;
  4187. return this;
  4188. };
  4189. /**
  4190. * Computes a new Color4 converted from the current one to gamma space
  4191. * @returns a new Color4 object
  4192. */
  4193. Color4.prototype.toGammaSpace = function () {
  4194. var convertedColor = new Color4();
  4195. this.toGammaSpaceToRef(convertedColor);
  4196. return convertedColor;
  4197. };
  4198. /**
  4199. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  4200. * @param convertedColor defines the Color4 object where to store the gamma space version
  4201. * @returns the unmodified Color4
  4202. */
  4203. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  4204. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  4205. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  4206. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  4207. convertedColor.a = this.a;
  4208. return this;
  4209. };
  4210. // Statics
  4211. /**
  4212. * Creates a new Color4 from the string containing valid hexadecimal values
  4213. * @param hex defines a string containing valid hexadecimal values
  4214. * @returns a new Color4 object
  4215. */
  4216. Color4.FromHexString = function (hex) {
  4217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  4218. return new Color4(0.0, 0.0, 0.0, 0.0);
  4219. }
  4220. var r = parseInt(hex.substring(1, 3), 16);
  4221. var g = parseInt(hex.substring(3, 5), 16);
  4222. var b = parseInt(hex.substring(5, 7), 16);
  4223. var a = parseInt(hex.substring(7, 9), 16);
  4224. return Color4.FromInts(r, g, b, a);
  4225. };
  4226. /**
  4227. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4228. * @param left defines the start value
  4229. * @param right defines the end value
  4230. * @param amount defines the gradient factor
  4231. * @returns a new Color4 object
  4232. */
  4233. Color4.Lerp = function (left, right, amount) {
  4234. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  4235. Color4.LerpToRef(left, right, amount, result);
  4236. return result;
  4237. };
  4238. /**
  4239. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4240. * @param left defines the start value
  4241. * @param right defines the end value
  4242. * @param amount defines the gradient factor
  4243. * @param result defines the Color4 object where to store data
  4244. */
  4245. Color4.LerpToRef = function (left, right, amount, result) {
  4246. result.r = left.r + (right.r - left.r) * amount;
  4247. result.g = left.g + (right.g - left.g) * amount;
  4248. result.b = left.b + (right.b - left.b) * amount;
  4249. result.a = left.a + (right.a - left.a) * amount;
  4250. };
  4251. /**
  4252. * Creates a new Color4 from a Color3 and an alpha value
  4253. * @param color3 defines the source Color3 to read from
  4254. * @param alpha defines the alpha component (1.0 by default)
  4255. * @returns a new Color4 object
  4256. */
  4257. Color4.FromColor3 = function (color3, alpha) {
  4258. if (alpha === void 0) { alpha = 1.0; }
  4259. return new Color4(color3.r, color3.g, color3.b, alpha);
  4260. };
  4261. /**
  4262. * Creates a new Color4 from the starting index element of the given array
  4263. * @param array defines the source array to read from
  4264. * @param offset defines the offset in the source array
  4265. * @returns a new Color4 object
  4266. */
  4267. Color4.FromArray = function (array, offset) {
  4268. if (offset === void 0) { offset = 0; }
  4269. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4270. };
  4271. /**
  4272. * Creates a new Color3 from integer values (< 256)
  4273. * @param r defines the red component to read from (value between 0 and 255)
  4274. * @param g defines the green component to read from (value between 0 and 255)
  4275. * @param b defines the blue component to read from (value between 0 and 255)
  4276. * @param a defines the alpha component to read from (value between 0 and 255)
  4277. * @returns a new Color3 object
  4278. */
  4279. Color4.FromInts = function (r, g, b, a) {
  4280. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  4281. };
  4282. /**
  4283. * Check the content of a given array and convert it to an array containing RGBA data
  4284. * If the original array was already containing count * 4 values then it is returned directly
  4285. * @param colors defines the array to check
  4286. * @param count defines the number of RGBA data to expect
  4287. * @returns an array containing count * 4 values (RGBA)
  4288. */
  4289. Color4.CheckColors4 = function (colors, count) {
  4290. // Check if color3 was used
  4291. if (colors.length === count * 3) {
  4292. var colors4 = [];
  4293. for (var index = 0; index < colors.length; index += 3) {
  4294. var newIndex = (index / 3) * 4;
  4295. colors4[newIndex] = colors[index];
  4296. colors4[newIndex + 1] = colors[index + 1];
  4297. colors4[newIndex + 2] = colors[index + 2];
  4298. colors4[newIndex + 3] = 1.0;
  4299. }
  4300. return colors4;
  4301. }
  4302. return colors;
  4303. };
  4304. return Color4;
  4305. }());
  4306. BABYLON.Color4 = Color4;
  4307. /**
  4308. * Class representing a vector containing 2 coordinates
  4309. */
  4310. var Vector2 = /** @class */ (function () {
  4311. /**
  4312. * Creates a new Vector2 from the given x and y coordinates
  4313. * @param x defines the first coordinate
  4314. * @param y defines the second coordinate
  4315. */
  4316. function Vector2(
  4317. /** defines the first coordinate */
  4318. x,
  4319. /** defines the second coordinate */
  4320. y) {
  4321. if (x === void 0) { x = 0; }
  4322. if (y === void 0) { y = 0; }
  4323. this.x = x;
  4324. this.y = y;
  4325. }
  4326. /**
  4327. * Gets a string with the Vector2 coordinates
  4328. * @returns a string with the Vector2 coordinates
  4329. */
  4330. Vector2.prototype.toString = function () {
  4331. return "{X: " + this.x + " Y:" + this.y + "}";
  4332. };
  4333. /**
  4334. * Gets class name
  4335. * @returns the string "Vector2"
  4336. */
  4337. Vector2.prototype.getClassName = function () {
  4338. return "Vector2";
  4339. };
  4340. /**
  4341. * Gets current vector hash code
  4342. * @returns the Vector2 hash code as a number
  4343. */
  4344. Vector2.prototype.getHashCode = function () {
  4345. var hash = this.x || 0;
  4346. hash = (hash * 397) ^ (this.y || 0);
  4347. return hash;
  4348. };
  4349. // Operators
  4350. /**
  4351. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  4352. * @param array defines the source array
  4353. * @param index defines the offset in source array
  4354. * @returns the current Vector2
  4355. */
  4356. Vector2.prototype.toArray = function (array, index) {
  4357. if (index === void 0) { index = 0; }
  4358. array[index] = this.x;
  4359. array[index + 1] = this.y;
  4360. return this;
  4361. };
  4362. /**
  4363. * Copy the current vector to an array
  4364. * @returns a new array with 2 elements: the Vector2 coordinates.
  4365. */
  4366. Vector2.prototype.asArray = function () {
  4367. var result = new Array();
  4368. this.toArray(result, 0);
  4369. return result;
  4370. };
  4371. /**
  4372. * Sets the Vector2 coordinates with the given Vector2 coordinates
  4373. * @param source defines the source Vector2
  4374. * @returns the current updated Vector2
  4375. */
  4376. Vector2.prototype.copyFrom = function (source) {
  4377. this.x = source.x;
  4378. this.y = source.y;
  4379. return this;
  4380. };
  4381. /**
  4382. * Sets the Vector2 coordinates with the given floats
  4383. * @param x defines the first coordinate
  4384. * @param y defines the second coordinate
  4385. * @returns the current updated Vector2
  4386. */
  4387. Vector2.prototype.copyFromFloats = function (x, y) {
  4388. this.x = x;
  4389. this.y = y;
  4390. return this;
  4391. };
  4392. /**
  4393. * Sets the Vector2 coordinates with the given floats
  4394. * @param x defines the first coordinate
  4395. * @param y defines the second coordinate
  4396. * @returns the current updated Vector2
  4397. */
  4398. Vector2.prototype.set = function (x, y) {
  4399. return this.copyFromFloats(x, y);
  4400. };
  4401. /**
  4402. * Add another vector with the current one
  4403. * @param otherVector defines the other vector
  4404. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  4405. */
  4406. Vector2.prototype.add = function (otherVector) {
  4407. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4408. };
  4409. /**
  4410. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  4411. * @param otherVector defines the other vector
  4412. * @param result defines the target vector
  4413. * @returns the unmodified current Vector2
  4414. */
  4415. Vector2.prototype.addToRef = function (otherVector, result) {
  4416. result.x = this.x + otherVector.x;
  4417. result.y = this.y + otherVector.y;
  4418. return this;
  4419. };
  4420. /**
  4421. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  4422. * @param otherVector defines the other vector
  4423. * @returns the current updated Vector2
  4424. */
  4425. Vector2.prototype.addInPlace = function (otherVector) {
  4426. this.x += otherVector.x;
  4427. this.y += otherVector.y;
  4428. return this;
  4429. };
  4430. /**
  4431. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  4432. * @param otherVector defines the other vector
  4433. * @returns a new Vector2
  4434. */
  4435. Vector2.prototype.addVector3 = function (otherVector) {
  4436. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4437. };
  4438. /**
  4439. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  4440. * @param otherVector defines the other vector
  4441. * @returns a new Vector2
  4442. */
  4443. Vector2.prototype.subtract = function (otherVector) {
  4444. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  4445. };
  4446. /**
  4447. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  4448. * @param otherVector defines the other vector
  4449. * @param result defines the target vector
  4450. * @returns the unmodified current Vector2
  4451. */
  4452. Vector2.prototype.subtractToRef = function (otherVector, result) {
  4453. result.x = this.x - otherVector.x;
  4454. result.y = this.y - otherVector.y;
  4455. return this;
  4456. };
  4457. /**
  4458. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  4459. * @param otherVector defines the other vector
  4460. * @returns the current updated Vector2
  4461. */
  4462. Vector2.prototype.subtractInPlace = function (otherVector) {
  4463. this.x -= otherVector.x;
  4464. this.y -= otherVector.y;
  4465. return this;
  4466. };
  4467. /**
  4468. * Multiplies in place the current Vector2 coordinates by the given ones
  4469. * @param otherVector defines the other vector
  4470. * @returns the current updated Vector2
  4471. */
  4472. Vector2.prototype.multiplyInPlace = function (otherVector) {
  4473. this.x *= otherVector.x;
  4474. this.y *= otherVector.y;
  4475. return this;
  4476. };
  4477. /**
  4478. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  4479. * @param otherVector defines the other vector
  4480. * @returns a new Vector2
  4481. */
  4482. Vector2.prototype.multiply = function (otherVector) {
  4483. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  4484. };
  4485. /**
  4486. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  4487. * @param otherVector defines the other vector
  4488. * @param result defines the target vector
  4489. * @returns the unmodified current Vector2
  4490. */
  4491. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  4492. result.x = this.x * otherVector.x;
  4493. result.y = this.y * otherVector.y;
  4494. return this;
  4495. };
  4496. /**
  4497. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  4498. * @param x defines the first coordinate
  4499. * @param y defines the second coordinate
  4500. * @returns a new Vector2
  4501. */
  4502. Vector2.prototype.multiplyByFloats = function (x, y) {
  4503. return new Vector2(this.x * x, this.y * y);
  4504. };
  4505. /**
  4506. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  4507. * @param otherVector defines the other vector
  4508. * @returns a new Vector2
  4509. */
  4510. Vector2.prototype.divide = function (otherVector) {
  4511. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  4512. };
  4513. /**
  4514. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  4515. * @param otherVector defines the other vector
  4516. * @param result defines the target vector
  4517. * @returns the unmodified current Vector2
  4518. */
  4519. Vector2.prototype.divideToRef = function (otherVector, result) {
  4520. result.x = this.x / otherVector.x;
  4521. result.y = this.y / otherVector.y;
  4522. return this;
  4523. };
  4524. /**
  4525. * Divides the current Vector2 coordinates by the given ones
  4526. * @param otherVector defines the other vector
  4527. * @returns the current updated Vector2
  4528. */
  4529. Vector2.prototype.divideInPlace = function (otherVector) {
  4530. return this.divideToRef(otherVector, this);
  4531. };
  4532. /**
  4533. * Gets a new Vector2 with current Vector2 negated coordinates
  4534. * @returns a new Vector2
  4535. */
  4536. Vector2.prototype.negate = function () {
  4537. return new Vector2(-this.x, -this.y);
  4538. };
  4539. /**
  4540. * Multiply the Vector2 coordinates by scale
  4541. * @param scale defines the scaling factor
  4542. * @returns the current updated Vector2
  4543. */
  4544. Vector2.prototype.scaleInPlace = function (scale) {
  4545. this.x *= scale;
  4546. this.y *= scale;
  4547. return this;
  4548. };
  4549. /**
  4550. * Returns a new Vector2 scaled by "scale" from the current Vector2
  4551. * @param scale defines the scaling factor
  4552. * @returns a new Vector2
  4553. */
  4554. Vector2.prototype.scale = function (scale) {
  4555. var result = new Vector2(0, 0);
  4556. this.scaleToRef(scale, result);
  4557. return result;
  4558. };
  4559. /**
  4560. * Scale the current Vector2 values by a factor to a given Vector2
  4561. * @param scale defines the scale factor
  4562. * @param result defines the Vector2 object where to store the result
  4563. * @returns the unmodified current Vector2
  4564. */
  4565. Vector2.prototype.scaleToRef = function (scale, result) {
  4566. result.x = this.x * scale;
  4567. result.y = this.y * scale;
  4568. return this;
  4569. };
  4570. /**
  4571. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  4572. * @param scale defines the scale factor
  4573. * @param result defines the Vector2 object where to store the result
  4574. * @returns the unmodified current Vector2
  4575. */
  4576. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  4577. result.x += this.x * scale;
  4578. result.y += this.y * scale;
  4579. return this;
  4580. };
  4581. /**
  4582. * Gets a boolean if two vectors are equals
  4583. * @param otherVector defines the other vector
  4584. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  4585. */
  4586. Vector2.prototype.equals = function (otherVector) {
  4587. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  4588. };
  4589. /**
  4590. * Gets a boolean if two vectors are equals (using an epsilon value)
  4591. * @param otherVector defines the other vector
  4592. * @param epsilon defines the minimal distance to consider equality
  4593. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  4594. */
  4595. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4596. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4597. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  4598. };
  4599. /**
  4600. * Gets a new Vector2 from current Vector2 floored values
  4601. * @returns a new Vector2
  4602. */
  4603. Vector2.prototype.floor = function () {
  4604. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  4605. };
  4606. /**
  4607. * Gets a new Vector2 from current Vector2 floored values
  4608. * @returns a new Vector2
  4609. */
  4610. Vector2.prototype.fract = function () {
  4611. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  4612. };
  4613. // Properties
  4614. /**
  4615. * Gets the length of the vector
  4616. * @returns the vector length (float)
  4617. */
  4618. Vector2.prototype.length = function () {
  4619. return Math.sqrt(this.x * this.x + this.y * this.y);
  4620. };
  4621. /**
  4622. * Gets the vector squared length
  4623. * @returns the vector squared length (float)
  4624. */
  4625. Vector2.prototype.lengthSquared = function () {
  4626. return (this.x * this.x + this.y * this.y);
  4627. };
  4628. // Methods
  4629. /**
  4630. * Normalize the vector
  4631. * @returns the current updated Vector2
  4632. */
  4633. Vector2.prototype.normalize = function () {
  4634. var len = this.length();
  4635. if (len === 0) {
  4636. return this;
  4637. }
  4638. var num = 1.0 / len;
  4639. this.x *= num;
  4640. this.y *= num;
  4641. return this;
  4642. };
  4643. /**
  4644. * Gets a new Vector2 copied from the Vector2
  4645. * @returns a new Vector2
  4646. */
  4647. Vector2.prototype.clone = function () {
  4648. return new Vector2(this.x, this.y);
  4649. };
  4650. // Statics
  4651. /**
  4652. * Gets a new Vector2(0, 0)
  4653. * @returns a new Vector2
  4654. */
  4655. Vector2.Zero = function () {
  4656. return new Vector2(0, 0);
  4657. };
  4658. /**
  4659. * Gets a new Vector2(1, 1)
  4660. * @returns a new Vector2
  4661. */
  4662. Vector2.One = function () {
  4663. return new Vector2(1, 1);
  4664. };
  4665. /**
  4666. * Gets a new Vector2 set from the given index element of the given array
  4667. * @param array defines the data source
  4668. * @param offset defines the offset in the data source
  4669. * @returns a new Vector2
  4670. */
  4671. Vector2.FromArray = function (array, offset) {
  4672. if (offset === void 0) { offset = 0; }
  4673. return new Vector2(array[offset], array[offset + 1]);
  4674. };
  4675. /**
  4676. * Sets "result" from the given index element of the given array
  4677. * @param array defines the data source
  4678. * @param offset defines the offset in the data source
  4679. * @param result defines the target vector
  4680. */
  4681. Vector2.FromArrayToRef = function (array, offset, result) {
  4682. result.x = array[offset];
  4683. result.y = array[offset + 1];
  4684. };
  4685. /**
  4686. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  4687. * @param value1 defines 1st point of control
  4688. * @param value2 defines 2nd point of control
  4689. * @param value3 defines 3rd point of control
  4690. * @param value4 defines 4th point of control
  4691. * @param amount defines the interpolation factor
  4692. * @returns a new Vector2
  4693. */
  4694. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  4695. var squared = amount * amount;
  4696. var cubed = amount * squared;
  4697. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  4698. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  4699. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  4700. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  4701. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  4702. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  4703. return new Vector2(x, y);
  4704. };
  4705. /**
  4706. * 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".
  4707. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  4708. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  4709. * @param value defines the value to clamp
  4710. * @param min defines the lower limit
  4711. * @param max defines the upper limit
  4712. * @returns a new Vector2
  4713. */
  4714. Vector2.Clamp = function (value, min, max) {
  4715. var x = value.x;
  4716. x = (x > max.x) ? max.x : x;
  4717. x = (x < min.x) ? min.x : x;
  4718. var y = value.y;
  4719. y = (y > max.y) ? max.y : y;
  4720. y = (y < min.y) ? min.y : y;
  4721. return new Vector2(x, y);
  4722. };
  4723. /**
  4724. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  4725. * @param value1 defines the 1st control point
  4726. * @param tangent1 defines the outgoing tangent
  4727. * @param value2 defines the 2nd control point
  4728. * @param tangent2 defines the incoming tangent
  4729. * @param amount defines the interpolation factor
  4730. * @returns a new Vector2
  4731. */
  4732. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4733. var squared = amount * amount;
  4734. var cubed = amount * squared;
  4735. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4736. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4737. var part3 = (cubed - (2.0 * squared)) + amount;
  4738. var part4 = cubed - squared;
  4739. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4740. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4741. return new Vector2(x, y);
  4742. };
  4743. /**
  4744. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  4745. * @param start defines the start vector
  4746. * @param end defines the end vector
  4747. * @param amount defines the interpolation factor
  4748. * @returns a new Vector2
  4749. */
  4750. Vector2.Lerp = function (start, end, amount) {
  4751. var x = start.x + ((end.x - start.x) * amount);
  4752. var y = start.y + ((end.y - start.y) * amount);
  4753. return new Vector2(x, y);
  4754. };
  4755. /**
  4756. * Gets the dot product of the vector "left" and the vector "right"
  4757. * @param left defines first vector
  4758. * @param right defines second vector
  4759. * @returns the dot product (float)
  4760. */
  4761. Vector2.Dot = function (left, right) {
  4762. return left.x * right.x + left.y * right.y;
  4763. };
  4764. /**
  4765. * Returns a new Vector2 equal to the normalized given vector
  4766. * @param vector defines the vector to normalize
  4767. * @returns a new Vector2
  4768. */
  4769. Vector2.Normalize = function (vector) {
  4770. var newVector = vector.clone();
  4771. newVector.normalize();
  4772. return newVector;
  4773. };
  4774. /**
  4775. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  4776. * @param left defines 1st vector
  4777. * @param right defines 2nd vector
  4778. * @returns a new Vector2
  4779. */
  4780. Vector2.Minimize = function (left, right) {
  4781. var x = (left.x < right.x) ? left.x : right.x;
  4782. var y = (left.y < right.y) ? left.y : right.y;
  4783. return new Vector2(x, y);
  4784. };
  4785. /**
  4786. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  4787. * @param left defines 1st vector
  4788. * @param right defines 2nd vector
  4789. * @returns a new Vector2
  4790. */
  4791. Vector2.Maximize = function (left, right) {
  4792. var x = (left.x > right.x) ? left.x : right.x;
  4793. var y = (left.y > right.y) ? left.y : right.y;
  4794. return new Vector2(x, y);
  4795. };
  4796. /**
  4797. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  4798. * @param vector defines the vector to transform
  4799. * @param transformation defines the matrix to apply
  4800. * @returns a new Vector2
  4801. */
  4802. Vector2.Transform = function (vector, transformation) {
  4803. var r = Vector2.Zero();
  4804. Vector2.TransformToRef(vector, transformation, r);
  4805. return r;
  4806. };
  4807. /**
  4808. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  4809. * @param vector defines the vector to transform
  4810. * @param transformation defines the matrix to apply
  4811. * @param result defines the target vector
  4812. */
  4813. Vector2.TransformToRef = function (vector, transformation, result) {
  4814. var m = transformation.m;
  4815. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  4816. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  4817. result.x = x;
  4818. result.y = y;
  4819. };
  4820. /**
  4821. * Determines if a given vector is included in a triangle
  4822. * @param p defines the vector to test
  4823. * @param p0 defines 1st triangle point
  4824. * @param p1 defines 2nd triangle point
  4825. * @param p2 defines 3rd triangle point
  4826. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  4827. */
  4828. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  4829. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  4830. var sign = a < 0 ? -1 : 1;
  4831. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  4832. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  4833. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  4834. };
  4835. /**
  4836. * Gets the distance between the vectors "value1" and "value2"
  4837. * @param value1 defines first vector
  4838. * @param value2 defines second vector
  4839. * @returns the distance between vectors
  4840. */
  4841. Vector2.Distance = function (value1, value2) {
  4842. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  4843. };
  4844. /**
  4845. * Returns the squared distance between the vectors "value1" and "value2"
  4846. * @param value1 defines first vector
  4847. * @param value2 defines second vector
  4848. * @returns the squared distance between vectors
  4849. */
  4850. Vector2.DistanceSquared = function (value1, value2) {
  4851. var x = value1.x - value2.x;
  4852. var y = value1.y - value2.y;
  4853. return (x * x) + (y * y);
  4854. };
  4855. /**
  4856. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  4857. * @param value1 defines first vector
  4858. * @param value2 defines second vector
  4859. * @returns a new Vector2
  4860. */
  4861. Vector2.Center = function (value1, value2) {
  4862. var center = value1.add(value2);
  4863. center.scaleInPlace(0.5);
  4864. return center;
  4865. };
  4866. /**
  4867. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  4868. * @param p defines the middle point
  4869. * @param segA defines one point of the segment
  4870. * @param segB defines the other point of the segment
  4871. * @returns the shortest distance
  4872. */
  4873. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  4874. var l2 = Vector2.DistanceSquared(segA, segB);
  4875. if (l2 === 0.0) {
  4876. return Vector2.Distance(p, segA);
  4877. }
  4878. var v = segB.subtract(segA);
  4879. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  4880. var proj = segA.add(v.multiplyByFloats(t, t));
  4881. return Vector2.Distance(p, proj);
  4882. };
  4883. return Vector2;
  4884. }());
  4885. BABYLON.Vector2 = Vector2;
  4886. /**
  4887. * Classed used to store (x,y,z) vector representation
  4888. * A Vector3 is the main object used in 3D geometry
  4889. * It can represent etiher the coordinates of a point the space, either a direction
  4890. * Reminder: Babylon.js uses a left handed forward facing system
  4891. */
  4892. var Vector3 = /** @class */ (function () {
  4893. /**
  4894. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  4895. * @param x defines the first coordinates (on X axis)
  4896. * @param y defines the second coordinates (on Y axis)
  4897. * @param z defines the third coordinates (on Z axis)
  4898. */
  4899. function Vector3(
  4900. /**
  4901. * Defines the first coordinates (on X axis)
  4902. */
  4903. x,
  4904. /**
  4905. * Defines the second coordinates (on Y axis)
  4906. */
  4907. y,
  4908. /**
  4909. * Defines the third coordinates (on Z axis)
  4910. */
  4911. z) {
  4912. if (x === void 0) { x = 0; }
  4913. if (y === void 0) { y = 0; }
  4914. if (z === void 0) { z = 0; }
  4915. this.x = x;
  4916. this.y = y;
  4917. this.z = z;
  4918. }
  4919. /**
  4920. * Creates a string representation of the Vector3
  4921. * @returns a string with the Vector3 coordinates.
  4922. */
  4923. Vector3.prototype.toString = function () {
  4924. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  4925. };
  4926. /**
  4927. * Gets the class name
  4928. * @returns the string "Vector3"
  4929. */
  4930. Vector3.prototype.getClassName = function () {
  4931. return "Vector3";
  4932. };
  4933. /**
  4934. * Creates the Vector3 hash code
  4935. * @returns a number which tends to be unique between Vector3 instances
  4936. */
  4937. Vector3.prototype.getHashCode = function () {
  4938. var hash = this.x || 0;
  4939. hash = (hash * 397) ^ (this.y || 0);
  4940. hash = (hash * 397) ^ (this.z || 0);
  4941. return hash;
  4942. };
  4943. // Operators
  4944. /**
  4945. * Creates an array containing three elements : the coordinates of the Vector3
  4946. * @returns a new array of numbers
  4947. */
  4948. Vector3.prototype.asArray = function () {
  4949. var result = [];
  4950. this.toArray(result, 0);
  4951. return result;
  4952. };
  4953. /**
  4954. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  4955. * @param array defines the destination array
  4956. * @param index defines the offset in the destination array
  4957. * @returns the current Vector3
  4958. */
  4959. Vector3.prototype.toArray = function (array, index) {
  4960. if (index === void 0) { index = 0; }
  4961. array[index] = this.x;
  4962. array[index + 1] = this.y;
  4963. array[index + 2] = this.z;
  4964. return this;
  4965. };
  4966. /**
  4967. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  4968. * @returns a new Quaternion object, computed from the Vector3 coordinates
  4969. */
  4970. Vector3.prototype.toQuaternion = function () {
  4971. return BABYLON.Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  4972. };
  4973. /**
  4974. * Adds the given vector to the current Vector3
  4975. * @param otherVector defines the second operand
  4976. * @returns the current updated Vector3
  4977. */
  4978. Vector3.prototype.addInPlace = function (otherVector) {
  4979. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  4980. };
  4981. /**
  4982. * Adds the given coordinates to the current Vector3
  4983. * @param x defines the x coordinate of the operand
  4984. * @param y defines the y coordinate of the operand
  4985. * @param z defines the z coordinate of the operand
  4986. * @returns the current updated Vector3
  4987. */
  4988. Vector3.prototype.addInPlaceFromFloats = function (x, y, z) {
  4989. this.x += x;
  4990. this.y += y;
  4991. this.z += z;
  4992. return this;
  4993. };
  4994. /**
  4995. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  4996. * @param otherVector defines the second operand
  4997. * @returns the resulting Vector3
  4998. */
  4999. Vector3.prototype.add = function (otherVector) {
  5000. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5001. };
  5002. /**
  5003. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  5004. * @param otherVector defines the second operand
  5005. * @param result defines the Vector3 object where to store the result
  5006. * @returns the current Vector3
  5007. */
  5008. Vector3.prototype.addToRef = function (otherVector, result) {
  5009. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5010. };
  5011. /**
  5012. * Subtract the given vector from the current Vector3
  5013. * @param otherVector defines the second operand
  5014. * @returns the current updated Vector3
  5015. */
  5016. Vector3.prototype.subtractInPlace = function (otherVector) {
  5017. this.x -= otherVector.x;
  5018. this.y -= otherVector.y;
  5019. this.z -= otherVector.z;
  5020. return this;
  5021. };
  5022. /**
  5023. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  5024. * @param otherVector defines the second operand
  5025. * @returns the resulting Vector3
  5026. */
  5027. Vector3.prototype.subtract = function (otherVector) {
  5028. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  5029. };
  5030. /**
  5031. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  5032. * @param otherVector defines the second operand
  5033. * @param result defines the Vector3 object where to store the result
  5034. * @returns the current Vector3
  5035. */
  5036. Vector3.prototype.subtractToRef = function (otherVector, result) {
  5037. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  5038. };
  5039. /**
  5040. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  5041. * @param x defines the x coordinate of the operand
  5042. * @param y defines the y coordinate of the operand
  5043. * @param z defines the z coordinate of the operand
  5044. * @returns the resulting Vector3
  5045. */
  5046. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  5047. return new Vector3(this.x - x, this.y - y, this.z - z);
  5048. };
  5049. /**
  5050. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  5051. * @param x defines the x coordinate of the operand
  5052. * @param y defines the y coordinate of the operand
  5053. * @param z defines the z coordinate of the operand
  5054. * @param result defines the Vector3 object where to store the result
  5055. * @returns the current Vector3
  5056. */
  5057. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  5058. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  5059. };
  5060. /**
  5061. * Gets a new Vector3 set with the current Vector3 negated coordinates
  5062. * @returns a new Vector3
  5063. */
  5064. Vector3.prototype.negate = function () {
  5065. return new Vector3(-this.x, -this.y, -this.z);
  5066. };
  5067. /**
  5068. * Multiplies the Vector3 coordinates by the float "scale"
  5069. * @param scale defines the multiplier factor
  5070. * @returns the current updated Vector3
  5071. */
  5072. Vector3.prototype.scaleInPlace = function (scale) {
  5073. this.x *= scale;
  5074. this.y *= scale;
  5075. this.z *= scale;
  5076. return this;
  5077. };
  5078. /**
  5079. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  5080. * @param scale defines the multiplier factor
  5081. * @returns a new Vector3
  5082. */
  5083. Vector3.prototype.scale = function (scale) {
  5084. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  5085. };
  5086. /**
  5087. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  5088. * @param scale defines the multiplier factor
  5089. * @param result defines the Vector3 object where to store the result
  5090. * @returns the current Vector3
  5091. */
  5092. Vector3.prototype.scaleToRef = function (scale, result) {
  5093. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5094. };
  5095. /**
  5096. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  5097. * @param scale defines the scale factor
  5098. * @param result defines the Vector3 object where to store the result
  5099. * @returns the unmodified current Vector3
  5100. */
  5101. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  5102. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5103. };
  5104. /**
  5105. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  5106. * @param otherVector defines the second operand
  5107. * @returns true if both vectors are equals
  5108. */
  5109. Vector3.prototype.equals = function (otherVector) {
  5110. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  5111. };
  5112. /**
  5113. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  5114. * @param otherVector defines the second operand
  5115. * @param epsilon defines the minimal distance to define values as equals
  5116. * @returns true if both vectors are distant less than epsilon
  5117. */
  5118. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  5119. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  5120. 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);
  5121. };
  5122. /**
  5123. * Returns true if the current Vector3 coordinates equals the given floats
  5124. * @param x defines the x coordinate of the operand
  5125. * @param y defines the y coordinate of the operand
  5126. * @param z defines the z coordinate of the operand
  5127. * @returns true if both vectors are equals
  5128. */
  5129. Vector3.prototype.equalsToFloats = function (x, y, z) {
  5130. return this.x === x && this.y === y && this.z === z;
  5131. };
  5132. /**
  5133. * Multiplies the current Vector3 coordinates by the given ones
  5134. * @param otherVector defines the second operand
  5135. * @returns the current updated Vector3
  5136. */
  5137. Vector3.prototype.multiplyInPlace = function (otherVector) {
  5138. this.x *= otherVector.x;
  5139. this.y *= otherVector.y;
  5140. this.z *= otherVector.z;
  5141. return this;
  5142. };
  5143. /**
  5144. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  5145. * @param otherVector defines the second operand
  5146. * @returns the new Vector3
  5147. */
  5148. Vector3.prototype.multiply = function (otherVector) {
  5149. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  5150. };
  5151. /**
  5152. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  5153. * @param otherVector defines the second operand
  5154. * @param result defines the Vector3 object where to store the result
  5155. * @returns the current Vector3
  5156. */
  5157. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  5158. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  5159. };
  5160. /**
  5161. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  5162. * @param x defines the x coordinate of the operand
  5163. * @param y defines the y coordinate of the operand
  5164. * @param z defines the z coordinate of the operand
  5165. * @returns the new Vector3
  5166. */
  5167. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  5168. return new Vector3(this.x * x, this.y * y, this.z * z);
  5169. };
  5170. /**
  5171. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  5172. * @param otherVector defines the second operand
  5173. * @returns the new Vector3
  5174. */
  5175. Vector3.prototype.divide = function (otherVector) {
  5176. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5177. };
  5178. /**
  5179. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  5180. * @param otherVector defines the second operand
  5181. * @param result defines the Vector3 object where to store the result
  5182. * @returns the current Vector3
  5183. */
  5184. Vector3.prototype.divideToRef = function (otherVector, result) {
  5185. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5186. };
  5187. /**
  5188. * Divides the current Vector3 coordinates by the given ones.
  5189. * @param otherVector defines the second operand
  5190. * @returns the current updated Vector3
  5191. */
  5192. Vector3.prototype.divideInPlace = function (otherVector) {
  5193. return this.divideToRef(otherVector, this);
  5194. };
  5195. /**
  5196. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  5197. * @param other defines the second operand
  5198. * @returns the current updated Vector3
  5199. */
  5200. Vector3.prototype.minimizeInPlace = function (other) {
  5201. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  5202. };
  5203. /**
  5204. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  5205. * @param other defines the second operand
  5206. * @returns the current updated Vector3
  5207. */
  5208. Vector3.prototype.maximizeInPlace = function (other) {
  5209. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  5210. };
  5211. /**
  5212. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  5213. * @param x defines the x coordinate of the operand
  5214. * @param y defines the y coordinate of the operand
  5215. * @param z defines the z coordinate of the operand
  5216. * @returns the current updated Vector3
  5217. */
  5218. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  5219. if (x < this.x) {
  5220. this.x = x;
  5221. }
  5222. if (y < this.y) {
  5223. this.y = y;
  5224. }
  5225. if (z < this.z) {
  5226. this.z = z;
  5227. }
  5228. return this;
  5229. };
  5230. /**
  5231. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  5232. * @param x defines the x coordinate of the operand
  5233. * @param y defines the y coordinate of the operand
  5234. * @param z defines the z coordinate of the operand
  5235. * @returns the current updated Vector3
  5236. */
  5237. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  5238. if (x > this.x) {
  5239. this.x = x;
  5240. }
  5241. if (y > this.y) {
  5242. this.y = y;
  5243. }
  5244. if (z > this.z) {
  5245. this.z = z;
  5246. }
  5247. return this;
  5248. };
  5249. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  5250. /**
  5251. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  5252. */
  5253. get: function () {
  5254. var absX = Math.abs(this.x);
  5255. var absY = Math.abs(this.y);
  5256. if (absX !== absY) {
  5257. return true;
  5258. }
  5259. var absZ = Math.abs(this.z);
  5260. if (absX !== absZ) {
  5261. return true;
  5262. }
  5263. if (absY !== absZ) {
  5264. return true;
  5265. }
  5266. return false;
  5267. },
  5268. enumerable: true,
  5269. configurable: true
  5270. });
  5271. /**
  5272. * Gets a new Vector3 from current Vector3 floored values
  5273. * @returns a new Vector3
  5274. */
  5275. Vector3.prototype.floor = function () {
  5276. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  5277. };
  5278. /**
  5279. * Gets a new Vector3 from current Vector3 floored values
  5280. * @returns a new Vector3
  5281. */
  5282. Vector3.prototype.fract = function () {
  5283. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  5284. };
  5285. // Properties
  5286. /**
  5287. * Gets the length of the Vector3
  5288. * @returns the length of the Vecto3
  5289. */
  5290. Vector3.prototype.length = function () {
  5291. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  5292. };
  5293. /**
  5294. * Gets the squared length of the Vector3
  5295. * @returns squared length of the Vector3
  5296. */
  5297. Vector3.prototype.lengthSquared = function () {
  5298. return (this.x * this.x + this.y * this.y + this.z * this.z);
  5299. };
  5300. /**
  5301. * Normalize the current Vector3.
  5302. * Please note that this is an in place operation.
  5303. * @returns the current updated Vector3
  5304. */
  5305. Vector3.prototype.normalize = function () {
  5306. return this.normalizeFromLength(this.length());
  5307. };
  5308. /**
  5309. * Normalize the current Vector3 with the given input length.
  5310. * Please note that this is an in place operation.
  5311. * @param len the length of the vector
  5312. * @returns the current updated Vector3
  5313. */
  5314. Vector3.prototype.normalizeFromLength = function (len) {
  5315. if (len === 0 || len === 1.0) {
  5316. return this;
  5317. }
  5318. return this.scaleInPlace(1.0 / len);
  5319. };
  5320. /**
  5321. * Normalize the current Vector3 to a new vector
  5322. * @returns the new Vector3
  5323. */
  5324. Vector3.prototype.normalizeToNew = function () {
  5325. var normalized = new Vector3(0, 0, 0);
  5326. this.normalizeToRef(normalized);
  5327. return normalized;
  5328. };
  5329. /**
  5330. * Normalize the current Vector3 to the reference
  5331. * @param reference define the Vector3 to update
  5332. * @returns the updated Vector3
  5333. */
  5334. Vector3.prototype.normalizeToRef = function (reference) {
  5335. var len = this.length();
  5336. if (len === 0 || len === 1.0) {
  5337. return reference.copyFromFloats(this.x, this.y, this.z);
  5338. }
  5339. return this.scaleToRef(1.0 / len, reference);
  5340. };
  5341. /**
  5342. * Creates a new Vector3 copied from the current Vector3
  5343. * @returns the new Vector3
  5344. */
  5345. Vector3.prototype.clone = function () {
  5346. return new Vector3(this.x, this.y, this.z);
  5347. };
  5348. /**
  5349. * Copies the given vector coordinates to the current Vector3 ones
  5350. * @param source defines the source Vector3
  5351. * @returns the current updated Vector3
  5352. */
  5353. Vector3.prototype.copyFrom = function (source) {
  5354. return this.copyFromFloats(source.x, source.y, source.z);
  5355. };
  5356. /**
  5357. * Copies the given floats to the current Vector3 coordinates
  5358. * @param x defines the x coordinate of the operand
  5359. * @param y defines the y coordinate of the operand
  5360. * @param z defines the z coordinate of the operand
  5361. * @returns the current updated Vector3
  5362. */
  5363. Vector3.prototype.copyFromFloats = function (x, y, z) {
  5364. this.x = x;
  5365. this.y = y;
  5366. this.z = z;
  5367. return this;
  5368. };
  5369. /**
  5370. * Copies the given floats to the current Vector3 coordinates
  5371. * @param x defines the x coordinate of the operand
  5372. * @param y defines the y coordinate of the operand
  5373. * @param z defines the z coordinate of the operand
  5374. * @returns the current updated Vector3
  5375. */
  5376. Vector3.prototype.set = function (x, y, z) {
  5377. return this.copyFromFloats(x, y, z);
  5378. };
  5379. /**
  5380. * Copies the given float to the current Vector3 coordinates
  5381. * @param v defines the x, y and z coordinates of the operand
  5382. * @returns the current updated Vector3
  5383. */
  5384. Vector3.prototype.setAll = function (v) {
  5385. this.x = this.y = this.z = v;
  5386. return this;
  5387. };
  5388. // Statics
  5389. /**
  5390. * Get the clip factor between two vectors
  5391. * @param vector0 defines the first operand
  5392. * @param vector1 defines the second operand
  5393. * @param axis defines the axis to use
  5394. * @param size defines the size along the axis
  5395. * @returns the clip factor
  5396. */
  5397. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  5398. var d0 = Vector3.Dot(vector0, axis) - size;
  5399. var d1 = Vector3.Dot(vector1, axis) - size;
  5400. var s = d0 / (d0 - d1);
  5401. return s;
  5402. };
  5403. /**
  5404. * Get angle between two vectors
  5405. * @param vector0 angle between vector0 and vector1
  5406. * @param vector1 angle between vector0 and vector1
  5407. * @param normal direction of the normal
  5408. * @return the angle between vector0 and vector1
  5409. */
  5410. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  5411. var v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  5412. var v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  5413. var dot = Vector3.Dot(v0, v1);
  5414. var n = MathTmp.Vector3[3];
  5415. Vector3.CrossToRef(v0, v1, n);
  5416. if (Vector3.Dot(n, normal) > 0) {
  5417. return Math.acos(dot);
  5418. }
  5419. return -Math.acos(dot);
  5420. };
  5421. /**
  5422. * Returns a new Vector3 set from the index "offset" of the given array
  5423. * @param array defines the source array
  5424. * @param offset defines the offset in the source array
  5425. * @returns the new Vector3
  5426. */
  5427. Vector3.FromArray = function (array, offset) {
  5428. if (offset === void 0) { offset = 0; }
  5429. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  5430. };
  5431. /**
  5432. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  5433. * This function is deprecated. Use FromArray instead
  5434. * @param array defines the source array
  5435. * @param offset defines the offset in the source array
  5436. * @returns the new Vector3
  5437. */
  5438. Vector3.FromFloatArray = function (array, offset) {
  5439. return Vector3.FromArray(array, offset);
  5440. };
  5441. /**
  5442. * Sets the given vector "result" with the element values from the index "offset" of the given array
  5443. * @param array defines the source array
  5444. * @param offset defines the offset in the source array
  5445. * @param result defines the Vector3 where to store the result
  5446. */
  5447. Vector3.FromArrayToRef = function (array, offset, result) {
  5448. result.x = array[offset];
  5449. result.y = array[offset + 1];
  5450. result.z = array[offset + 2];
  5451. };
  5452. /**
  5453. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  5454. * This function is deprecated. Use FromArrayToRef instead.
  5455. * @param array defines the source array
  5456. * @param offset defines the offset in the source array
  5457. * @param result defines the Vector3 where to store the result
  5458. */
  5459. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  5460. return Vector3.FromArrayToRef(array, offset, result);
  5461. };
  5462. /**
  5463. * Sets the given vector "result" with the given floats.
  5464. * @param x defines the x coordinate of the source
  5465. * @param y defines the y coordinate of the source
  5466. * @param z defines the z coordinate of the source
  5467. * @param result defines the Vector3 where to store the result
  5468. */
  5469. Vector3.FromFloatsToRef = function (x, y, z, result) {
  5470. result.copyFromFloats(x, y, z);
  5471. };
  5472. /**
  5473. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  5474. * @returns a new empty Vector3
  5475. */
  5476. Vector3.Zero = function () {
  5477. return new Vector3(0.0, 0.0, 0.0);
  5478. };
  5479. /**
  5480. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  5481. * @returns a new unit Vector3
  5482. */
  5483. Vector3.One = function () {
  5484. return new Vector3(1.0, 1.0, 1.0);
  5485. };
  5486. /**
  5487. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  5488. * @returns a new up Vector3
  5489. */
  5490. Vector3.Up = function () {
  5491. return new Vector3(0.0, 1.0, 0.0);
  5492. };
  5493. /**
  5494. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  5495. * @returns a new down Vector3
  5496. */
  5497. Vector3.Down = function () {
  5498. return new Vector3(0.0, -1.0, 0.0);
  5499. };
  5500. /**
  5501. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  5502. * @returns a new forward Vector3
  5503. */
  5504. Vector3.Forward = function () {
  5505. return new Vector3(0.0, 0.0, 1.0);
  5506. };
  5507. /**
  5508. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  5509. * @returns a new forward Vector3
  5510. */
  5511. Vector3.Backward = function () {
  5512. return new Vector3(0.0, 0.0, -1.0);
  5513. };
  5514. /**
  5515. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  5516. * @returns a new right Vector3
  5517. */
  5518. Vector3.Right = function () {
  5519. return new Vector3(1.0, 0.0, 0.0);
  5520. };
  5521. /**
  5522. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  5523. * @returns a new left Vector3
  5524. */
  5525. Vector3.Left = function () {
  5526. return new Vector3(-1.0, 0.0, 0.0);
  5527. };
  5528. /**
  5529. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  5530. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5531. * @param vector defines the Vector3 to transform
  5532. * @param transformation defines the transformation matrix
  5533. * @returns the transformed Vector3
  5534. */
  5535. Vector3.TransformCoordinates = function (vector, transformation) {
  5536. var result = Vector3.Zero();
  5537. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  5538. return result;
  5539. };
  5540. /**
  5541. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  5542. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5543. * @param vector defines the Vector3 to transform
  5544. * @param transformation defines the transformation matrix
  5545. * @param result defines the Vector3 where to store the result
  5546. */
  5547. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  5548. return Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5549. };
  5550. /**
  5551. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  5552. * This method computes tranformed coordinates only, not transformed direction vectors
  5553. * @param x define the x coordinate of the source vector
  5554. * @param y define the y coordinate of the source vector
  5555. * @param z define the z coordinate of the source vector
  5556. * @param transformation defines the transformation matrix
  5557. * @param result defines the Vector3 where to store the result
  5558. */
  5559. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  5560. var m = transformation.m;
  5561. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  5562. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  5563. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  5564. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  5565. result.x = rx * rw;
  5566. result.y = ry * rw;
  5567. result.z = rz * rw;
  5568. };
  5569. /**
  5570. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  5571. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5572. * @param vector defines the Vector3 to transform
  5573. * @param transformation defines the transformation matrix
  5574. * @returns the new Vector3
  5575. */
  5576. Vector3.TransformNormal = function (vector, transformation) {
  5577. var result = Vector3.Zero();
  5578. Vector3.TransformNormalToRef(vector, transformation, result);
  5579. return result;
  5580. };
  5581. /**
  5582. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  5583. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5584. * @param vector defines the Vector3 to transform
  5585. * @param transformation defines the transformation matrix
  5586. * @param result defines the Vector3 where to store the result
  5587. */
  5588. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  5589. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5590. };
  5591. /**
  5592. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  5593. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5594. * @param x define the x coordinate of the source vector
  5595. * @param y define the y coordinate of the source vector
  5596. * @param z define the z coordinate of the source vector
  5597. * @param transformation defines the transformation matrix
  5598. * @param result defines the Vector3 where to store the result
  5599. */
  5600. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  5601. var m = transformation.m;
  5602. result.x = x * m[0] + y * m[4] + z * m[8];
  5603. result.y = x * m[1] + y * m[5] + z * m[9];
  5604. result.z = x * m[2] + y * m[6] + z * m[10];
  5605. };
  5606. /**
  5607. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  5608. * @param value1 defines the first control point
  5609. * @param value2 defines the second control point
  5610. * @param value3 defines the third control point
  5611. * @param value4 defines the fourth control point
  5612. * @param amount defines the amount on the spline to use
  5613. * @returns the new Vector3
  5614. */
  5615. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  5616. var squared = amount * amount;
  5617. var cubed = amount * squared;
  5618. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  5619. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  5620. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  5621. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  5622. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  5623. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  5624. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  5625. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  5626. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  5627. return new Vector3(x, y, z);
  5628. };
  5629. /**
  5630. * 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"
  5631. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5632. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5633. * @param value defines the current value
  5634. * @param min defines the lower range value
  5635. * @param max defines the upper range value
  5636. * @returns the new Vector3
  5637. */
  5638. Vector3.Clamp = function (value, min, max) {
  5639. var v = new Vector3();
  5640. Vector3.ClampToRef(value, min, max, v);
  5641. return v;
  5642. };
  5643. /**
  5644. * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  5645. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5646. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5647. * @param value defines the current value
  5648. * @param min defines the lower range value
  5649. * @param max defines the upper range value
  5650. * @param result defines the Vector3 where to store the result
  5651. */
  5652. Vector3.ClampToRef = function (value, min, max, result) {
  5653. var x = value.x;
  5654. x = (x > max.x) ? max.x : x;
  5655. x = (x < min.x) ? min.x : x;
  5656. var y = value.y;
  5657. y = (y > max.y) ? max.y : y;
  5658. y = (y < min.y) ? min.y : y;
  5659. var z = value.z;
  5660. z = (z > max.z) ? max.z : z;
  5661. z = (z < min.z) ? min.z : z;
  5662. result.copyFromFloats(x, y, z);
  5663. };
  5664. /**
  5665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  5666. * @param value1 defines the first control point
  5667. * @param tangent1 defines the first tangent vector
  5668. * @param value2 defines the second control point
  5669. * @param tangent2 defines the second tangent vector
  5670. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  5671. * @returns the new Vector3
  5672. */
  5673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5674. var squared = amount * amount;
  5675. var cubed = amount * squared;
  5676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5678. var part3 = (cubed - (2.0 * squared)) + amount;
  5679. var part4 = cubed - squared;
  5680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5683. return new Vector3(x, y, z);
  5684. };
  5685. /**
  5686. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  5687. * @param start defines the start value
  5688. * @param end defines the end value
  5689. * @param amount max defines amount between both (between 0 and 1)
  5690. * @returns the new Vector3
  5691. */
  5692. Vector3.Lerp = function (start, end, amount) {
  5693. var result = new Vector3(0, 0, 0);
  5694. Vector3.LerpToRef(start, end, amount, result);
  5695. return result;
  5696. };
  5697. /**
  5698. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  5699. * @param start defines the start value
  5700. * @param end defines the end value
  5701. * @param amount max defines amount between both (between 0 and 1)
  5702. * @param result defines the Vector3 where to store the result
  5703. */
  5704. Vector3.LerpToRef = function (start, end, amount, result) {
  5705. result.x = start.x + ((end.x - start.x) * amount);
  5706. result.y = start.y + ((end.y - start.y) * amount);
  5707. result.z = start.z + ((end.z - start.z) * amount);
  5708. };
  5709. /**
  5710. * Returns the dot product (float) between the vectors "left" and "right"
  5711. * @param left defines the left operand
  5712. * @param right defines the right operand
  5713. * @returns the dot product
  5714. */
  5715. Vector3.Dot = function (left, right) {
  5716. return (left.x * right.x + left.y * right.y + left.z * right.z);
  5717. };
  5718. /**
  5719. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  5720. * The cross product is then orthogonal to both "left" and "right"
  5721. * @param left defines the left operand
  5722. * @param right defines the right operand
  5723. * @returns the cross product
  5724. */
  5725. Vector3.Cross = function (left, right) {
  5726. var result = Vector3.Zero();
  5727. Vector3.CrossToRef(left, right, result);
  5728. return result;
  5729. };
  5730. /**
  5731. * Sets the given vector "result" with the cross product of "left" and "right"
  5732. * The cross product is then orthogonal to both "left" and "right"
  5733. * @param left defines the left operand
  5734. * @param right defines the right operand
  5735. * @param result defines the Vector3 where to store the result
  5736. */
  5737. Vector3.CrossToRef = function (left, right, result) {
  5738. var x = left.y * right.z - left.z * right.y;
  5739. var y = left.z * right.x - left.x * right.z;
  5740. var z = left.x * right.y - left.y * right.x;
  5741. result.copyFromFloats(x, y, z);
  5742. };
  5743. /**
  5744. * Returns a new Vector3 as the normalization of the given vector
  5745. * @param vector defines the Vector3 to normalize
  5746. * @returns the new Vector3
  5747. */
  5748. Vector3.Normalize = function (vector) {
  5749. var result = Vector3.Zero();
  5750. Vector3.NormalizeToRef(vector, result);
  5751. return result;
  5752. };
  5753. /**
  5754. * Sets the given vector "result" with the normalization of the given first vector
  5755. * @param vector defines the Vector3 to normalize
  5756. * @param result defines the Vector3 where to store the result
  5757. */
  5758. Vector3.NormalizeToRef = function (vector, result) {
  5759. vector.normalizeToRef(result);
  5760. };
  5761. /**
  5762. * Project a Vector3 onto screen space
  5763. * @param vector defines the Vector3 to project
  5764. * @param world defines the world matrix to use
  5765. * @param transform defines the transform (view x projection) matrix to use
  5766. * @param viewport defines the screen viewport to use
  5767. * @returns the new Vector3
  5768. */
  5769. Vector3.Project = function (vector, world, transform, viewport) {
  5770. var cw = viewport.width;
  5771. var ch = viewport.height;
  5772. var cx = viewport.x;
  5773. var cy = viewport.y;
  5774. var viewportMatrix = MathTmp.Matrix[1];
  5775. 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);
  5776. var matrix = MathTmp.Matrix[0];
  5777. world.multiplyToRef(transform, matrix);
  5778. matrix.multiplyToRef(viewportMatrix, matrix);
  5779. return Vector3.TransformCoordinates(vector, matrix);
  5780. };
  5781. /** @hidden */
  5782. Vector3.UnprojectFromInvertedMatrixToRef = function (source, matrix, result) {
  5783. Vector3.TransformCoordinatesToRef(source, matrix, result);
  5784. var m = matrix.m;
  5785. var num = source.x * m[3] + source.y * m[7] + source.z * m[11] + m[15];
  5786. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5787. result.scaleInPlace(1.0 / num);
  5788. }
  5789. };
  5790. /**
  5791. * Unproject from screen space to object space
  5792. * @param source defines the screen space Vector3 to use
  5793. * @param viewportWidth defines the current width of the viewport
  5794. * @param viewportHeight defines the current height of the viewport
  5795. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5796. * @param transform defines the transform (view x projection) matrix to use
  5797. * @returns the new Vector3
  5798. */
  5799. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5800. var matrix = MathTmp.Matrix[0];
  5801. world.multiplyToRef(transform, matrix);
  5802. matrix.invert();
  5803. source.x = source.x / viewportWidth * 2 - 1;
  5804. source.y = -(source.y / viewportHeight * 2 - 1);
  5805. var vector = new Vector3();
  5806. Vector3.UnprojectFromInvertedMatrixToRef(source, matrix, vector);
  5807. return vector;
  5808. };
  5809. /**
  5810. * Unproject from screen space to object space
  5811. * @param source defines the screen space Vector3 to use
  5812. * @param viewportWidth defines the current width of the viewport
  5813. * @param viewportHeight defines the current height of the viewport
  5814. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5815. * @param view defines the view matrix to use
  5816. * @param projection defines the projection matrix to use
  5817. * @returns the new Vector3
  5818. */
  5819. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5820. var result = Vector3.Zero();
  5821. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5822. return result;
  5823. };
  5824. /**
  5825. * Unproject from screen space to object space
  5826. * @param source defines the screen space Vector3 to use
  5827. * @param viewportWidth defines the current width of the viewport
  5828. * @param viewportHeight defines the current height of the viewport
  5829. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5830. * @param view defines the view matrix to use
  5831. * @param projection defines the projection matrix to use
  5832. * @param result defines the Vector3 where to store the result
  5833. */
  5834. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  5835. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  5836. };
  5837. /**
  5838. * Unproject from screen space to object space
  5839. * @param sourceX defines the screen space x coordinate to use
  5840. * @param sourceY defines the screen space y coordinate to use
  5841. * @param sourceZ defines the screen space z coordinate to use
  5842. * @param viewportWidth defines the current width of the viewport
  5843. * @param viewportHeight defines the current height of the viewport
  5844. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5845. * @param view defines the view matrix to use
  5846. * @param projection defines the projection matrix to use
  5847. * @param result defines the Vector3 where to store the result
  5848. */
  5849. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  5850. var matrix = MathTmp.Matrix[0];
  5851. world.multiplyToRef(view, matrix);
  5852. matrix.multiplyToRef(projection, matrix);
  5853. matrix.invert();
  5854. var screenSource = MathTmp.Vector3[0];
  5855. screenSource.x = sourceX / viewportWidth * 2 - 1;
  5856. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5857. screenSource.z = 2 * sourceZ - 1.0;
  5858. Vector3.UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
  5859. };
  5860. /**
  5861. * Unproject a ray from screen space to object space
  5862. * @param sourceX defines the screen space x coordinate to use
  5863. * @param sourceY defines the screen space y coordinate to use
  5864. * @param viewportWidth defines the current width of the viewport
  5865. * @param viewportHeight defines the current height of the viewport
  5866. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5867. * @param view defines the view matrix to use
  5868. * @param projection defines the projection matrix to use
  5869. * @param ray defines the Ray where to store the result
  5870. */
  5871. Vector3.UnprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection, ray) {
  5872. var matrix = MathTmp.Matrix[0];
  5873. world.multiplyToRef(view, matrix);
  5874. matrix.multiplyToRef(projection, matrix);
  5875. matrix.invert();
  5876. var nearScreenSource = MathTmp.Vector3[0];
  5877. nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
  5878. nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5879. nearScreenSource.z = -1.0;
  5880. var farScreenSource = MathTmp.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
  5881. var nearVec3 = MathTmp.Vector3[2];
  5882. var farVec3 = MathTmp.Vector3[3];
  5883. Vector3.UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
  5884. Vector3.UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
  5885. ray.origin.copyFrom(nearVec3);
  5886. farVec3.subtractToRef(nearVec3, ray.direction);
  5887. ray.direction.normalize();
  5888. };
  5889. /**
  5890. * Gets the minimal coordinate values between two Vector3
  5891. * @param left defines the first operand
  5892. * @param right defines the second operand
  5893. * @returns the new Vector3
  5894. */
  5895. Vector3.Minimize = function (left, right) {
  5896. var min = left.clone();
  5897. min.minimizeInPlace(right);
  5898. return min;
  5899. };
  5900. /**
  5901. * Gets the maximal coordinate values between two Vector3
  5902. * @param left defines the first operand
  5903. * @param right defines the second operand
  5904. * @returns the new Vector3
  5905. */
  5906. Vector3.Maximize = function (left, right) {
  5907. var max = left.clone();
  5908. max.maximizeInPlace(right);
  5909. return max;
  5910. };
  5911. /**
  5912. * Returns the distance between the vectors "value1" and "value2"
  5913. * @param value1 defines the first operand
  5914. * @param value2 defines the second operand
  5915. * @returns the distance
  5916. */
  5917. Vector3.Distance = function (value1, value2) {
  5918. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  5919. };
  5920. /**
  5921. * Returns the squared distance between the vectors "value1" and "value2"
  5922. * @param value1 defines the first operand
  5923. * @param value2 defines the second operand
  5924. * @returns the squared distance
  5925. */
  5926. Vector3.DistanceSquared = function (value1, value2) {
  5927. var x = value1.x - value2.x;
  5928. var y = value1.y - value2.y;
  5929. var z = value1.z - value2.z;
  5930. return (x * x) + (y * y) + (z * z);
  5931. };
  5932. /**
  5933. * Returns a new Vector3 located at the center between "value1" and "value2"
  5934. * @param value1 defines the first operand
  5935. * @param value2 defines the second operand
  5936. * @returns the new Vector3
  5937. */
  5938. Vector3.Center = function (value1, value2) {
  5939. var center = value1.add(value2);
  5940. center.scaleInPlace(0.5);
  5941. return center;
  5942. };
  5943. /**
  5944. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  5945. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  5946. * to something in order to rotate it from its local system to the given target system
  5947. * Note: axis1, axis2 and axis3 are normalized during this operation
  5948. * @param axis1 defines the first axis
  5949. * @param axis2 defines the second axis
  5950. * @param axis3 defines the third axis
  5951. * @returns a new Vector3
  5952. */
  5953. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  5954. var rotation = Vector3.Zero();
  5955. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  5956. return rotation;
  5957. };
  5958. /**
  5959. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  5960. * @param axis1 defines the first axis
  5961. * @param axis2 defines the second axis
  5962. * @param axis3 defines the third axis
  5963. * @param ref defines the Vector3 where to store the result
  5964. */
  5965. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5966. var quat = MathTmp.Quaternion[0];
  5967. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5968. quat.toEulerAnglesToRef(ref);
  5969. };
  5970. return Vector3;
  5971. }());
  5972. BABYLON.Vector3 = Vector3;
  5973. /**
  5974. * Vector4 class created for EulerAngle class conversion to Quaternion
  5975. */
  5976. var Vector4 = /** @class */ (function () {
  5977. /**
  5978. * Creates a Vector4 object from the given floats.
  5979. * @param x x value of the vector
  5980. * @param y y value of the vector
  5981. * @param z z value of the vector
  5982. * @param w w value of the vector
  5983. */
  5984. function Vector4(
  5985. /** x value of the vector */
  5986. x,
  5987. /** y value of the vector */
  5988. y,
  5989. /** z value of the vector */
  5990. z,
  5991. /** w value of the vector */
  5992. w) {
  5993. this.x = x;
  5994. this.y = y;
  5995. this.z = z;
  5996. this.w = w;
  5997. }
  5998. /**
  5999. * Returns the string with the Vector4 coordinates.
  6000. * @returns a string containing all the vector values
  6001. */
  6002. Vector4.prototype.toString = function () {
  6003. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6004. };
  6005. /**
  6006. * Returns the string "Vector4".
  6007. * @returns "Vector4"
  6008. */
  6009. Vector4.prototype.getClassName = function () {
  6010. return "Vector4";
  6011. };
  6012. /**
  6013. * Returns the Vector4 hash code.
  6014. * @returns a unique hash code
  6015. */
  6016. Vector4.prototype.getHashCode = function () {
  6017. var hash = this.x || 0;
  6018. hash = (hash * 397) ^ (this.y || 0);
  6019. hash = (hash * 397) ^ (this.z || 0);
  6020. hash = (hash * 397) ^ (this.w || 0);
  6021. return hash;
  6022. };
  6023. // Operators
  6024. /**
  6025. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  6026. * @returns the resulting array
  6027. */
  6028. Vector4.prototype.asArray = function () {
  6029. var result = new Array();
  6030. this.toArray(result, 0);
  6031. return result;
  6032. };
  6033. /**
  6034. * Populates the given array from the given index with the Vector4 coordinates.
  6035. * @param array array to populate
  6036. * @param index index of the array to start at (default: 0)
  6037. * @returns the Vector4.
  6038. */
  6039. Vector4.prototype.toArray = function (array, index) {
  6040. if (index === undefined) {
  6041. index = 0;
  6042. }
  6043. array[index] = this.x;
  6044. array[index + 1] = this.y;
  6045. array[index + 2] = this.z;
  6046. array[index + 3] = this.w;
  6047. return this;
  6048. };
  6049. /**
  6050. * Adds the given vector to the current Vector4.
  6051. * @param otherVector the vector to add
  6052. * @returns the updated Vector4.
  6053. */
  6054. Vector4.prototype.addInPlace = function (otherVector) {
  6055. this.x += otherVector.x;
  6056. this.y += otherVector.y;
  6057. this.z += otherVector.z;
  6058. this.w += otherVector.w;
  6059. return this;
  6060. };
  6061. /**
  6062. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6063. * @param otherVector the vector to add
  6064. * @returns the resulting vector
  6065. */
  6066. Vector4.prototype.add = function (otherVector) {
  6067. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6068. };
  6069. /**
  6070. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6071. * @param otherVector the vector to add
  6072. * @param result the vector to store the result
  6073. * @returns the current Vector4.
  6074. */
  6075. Vector4.prototype.addToRef = function (otherVector, result) {
  6076. result.x = this.x + otherVector.x;
  6077. result.y = this.y + otherVector.y;
  6078. result.z = this.z + otherVector.z;
  6079. result.w = this.w + otherVector.w;
  6080. return this;
  6081. };
  6082. /**
  6083. * Subtract in place the given vector from the current Vector4.
  6084. * @param otherVector the vector to subtract
  6085. * @returns the updated Vector4.
  6086. */
  6087. Vector4.prototype.subtractInPlace = function (otherVector) {
  6088. this.x -= otherVector.x;
  6089. this.y -= otherVector.y;
  6090. this.z -= otherVector.z;
  6091. this.w -= otherVector.w;
  6092. return this;
  6093. };
  6094. /**
  6095. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6096. * @param otherVector the vector to add
  6097. * @returns the new vector with the result
  6098. */
  6099. Vector4.prototype.subtract = function (otherVector) {
  6100. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6101. };
  6102. /**
  6103. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6104. * @param otherVector the vector to subtract
  6105. * @param result the vector to store the result
  6106. * @returns the current Vector4.
  6107. */
  6108. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6109. result.x = this.x - otherVector.x;
  6110. result.y = this.y - otherVector.y;
  6111. result.z = this.z - otherVector.z;
  6112. result.w = this.w - otherVector.w;
  6113. return this;
  6114. };
  6115. /**
  6116. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6117. */
  6118. /**
  6119. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6120. * @param x value to subtract
  6121. * @param y value to subtract
  6122. * @param z value to subtract
  6123. * @param w value to subtract
  6124. * @returns new vector containing the result
  6125. */
  6126. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6127. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6128. };
  6129. /**
  6130. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6131. * @param x value to subtract
  6132. * @param y value to subtract
  6133. * @param z value to subtract
  6134. * @param w value to subtract
  6135. * @param result the vector to store the result in
  6136. * @returns the current Vector4.
  6137. */
  6138. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6139. result.x = this.x - x;
  6140. result.y = this.y - y;
  6141. result.z = this.z - z;
  6142. result.w = this.w - w;
  6143. return this;
  6144. };
  6145. /**
  6146. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6147. * @returns a new vector with the negated values
  6148. */
  6149. Vector4.prototype.negate = function () {
  6150. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6151. };
  6152. /**
  6153. * Multiplies the current Vector4 coordinates by scale (float).
  6154. * @param scale the number to scale with
  6155. * @returns the updated Vector4.
  6156. */
  6157. Vector4.prototype.scaleInPlace = function (scale) {
  6158. this.x *= scale;
  6159. this.y *= scale;
  6160. this.z *= scale;
  6161. this.w *= scale;
  6162. return this;
  6163. };
  6164. /**
  6165. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6166. * @param scale the number to scale with
  6167. * @returns a new vector with the result
  6168. */
  6169. Vector4.prototype.scale = function (scale) {
  6170. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6171. };
  6172. /**
  6173. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6174. * @param scale the number to scale with
  6175. * @param result a vector to store the result in
  6176. * @returns the current Vector4.
  6177. */
  6178. Vector4.prototype.scaleToRef = function (scale, result) {
  6179. result.x = this.x * scale;
  6180. result.y = this.y * scale;
  6181. result.z = this.z * scale;
  6182. result.w = this.w * scale;
  6183. return this;
  6184. };
  6185. /**
  6186. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6187. * @param scale defines the scale factor
  6188. * @param result defines the Vector4 object where to store the result
  6189. * @returns the unmodified current Vector4
  6190. */
  6191. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6192. result.x += this.x * scale;
  6193. result.y += this.y * scale;
  6194. result.z += this.z * scale;
  6195. result.w += this.w * scale;
  6196. return this;
  6197. };
  6198. /**
  6199. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6200. * @param otherVector the vector to compare against
  6201. * @returns true if they are equal
  6202. */
  6203. Vector4.prototype.equals = function (otherVector) {
  6204. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6205. };
  6206. /**
  6207. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6208. * @param otherVector vector to compare against
  6209. * @param epsilon (Default: very small number)
  6210. * @returns true if they are equal
  6211. */
  6212. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6213. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6214. return otherVector
  6215. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6216. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6217. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6218. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6219. };
  6220. /**
  6221. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6222. * @param x x value to compare against
  6223. * @param y y value to compare against
  6224. * @param z z value to compare against
  6225. * @param w w value to compare against
  6226. * @returns true if equal
  6227. */
  6228. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6229. return this.x === x && this.y === y && this.z === z && this.w === w;
  6230. };
  6231. /**
  6232. * Multiplies in place the current Vector4 by the given one.
  6233. * @param otherVector vector to multiple with
  6234. * @returns the updated Vector4.
  6235. */
  6236. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6237. this.x *= otherVector.x;
  6238. this.y *= otherVector.y;
  6239. this.z *= otherVector.z;
  6240. this.w *= otherVector.w;
  6241. return this;
  6242. };
  6243. /**
  6244. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6245. * @param otherVector vector to multiple with
  6246. * @returns resulting new vector
  6247. */
  6248. Vector4.prototype.multiply = function (otherVector) {
  6249. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6250. };
  6251. /**
  6252. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6253. * @param otherVector vector to multiple with
  6254. * @param result vector to store the result
  6255. * @returns the current Vector4.
  6256. */
  6257. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6258. result.x = this.x * otherVector.x;
  6259. result.y = this.y * otherVector.y;
  6260. result.z = this.z * otherVector.z;
  6261. result.w = this.w * otherVector.w;
  6262. return this;
  6263. };
  6264. /**
  6265. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6266. * @param x x value multiply with
  6267. * @param y y value multiply with
  6268. * @param z z value multiply with
  6269. * @param w w value multiply with
  6270. * @returns resulting new vector
  6271. */
  6272. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6273. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6274. };
  6275. /**
  6276. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6277. * @param otherVector vector to devide with
  6278. * @returns resulting new vector
  6279. */
  6280. Vector4.prototype.divide = function (otherVector) {
  6281. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6282. };
  6283. /**
  6284. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6285. * @param otherVector vector to devide with
  6286. * @param result vector to store the result
  6287. * @returns the current Vector4.
  6288. */
  6289. Vector4.prototype.divideToRef = function (otherVector, result) {
  6290. result.x = this.x / otherVector.x;
  6291. result.y = this.y / otherVector.y;
  6292. result.z = this.z / otherVector.z;
  6293. result.w = this.w / otherVector.w;
  6294. return this;
  6295. };
  6296. /**
  6297. * Divides the current Vector3 coordinates by the given ones.
  6298. * @param otherVector vector to devide with
  6299. * @returns the updated Vector3.
  6300. */
  6301. Vector4.prototype.divideInPlace = function (otherVector) {
  6302. return this.divideToRef(otherVector, this);
  6303. };
  6304. /**
  6305. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6306. * @param other defines the second operand
  6307. * @returns the current updated Vector4
  6308. */
  6309. Vector4.prototype.minimizeInPlace = function (other) {
  6310. if (other.x < this.x) {
  6311. this.x = other.x;
  6312. }
  6313. if (other.y < this.y) {
  6314. this.y = other.y;
  6315. }
  6316. if (other.z < this.z) {
  6317. this.z = other.z;
  6318. }
  6319. if (other.w < this.w) {
  6320. this.w = other.w;
  6321. }
  6322. return this;
  6323. };
  6324. /**
  6325. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6326. * @param other defines the second operand
  6327. * @returns the current updated Vector4
  6328. */
  6329. Vector4.prototype.maximizeInPlace = function (other) {
  6330. if (other.x > this.x) {
  6331. this.x = other.x;
  6332. }
  6333. if (other.y > this.y) {
  6334. this.y = other.y;
  6335. }
  6336. if (other.z > this.z) {
  6337. this.z = other.z;
  6338. }
  6339. if (other.w > this.w) {
  6340. this.w = other.w;
  6341. }
  6342. return this;
  6343. };
  6344. /**
  6345. * Gets a new Vector4 from current Vector4 floored values
  6346. * @returns a new Vector4
  6347. */
  6348. Vector4.prototype.floor = function () {
  6349. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6350. };
  6351. /**
  6352. * Gets a new Vector4 from current Vector3 floored values
  6353. * @returns a new Vector4
  6354. */
  6355. Vector4.prototype.fract = function () {
  6356. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  6357. };
  6358. // Properties
  6359. /**
  6360. * Returns the Vector4 length (float).
  6361. * @returns the length
  6362. */
  6363. Vector4.prototype.length = function () {
  6364. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6365. };
  6366. /**
  6367. * Returns the Vector4 squared length (float).
  6368. * @returns the length squared
  6369. */
  6370. Vector4.prototype.lengthSquared = function () {
  6371. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6372. };
  6373. // Methods
  6374. /**
  6375. * Normalizes in place the Vector4.
  6376. * @returns the updated Vector4.
  6377. */
  6378. Vector4.prototype.normalize = function () {
  6379. var len = this.length();
  6380. if (len === 0) {
  6381. return this;
  6382. }
  6383. return this.scaleInPlace(1.0 / len);
  6384. };
  6385. /**
  6386. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6387. * @returns this converted to a new vector3
  6388. */
  6389. Vector4.prototype.toVector3 = function () {
  6390. return new Vector3(this.x, this.y, this.z);
  6391. };
  6392. /**
  6393. * Returns a new Vector4 copied from the current one.
  6394. * @returns the new cloned vector
  6395. */
  6396. Vector4.prototype.clone = function () {
  6397. return new Vector4(this.x, this.y, this.z, this.w);
  6398. };
  6399. /**
  6400. * Updates the current Vector4 with the given one coordinates.
  6401. * @param source the source vector to copy from
  6402. * @returns the updated Vector4.
  6403. */
  6404. Vector4.prototype.copyFrom = function (source) {
  6405. this.x = source.x;
  6406. this.y = source.y;
  6407. this.z = source.z;
  6408. this.w = source.w;
  6409. return this;
  6410. };
  6411. /**
  6412. * Updates the current Vector4 coordinates with the given floats.
  6413. * @param x float to copy from
  6414. * @param y float to copy from
  6415. * @param z float to copy from
  6416. * @param w float to copy from
  6417. * @returns the updated Vector4.
  6418. */
  6419. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6420. this.x = x;
  6421. this.y = y;
  6422. this.z = z;
  6423. this.w = w;
  6424. return this;
  6425. };
  6426. /**
  6427. * Updates the current Vector4 coordinates with the given floats.
  6428. * @param x float to set from
  6429. * @param y float to set from
  6430. * @param z float to set from
  6431. * @param w float to set from
  6432. * @returns the updated Vector4.
  6433. */
  6434. Vector4.prototype.set = function (x, y, z, w) {
  6435. return this.copyFromFloats(x, y, z, w);
  6436. };
  6437. /**
  6438. * Copies the given float to the current Vector3 coordinates
  6439. * @param v defines the x, y, z and w coordinates of the operand
  6440. * @returns the current updated Vector3
  6441. */
  6442. Vector4.prototype.setAll = function (v) {
  6443. this.x = this.y = this.z = this.w = v;
  6444. return this;
  6445. };
  6446. // Statics
  6447. /**
  6448. * Returns a new Vector4 set from the starting index of the given array.
  6449. * @param array the array to pull values from
  6450. * @param offset the offset into the array to start at
  6451. * @returns the new vector
  6452. */
  6453. Vector4.FromArray = function (array, offset) {
  6454. if (!offset) {
  6455. offset = 0;
  6456. }
  6457. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6458. };
  6459. /**
  6460. * Updates the given vector "result" from the starting index of the given array.
  6461. * @param array the array to pull values from
  6462. * @param offset the offset into the array to start at
  6463. * @param result the vector to store the result in
  6464. */
  6465. Vector4.FromArrayToRef = function (array, offset, result) {
  6466. result.x = array[offset];
  6467. result.y = array[offset + 1];
  6468. result.z = array[offset + 2];
  6469. result.w = array[offset + 3];
  6470. };
  6471. /**
  6472. * Updates the given vector "result" from the starting index of the given Float32Array.
  6473. * @param array the array to pull values from
  6474. * @param offset the offset into the array to start at
  6475. * @param result the vector to store the result in
  6476. */
  6477. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6478. Vector4.FromArrayToRef(array, offset, result);
  6479. };
  6480. /**
  6481. * Updates the given vector "result" coordinates from the given floats.
  6482. * @param x float to set from
  6483. * @param y float to set from
  6484. * @param z float to set from
  6485. * @param w float to set from
  6486. * @param result the vector to the floats in
  6487. */
  6488. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6489. result.x = x;
  6490. result.y = y;
  6491. result.z = z;
  6492. result.w = w;
  6493. };
  6494. /**
  6495. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6496. * @returns the new vector
  6497. */
  6498. Vector4.Zero = function () {
  6499. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6500. };
  6501. /**
  6502. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6503. * @returns the new vector
  6504. */
  6505. Vector4.One = function () {
  6506. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6507. };
  6508. /**
  6509. * Returns a new normalized Vector4 from the given one.
  6510. * @param vector the vector to normalize
  6511. * @returns the vector
  6512. */
  6513. Vector4.Normalize = function (vector) {
  6514. var result = Vector4.Zero();
  6515. Vector4.NormalizeToRef(vector, result);
  6516. return result;
  6517. };
  6518. /**
  6519. * Updates the given vector "result" from the normalization of the given one.
  6520. * @param vector the vector to normalize
  6521. * @param result the vector to store the result in
  6522. */
  6523. Vector4.NormalizeToRef = function (vector, result) {
  6524. result.copyFrom(vector);
  6525. result.normalize();
  6526. };
  6527. /**
  6528. * Returns a vector with the minimum values from the left and right vectors
  6529. * @param left left vector to minimize
  6530. * @param right right vector to minimize
  6531. * @returns a new vector with the minimum of the left and right vector values
  6532. */
  6533. Vector4.Minimize = function (left, right) {
  6534. var min = left.clone();
  6535. min.minimizeInPlace(right);
  6536. return min;
  6537. };
  6538. /**
  6539. * Returns a vector with the maximum values from the left and right vectors
  6540. * @param left left vector to maximize
  6541. * @param right right vector to maximize
  6542. * @returns a new vector with the maximum of the left and right vector values
  6543. */
  6544. Vector4.Maximize = function (left, right) {
  6545. var max = left.clone();
  6546. max.maximizeInPlace(right);
  6547. return max;
  6548. };
  6549. /**
  6550. * Returns the distance (float) between the vectors "value1" and "value2".
  6551. * @param value1 value to calulate the distance between
  6552. * @param value2 value to calulate the distance between
  6553. * @return the distance between the two vectors
  6554. */
  6555. Vector4.Distance = function (value1, value2) {
  6556. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6557. };
  6558. /**
  6559. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6560. * @param value1 value to calulate the distance between
  6561. * @param value2 value to calulate the distance between
  6562. * @return the distance between the two vectors squared
  6563. */
  6564. Vector4.DistanceSquared = function (value1, value2) {
  6565. var x = value1.x - value2.x;
  6566. var y = value1.y - value2.y;
  6567. var z = value1.z - value2.z;
  6568. var w = value1.w - value2.w;
  6569. return (x * x) + (y * y) + (z * z) + (w * w);
  6570. };
  6571. /**
  6572. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6573. * @param value1 value to calulate the center between
  6574. * @param value2 value to calulate the center between
  6575. * @return the center between the two vectors
  6576. */
  6577. Vector4.Center = function (value1, value2) {
  6578. var center = value1.add(value2);
  6579. center.scaleInPlace(0.5);
  6580. return center;
  6581. };
  6582. /**
  6583. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6584. * This methods computes transformed normalized direction vectors only.
  6585. * @param vector the vector to transform
  6586. * @param transformation the transformation matrix to apply
  6587. * @returns the new vector
  6588. */
  6589. Vector4.TransformNormal = function (vector, transformation) {
  6590. var result = Vector4.Zero();
  6591. Vector4.TransformNormalToRef(vector, transformation, result);
  6592. return result;
  6593. };
  6594. /**
  6595. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6596. * This methods computes transformed normalized direction vectors only.
  6597. * @param vector the vector to transform
  6598. * @param transformation the transformation matrix to apply
  6599. * @param result the vector to store the result in
  6600. */
  6601. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6602. var m = transformation.m;
  6603. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6604. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6605. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6606. result.x = x;
  6607. result.y = y;
  6608. result.z = z;
  6609. result.w = vector.w;
  6610. };
  6611. /**
  6612. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6613. * This methods computes transformed normalized direction vectors only.
  6614. * @param x value to transform
  6615. * @param y value to transform
  6616. * @param z value to transform
  6617. * @param w value to transform
  6618. * @param transformation the transformation matrix to apply
  6619. * @param result the vector to store the results in
  6620. */
  6621. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6622. var m = transformation.m;
  6623. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6624. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6625. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6626. result.w = w;
  6627. };
  6628. return Vector4;
  6629. }());
  6630. BABYLON.Vector4 = Vector4;
  6631. /**
  6632. * Size containing widht and height
  6633. */
  6634. var Size = /** @class */ (function () {
  6635. /**
  6636. * Creates a Size object from the given width and height (floats).
  6637. * @param width width of the new size
  6638. * @param height height of the new size
  6639. */
  6640. function Size(width, height) {
  6641. this.width = width;
  6642. this.height = height;
  6643. }
  6644. /**
  6645. * Returns a string with the Size width and height
  6646. * @returns a string with the Size width and height
  6647. */
  6648. Size.prototype.toString = function () {
  6649. return "{W: " + this.width + ", H: " + this.height + "}";
  6650. };
  6651. /**
  6652. * "Size"
  6653. * @returns the string "Size"
  6654. */
  6655. Size.prototype.getClassName = function () {
  6656. return "Size";
  6657. };
  6658. /**
  6659. * Returns the Size hash code.
  6660. * @returns a hash code for a unique width and height
  6661. */
  6662. Size.prototype.getHashCode = function () {
  6663. var hash = this.width || 0;
  6664. hash = (hash * 397) ^ (this.height || 0);
  6665. return hash;
  6666. };
  6667. /**
  6668. * Updates the current size from the given one.
  6669. * @param src the given size
  6670. */
  6671. Size.prototype.copyFrom = function (src) {
  6672. this.width = src.width;
  6673. this.height = src.height;
  6674. };
  6675. /**
  6676. * Updates in place the current Size from the given floats.
  6677. * @param width width of the new size
  6678. * @param height height of the new size
  6679. * @returns the updated Size.
  6680. */
  6681. Size.prototype.copyFromFloats = function (width, height) {
  6682. this.width = width;
  6683. this.height = height;
  6684. return this;
  6685. };
  6686. /**
  6687. * Updates in place the current Size from the given floats.
  6688. * @param width width to set
  6689. * @param height height to set
  6690. * @returns the updated Size.
  6691. */
  6692. Size.prototype.set = function (width, height) {
  6693. return this.copyFromFloats(width, height);
  6694. };
  6695. /**
  6696. * Multiplies the width and height by numbers
  6697. * @param w factor to multiple the width by
  6698. * @param h factor to multiple the height by
  6699. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6700. */
  6701. Size.prototype.multiplyByFloats = function (w, h) {
  6702. return new Size(this.width * w, this.height * h);
  6703. };
  6704. /**
  6705. * Clones the size
  6706. * @returns a new Size copied from the given one.
  6707. */
  6708. Size.prototype.clone = function () {
  6709. return new Size(this.width, this.height);
  6710. };
  6711. /**
  6712. * True if the current Size and the given one width and height are strictly equal.
  6713. * @param other the other size to compare against
  6714. * @returns True if the current Size and the given one width and height are strictly equal.
  6715. */
  6716. Size.prototype.equals = function (other) {
  6717. if (!other) {
  6718. return false;
  6719. }
  6720. return (this.width === other.width) && (this.height === other.height);
  6721. };
  6722. Object.defineProperty(Size.prototype, "surface", {
  6723. /**
  6724. * The surface of the Size : width * height (float).
  6725. */
  6726. get: function () {
  6727. return this.width * this.height;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. /**
  6733. * Create a new size of zero
  6734. * @returns a new Size set to (0.0, 0.0)
  6735. */
  6736. Size.Zero = function () {
  6737. return new Size(0.0, 0.0);
  6738. };
  6739. /**
  6740. * Sums the width and height of two sizes
  6741. * @param otherSize size to add to this size
  6742. * @returns a new Size set as the addition result of the current Size and the given one.
  6743. */
  6744. Size.prototype.add = function (otherSize) {
  6745. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6746. return r;
  6747. };
  6748. /**
  6749. * Subtracts the width and height of two
  6750. * @param otherSize size to subtract to this size
  6751. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6752. */
  6753. Size.prototype.subtract = function (otherSize) {
  6754. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6755. return r;
  6756. };
  6757. /**
  6758. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6759. * @param start starting size to lerp between
  6760. * @param end end size to lerp between
  6761. * @param amount amount to lerp between the start and end values
  6762. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6763. */
  6764. Size.Lerp = function (start, end, amount) {
  6765. var w = start.width + ((end.width - start.width) * amount);
  6766. var h = start.height + ((end.height - start.height) * amount);
  6767. return new Size(w, h);
  6768. };
  6769. return Size;
  6770. }());
  6771. BABYLON.Size = Size;
  6772. /**
  6773. * Class used to store quaternion data
  6774. * @see https://en.wikipedia.org/wiki/Quaternion
  6775. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6776. */
  6777. var Quaternion = /** @class */ (function () {
  6778. /**
  6779. * Creates a new Quaternion from the given floats
  6780. * @param x defines the first component (0 by default)
  6781. * @param y defines the second component (0 by default)
  6782. * @param z defines the third component (0 by default)
  6783. * @param w defines the fourth component (1.0 by default)
  6784. */
  6785. function Quaternion(
  6786. /** defines the first component (0 by default) */
  6787. x,
  6788. /** defines the second component (0 by default) */
  6789. y,
  6790. /** defines the third component (0 by default) */
  6791. z,
  6792. /** defines the fourth component (1.0 by default) */
  6793. w) {
  6794. if (x === void 0) { x = 0.0; }
  6795. if (y === void 0) { y = 0.0; }
  6796. if (z === void 0) { z = 0.0; }
  6797. if (w === void 0) { w = 1.0; }
  6798. this.x = x;
  6799. this.y = y;
  6800. this.z = z;
  6801. this.w = w;
  6802. }
  6803. /**
  6804. * Gets a string representation for the current quaternion
  6805. * @returns a string with the Quaternion coordinates
  6806. */
  6807. Quaternion.prototype.toString = function () {
  6808. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6809. };
  6810. /**
  6811. * Gets the class name of the quaternion
  6812. * @returns the string "Quaternion"
  6813. */
  6814. Quaternion.prototype.getClassName = function () {
  6815. return "Quaternion";
  6816. };
  6817. /**
  6818. * Gets a hash code for this quaternion
  6819. * @returns the quaternion hash code
  6820. */
  6821. Quaternion.prototype.getHashCode = function () {
  6822. var hash = this.x || 0;
  6823. hash = (hash * 397) ^ (this.y || 0);
  6824. hash = (hash * 397) ^ (this.z || 0);
  6825. hash = (hash * 397) ^ (this.w || 0);
  6826. return hash;
  6827. };
  6828. /**
  6829. * Copy the quaternion to an array
  6830. * @returns a new array populated with 4 elements from the quaternion coordinates
  6831. */
  6832. Quaternion.prototype.asArray = function () {
  6833. return [this.x, this.y, this.z, this.w];
  6834. };
  6835. /**
  6836. * Check if two quaternions are equals
  6837. * @param otherQuaternion defines the second operand
  6838. * @return true if the current quaternion and the given one coordinates are strictly equals
  6839. */
  6840. Quaternion.prototype.equals = function (otherQuaternion) {
  6841. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  6842. };
  6843. /**
  6844. * Clone the current quaternion
  6845. * @returns a new quaternion copied from the current one
  6846. */
  6847. Quaternion.prototype.clone = function () {
  6848. return new Quaternion(this.x, this.y, this.z, this.w);
  6849. };
  6850. /**
  6851. * Copy a quaternion to the current one
  6852. * @param other defines the other quaternion
  6853. * @returns the updated current quaternion
  6854. */
  6855. Quaternion.prototype.copyFrom = function (other) {
  6856. this.x = other.x;
  6857. this.y = other.y;
  6858. this.z = other.z;
  6859. this.w = other.w;
  6860. return this;
  6861. };
  6862. /**
  6863. * Updates the current quaternion with the given float coordinates
  6864. * @param x defines the x coordinate
  6865. * @param y defines the y coordinate
  6866. * @param z defines the z coordinate
  6867. * @param w defines the w coordinate
  6868. * @returns the updated current quaternion
  6869. */
  6870. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  6871. this.x = x;
  6872. this.y = y;
  6873. this.z = z;
  6874. this.w = w;
  6875. return this;
  6876. };
  6877. /**
  6878. * Updates the current quaternion from the given float coordinates
  6879. * @param x defines the x coordinate
  6880. * @param y defines the y coordinate
  6881. * @param z defines the z coordinate
  6882. * @param w defines the w coordinate
  6883. * @returns the updated current quaternion
  6884. */
  6885. Quaternion.prototype.set = function (x, y, z, w) {
  6886. return this.copyFromFloats(x, y, z, w);
  6887. };
  6888. /**
  6889. * Adds two quaternions
  6890. * @param other defines the second operand
  6891. * @returns a new quaternion as the addition result of the given one and the current quaternion
  6892. */
  6893. Quaternion.prototype.add = function (other) {
  6894. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  6895. };
  6896. /**
  6897. * Add a quaternion to the current one
  6898. * @param other defines the quaternion to add
  6899. * @returns the current quaternion
  6900. */
  6901. Quaternion.prototype.addInPlace = function (other) {
  6902. this.x += other.x;
  6903. this.y += other.y;
  6904. this.z += other.z;
  6905. this.w += other.w;
  6906. return this;
  6907. };
  6908. /**
  6909. * Subtract two quaternions
  6910. * @param other defines the second operand
  6911. * @returns a new quaternion as the subtraction result of the given one from the current one
  6912. */
  6913. Quaternion.prototype.subtract = function (other) {
  6914. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  6915. };
  6916. /**
  6917. * Multiplies the current quaternion by a scale factor
  6918. * @param value defines the scale factor
  6919. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  6920. */
  6921. Quaternion.prototype.scale = function (value) {
  6922. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  6923. };
  6924. /**
  6925. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  6926. * @param scale defines the scale factor
  6927. * @param result defines the Quaternion object where to store the result
  6928. * @returns the unmodified current quaternion
  6929. */
  6930. Quaternion.prototype.scaleToRef = function (scale, result) {
  6931. result.x = this.x * scale;
  6932. result.y = this.y * scale;
  6933. result.z = this.z * scale;
  6934. result.w = this.w * scale;
  6935. return this;
  6936. };
  6937. /**
  6938. * Multiplies in place the current quaternion by a scale factor
  6939. * @param value defines the scale factor
  6940. * @returns the current modified quaternion
  6941. */
  6942. Quaternion.prototype.scaleInPlace = function (value) {
  6943. this.x *= value;
  6944. this.y *= value;
  6945. this.z *= value;
  6946. this.w *= value;
  6947. return this;
  6948. };
  6949. /**
  6950. * Scale the current quaternion values by a factor and add the result to a given quaternion
  6951. * @param scale defines the scale factor
  6952. * @param result defines the Quaternion object where to store the result
  6953. * @returns the unmodified current quaternion
  6954. */
  6955. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  6956. result.x += this.x * scale;
  6957. result.y += this.y * scale;
  6958. result.z += this.z * scale;
  6959. result.w += this.w * scale;
  6960. return this;
  6961. };
  6962. /**
  6963. * Multiplies two quaternions
  6964. * @param q1 defines the second operand
  6965. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  6966. */
  6967. Quaternion.prototype.multiply = function (q1) {
  6968. var result = new Quaternion(0, 0, 0, 1.0);
  6969. this.multiplyToRef(q1, result);
  6970. return result;
  6971. };
  6972. /**
  6973. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  6974. * @param q1 defines the second operand
  6975. * @param result defines the target quaternion
  6976. * @returns the current quaternion
  6977. */
  6978. Quaternion.prototype.multiplyToRef = function (q1, result) {
  6979. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  6980. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  6981. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  6982. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  6983. result.copyFromFloats(x, y, z, w);
  6984. return this;
  6985. };
  6986. /**
  6987. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  6988. * @param q1 defines the second operand
  6989. * @returns the currentupdated quaternion
  6990. */
  6991. Quaternion.prototype.multiplyInPlace = function (q1) {
  6992. this.multiplyToRef(q1, this);
  6993. return this;
  6994. };
  6995. /**
  6996. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  6997. * @param ref defines the target quaternion
  6998. * @returns the current quaternion
  6999. */
  7000. Quaternion.prototype.conjugateToRef = function (ref) {
  7001. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  7002. return this;
  7003. };
  7004. /**
  7005. * Conjugates in place (1-q) the current quaternion
  7006. * @returns the current updated quaternion
  7007. */
  7008. Quaternion.prototype.conjugateInPlace = function () {
  7009. this.x *= -1;
  7010. this.y *= -1;
  7011. this.z *= -1;
  7012. return this;
  7013. };
  7014. /**
  7015. * Conjugates in place (1-q) the current quaternion
  7016. * @returns a new quaternion
  7017. */
  7018. Quaternion.prototype.conjugate = function () {
  7019. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  7020. return result;
  7021. };
  7022. /**
  7023. * Gets length of current quaternion
  7024. * @returns the quaternion length (float)
  7025. */
  7026. Quaternion.prototype.length = function () {
  7027. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  7028. };
  7029. /**
  7030. * Normalize in place the current quaternion
  7031. * @returns the current updated quaternion
  7032. */
  7033. Quaternion.prototype.normalize = function () {
  7034. var length = 1.0 / this.length();
  7035. this.x *= length;
  7036. this.y *= length;
  7037. this.z *= length;
  7038. this.w *= length;
  7039. return this;
  7040. };
  7041. /**
  7042. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7043. * @param order is a reserved parameter and is ignore for now
  7044. * @returns a new Vector3 containing the Euler angles
  7045. */
  7046. Quaternion.prototype.toEulerAngles = function (order) {
  7047. if (order === void 0) { order = "YZX"; }
  7048. var result = Vector3.Zero();
  7049. this.toEulerAnglesToRef(result, order);
  7050. return result;
  7051. };
  7052. /**
  7053. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7054. * @param result defines the vector which will be filled with the Euler angles
  7055. * @param order is a reserved parameter and is ignore for now
  7056. * @returns the current unchanged quaternion
  7057. */
  7058. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7059. if (order === void 0) { order = "YZX"; }
  7060. var qz = this.z;
  7061. var qx = this.x;
  7062. var qy = this.y;
  7063. var qw = this.w;
  7064. var sqw = qw * qw;
  7065. var sqz = qz * qz;
  7066. var sqx = qx * qx;
  7067. var sqy = qy * qy;
  7068. var zAxisY = qy * qz - qx * qw;
  7069. var limit = .4999999;
  7070. if (zAxisY < -limit) {
  7071. result.y = 2 * Math.atan2(qy, qw);
  7072. result.x = Math.PI / 2;
  7073. result.z = 0;
  7074. }
  7075. else if (zAxisY > limit) {
  7076. result.y = 2 * Math.atan2(qy, qw);
  7077. result.x = -Math.PI / 2;
  7078. result.z = 0;
  7079. }
  7080. else {
  7081. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7082. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7083. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7084. }
  7085. return this;
  7086. };
  7087. /**
  7088. * Updates the given rotation matrix with the current quaternion values
  7089. * @param result defines the target matrix
  7090. * @returns the current unchanged quaternion
  7091. */
  7092. Quaternion.prototype.toRotationMatrix = function (result) {
  7093. Matrix.FromQuaternionToRef(this, result);
  7094. return this;
  7095. };
  7096. /**
  7097. * Updates the current quaternion from the given rotation matrix values
  7098. * @param matrix defines the source matrix
  7099. * @returns the current updated quaternion
  7100. */
  7101. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7102. Quaternion.FromRotationMatrixToRef(matrix, this);
  7103. return this;
  7104. };
  7105. // Statics
  7106. /**
  7107. * Creates a new quaternion from a rotation matrix
  7108. * @param matrix defines the source matrix
  7109. * @returns a new quaternion created from the given rotation matrix values
  7110. */
  7111. Quaternion.FromRotationMatrix = function (matrix) {
  7112. var result = new Quaternion();
  7113. Quaternion.FromRotationMatrixToRef(matrix, result);
  7114. return result;
  7115. };
  7116. /**
  7117. * Updates the given quaternion with the given rotation matrix values
  7118. * @param matrix defines the source matrix
  7119. * @param result defines the target quaternion
  7120. */
  7121. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7122. var data = matrix.m;
  7123. var m11 = data[0], m12 = data[4], m13 = data[8];
  7124. var m21 = data[1], m22 = data[5], m23 = data[9];
  7125. var m31 = data[2], m32 = data[6], m33 = data[10];
  7126. var trace = m11 + m22 + m33;
  7127. var s;
  7128. if (trace > 0) {
  7129. s = 0.5 / Math.sqrt(trace + 1.0);
  7130. result.w = 0.25 / s;
  7131. result.x = (m32 - m23) * s;
  7132. result.y = (m13 - m31) * s;
  7133. result.z = (m21 - m12) * s;
  7134. }
  7135. else if (m11 > m22 && m11 > m33) {
  7136. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7137. result.w = (m32 - m23) / s;
  7138. result.x = 0.25 * s;
  7139. result.y = (m12 + m21) / s;
  7140. result.z = (m13 + m31) / s;
  7141. }
  7142. else if (m22 > m33) {
  7143. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7144. result.w = (m13 - m31) / s;
  7145. result.x = (m12 + m21) / s;
  7146. result.y = 0.25 * s;
  7147. result.z = (m23 + m32) / s;
  7148. }
  7149. else {
  7150. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7151. result.w = (m21 - m12) / s;
  7152. result.x = (m13 + m31) / s;
  7153. result.y = (m23 + m32) / s;
  7154. result.z = 0.25 * s;
  7155. }
  7156. };
  7157. /**
  7158. * Returns the dot product (float) between the quaternions "left" and "right"
  7159. * @param left defines the left operand
  7160. * @param right defines the right operand
  7161. * @returns the dot product
  7162. */
  7163. Quaternion.Dot = function (left, right) {
  7164. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7165. };
  7166. /**
  7167. * Checks if the two quaternions are close to each other
  7168. * @param quat0 defines the first quaternion to check
  7169. * @param quat1 defines the second quaternion to check
  7170. * @returns true if the two quaternions are close to each other
  7171. */
  7172. Quaternion.AreClose = function (quat0, quat1) {
  7173. var dot = Quaternion.Dot(quat0, quat1);
  7174. return dot >= 0;
  7175. };
  7176. /**
  7177. * Creates an empty quaternion
  7178. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7179. */
  7180. Quaternion.Zero = function () {
  7181. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7182. };
  7183. /**
  7184. * Inverse a given quaternion
  7185. * @param q defines the source quaternion
  7186. * @returns a new quaternion as the inverted current quaternion
  7187. */
  7188. Quaternion.Inverse = function (q) {
  7189. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7190. };
  7191. /**
  7192. * Creates an identity quaternion
  7193. * @returns the identity quaternion
  7194. */
  7195. Quaternion.Identity = function () {
  7196. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7197. };
  7198. /**
  7199. * Gets a boolean indicating if the given quaternion is identity
  7200. * @param quaternion defines the quaternion to check
  7201. * @returns true if the quaternion is identity
  7202. */
  7203. Quaternion.IsIdentity = function (quaternion) {
  7204. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7205. };
  7206. /**
  7207. * Creates a quaternion from a rotation around an axis
  7208. * @param axis defines the axis to use
  7209. * @param angle defines the angle to use
  7210. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7211. */
  7212. Quaternion.RotationAxis = function (axis, angle) {
  7213. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7214. };
  7215. /**
  7216. * Creates a rotation around an axis and stores it into the given quaternion
  7217. * @param axis defines the axis to use
  7218. * @param angle defines the angle to use
  7219. * @param result defines the target quaternion
  7220. * @returns the target quaternion
  7221. */
  7222. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7223. var sin = Math.sin(angle / 2);
  7224. axis.normalize();
  7225. result.w = Math.cos(angle / 2);
  7226. result.x = axis.x * sin;
  7227. result.y = axis.y * sin;
  7228. result.z = axis.z * sin;
  7229. return result;
  7230. };
  7231. /**
  7232. * Creates a new quaternion from data stored into an array
  7233. * @param array defines the data source
  7234. * @param offset defines the offset in the source array where the data starts
  7235. * @returns a new quaternion
  7236. */
  7237. Quaternion.FromArray = function (array, offset) {
  7238. if (!offset) {
  7239. offset = 0;
  7240. }
  7241. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7242. };
  7243. /**
  7244. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7245. * @param yaw defines the rotation around Y axis
  7246. * @param pitch defines the rotation around X axis
  7247. * @param roll defines the rotation around Z axis
  7248. * @returns the new quaternion
  7249. */
  7250. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7251. var q = new Quaternion();
  7252. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7253. return q;
  7254. };
  7255. /**
  7256. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7257. * @param yaw defines the rotation around Y axis
  7258. * @param pitch defines the rotation around X axis
  7259. * @param roll defines the rotation around Z axis
  7260. * @param result defines the target quaternion
  7261. */
  7262. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7263. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7264. var halfRoll = roll * 0.5;
  7265. var halfPitch = pitch * 0.5;
  7266. var halfYaw = yaw * 0.5;
  7267. var sinRoll = Math.sin(halfRoll);
  7268. var cosRoll = Math.cos(halfRoll);
  7269. var sinPitch = Math.sin(halfPitch);
  7270. var cosPitch = Math.cos(halfPitch);
  7271. var sinYaw = Math.sin(halfYaw);
  7272. var cosYaw = Math.cos(halfYaw);
  7273. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7274. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7275. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7276. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7277. };
  7278. /**
  7279. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7280. * @param alpha defines the rotation around first axis
  7281. * @param beta defines the rotation around second axis
  7282. * @param gamma defines the rotation around third axis
  7283. * @returns the new quaternion
  7284. */
  7285. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7286. var result = new Quaternion();
  7287. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7288. return result;
  7289. };
  7290. /**
  7291. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7292. * @param alpha defines the rotation around first axis
  7293. * @param beta defines the rotation around second axis
  7294. * @param gamma defines the rotation around third axis
  7295. * @param result defines the target quaternion
  7296. */
  7297. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7298. // Produces a quaternion from Euler angles in the z-x-z orientation
  7299. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7300. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7301. var halfBeta = beta * 0.5;
  7302. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7303. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7304. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7305. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7306. };
  7307. /**
  7308. * 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)
  7309. * @param axis1 defines the first axis
  7310. * @param axis2 defines the second axis
  7311. * @param axis3 defines the third axis
  7312. * @returns the new quaternion
  7313. */
  7314. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7315. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7316. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7317. return quat;
  7318. };
  7319. /**
  7320. * 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
  7321. * @param axis1 defines the first axis
  7322. * @param axis2 defines the second axis
  7323. * @param axis3 defines the third axis
  7324. * @param ref defines the target quaternion
  7325. */
  7326. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7327. var rotMat = MathTmp.Matrix[0];
  7328. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7329. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7330. };
  7331. /**
  7332. * Interpolates between two quaternions
  7333. * @param left defines first quaternion
  7334. * @param right defines second quaternion
  7335. * @param amount defines the gradient to use
  7336. * @returns the new interpolated quaternion
  7337. */
  7338. Quaternion.Slerp = function (left, right, amount) {
  7339. var result = Quaternion.Identity();
  7340. Quaternion.SlerpToRef(left, right, amount, result);
  7341. return result;
  7342. };
  7343. /**
  7344. * Interpolates between two quaternions and stores it into a target quaternion
  7345. * @param left defines first quaternion
  7346. * @param right defines second quaternion
  7347. * @param amount defines the gradient to use
  7348. * @param result defines the target quaternion
  7349. */
  7350. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7351. var num2;
  7352. var num3;
  7353. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7354. var flag = false;
  7355. if (num4 < 0) {
  7356. flag = true;
  7357. num4 = -num4;
  7358. }
  7359. if (num4 > 0.999999) {
  7360. num3 = 1 - amount;
  7361. num2 = flag ? -amount : amount;
  7362. }
  7363. else {
  7364. var num5 = Math.acos(num4);
  7365. var num6 = (1.0 / Math.sin(num5));
  7366. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7367. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7368. }
  7369. result.x = (num3 * left.x) + (num2 * right.x);
  7370. result.y = (num3 * left.y) + (num2 * right.y);
  7371. result.z = (num3 * left.z) + (num2 * right.z);
  7372. result.w = (num3 * left.w) + (num2 * right.w);
  7373. };
  7374. /**
  7375. * Interpolate between two quaternions using Hermite interpolation
  7376. * @param value1 defines first quaternion
  7377. * @param tangent1 defines the incoming tangent
  7378. * @param value2 defines second quaternion
  7379. * @param tangent2 defines the outgoing tangent
  7380. * @param amount defines the target quaternion
  7381. * @returns the new interpolated quaternion
  7382. */
  7383. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7384. var squared = amount * amount;
  7385. var cubed = amount * squared;
  7386. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7387. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7388. var part3 = (cubed - (2.0 * squared)) + amount;
  7389. var part4 = cubed - squared;
  7390. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7391. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7392. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7393. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7394. return new Quaternion(x, y, z, w);
  7395. };
  7396. return Quaternion;
  7397. }());
  7398. BABYLON.Quaternion = Quaternion;
  7399. /**
  7400. * Class used to store matrix data (4x4)
  7401. */
  7402. var Matrix = /** @class */ (function () {
  7403. /**
  7404. * Creates an empty matrix (filled with zeros)
  7405. */
  7406. function Matrix() {
  7407. this._isIdentity = false;
  7408. this._isIdentityDirty = true;
  7409. this._isIdentity3x2 = true;
  7410. this._isIdentity3x2Dirty = true;
  7411. this._m = new Float32Array(16);
  7412. this._updateIdentityStatus(false);
  7413. }
  7414. Object.defineProperty(Matrix.prototype, "m", {
  7415. /**
  7416. * Gets the internal data of the matrix
  7417. */
  7418. get: function () { return this._m; },
  7419. enumerable: true,
  7420. configurable: true
  7421. });
  7422. /** @hidden */
  7423. Matrix.prototype._markAsUpdated = function () {
  7424. this.updateFlag = Matrix._updateFlagSeed++;
  7425. this._isIdentity = false;
  7426. this._isIdentity3x2 = false;
  7427. this._isIdentityDirty = true;
  7428. this._isIdentity3x2Dirty = true;
  7429. };
  7430. /** @hidden */
  7431. Matrix.prototype._updateIdentityStatus = function (isIdentity, isIdentityDirty, isIdentity3x2, isIdentity3x2Dirty) {
  7432. if (isIdentityDirty === void 0) { isIdentityDirty = false; }
  7433. if (isIdentity3x2 === void 0) { isIdentity3x2 = false; }
  7434. if (isIdentity3x2Dirty === void 0) { isIdentity3x2Dirty = true; }
  7435. this.updateFlag = Matrix._updateFlagSeed++;
  7436. this._isIdentity = isIdentity;
  7437. this._isIdentity3x2 = isIdentity || isIdentity3x2;
  7438. this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
  7439. this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
  7440. };
  7441. // Properties
  7442. /**
  7443. * Check if the current matrix is identity
  7444. * @returns true is the matrix is the identity matrix
  7445. */
  7446. Matrix.prototype.isIdentity = function () {
  7447. if (this._isIdentityDirty) {
  7448. this._isIdentityDirty = false;
  7449. var m = this._m;
  7450. this._isIdentity = (m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
  7451. m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
  7452. m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
  7453. m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0);
  7454. }
  7455. return this._isIdentity;
  7456. };
  7457. /**
  7458. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  7459. * @returns true is the matrix is the identity matrix
  7460. */
  7461. Matrix.prototype.isIdentityAs3x2 = function () {
  7462. if (this._isIdentity3x2Dirty) {
  7463. this._isIdentity3x2Dirty = false;
  7464. if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
  7465. this._isIdentity3x2 = false;
  7466. }
  7467. else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
  7468. this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
  7469. this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
  7470. this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
  7471. this._isIdentity3x2 = false;
  7472. }
  7473. else {
  7474. this._isIdentity3x2 = true;
  7475. }
  7476. }
  7477. return this._isIdentity3x2;
  7478. };
  7479. /**
  7480. * Gets the determinant of the matrix
  7481. * @returns the matrix determinant
  7482. */
  7483. Matrix.prototype.determinant = function () {
  7484. if (this._isIdentity === true) {
  7485. return 1;
  7486. }
  7487. var m = this._m;
  7488. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7489. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7490. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7491. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7492. // https://en.wikipedia.org/wiki/Laplace_expansion
  7493. // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
  7494. // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
  7495. // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
  7496. // where
  7497. // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
  7498. // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
  7499. //
  7500. // Here we do that for the 1st row.
  7501. var det_22_33 = m22 * m33 - m32 * m23;
  7502. var det_21_33 = m21 * m33 - m31 * m23;
  7503. var det_21_32 = m21 * m32 - m31 * m22;
  7504. var det_20_33 = m20 * m33 - m30 * m23;
  7505. var det_20_32 = m20 * m32 - m22 * m30;
  7506. var det_20_31 = m20 * m31 - m30 * m21;
  7507. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7508. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7509. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7510. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7511. return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7512. };
  7513. // Methods
  7514. /**
  7515. * Returns the matrix as a Float32Array
  7516. * @returns the matrix underlying array
  7517. */
  7518. Matrix.prototype.toArray = function () {
  7519. return this._m;
  7520. };
  7521. /**
  7522. * Returns the matrix as a Float32Array
  7523. * @returns the matrix underlying array.
  7524. */
  7525. Matrix.prototype.asArray = function () {
  7526. return this._m;
  7527. };
  7528. /**
  7529. * Inverts the current matrix in place
  7530. * @returns the current inverted matrix
  7531. */
  7532. Matrix.prototype.invert = function () {
  7533. this.invertToRef(this);
  7534. return this;
  7535. };
  7536. /**
  7537. * Sets all the matrix elements to zero
  7538. * @returns the current matrix
  7539. */
  7540. Matrix.prototype.reset = function () {
  7541. Matrix.FromValuesToRef(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, this);
  7542. this._updateIdentityStatus(false);
  7543. return this;
  7544. };
  7545. /**
  7546. * Adds the current matrix with a second one
  7547. * @param other defines the matrix to add
  7548. * @returns a new matrix as the addition of the current matrix and the given one
  7549. */
  7550. Matrix.prototype.add = function (other) {
  7551. var result = new Matrix();
  7552. this.addToRef(other, result);
  7553. return result;
  7554. };
  7555. /**
  7556. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7557. * @param other defines the matrix to add
  7558. * @param result defines the target matrix
  7559. * @returns the current matrix
  7560. */
  7561. Matrix.prototype.addToRef = function (other, result) {
  7562. for (var index = 0; index < 16; index++) {
  7563. result._m[index] = this._m[index] + other._m[index];
  7564. }
  7565. result._markAsUpdated();
  7566. return this;
  7567. };
  7568. /**
  7569. * Adds in place the given matrix to the current matrix
  7570. * @param other defines the second operand
  7571. * @returns the current updated matrix
  7572. */
  7573. Matrix.prototype.addToSelf = function (other) {
  7574. for (var index = 0; index < 16; index++) {
  7575. this._m[index] += other._m[index];
  7576. }
  7577. this._markAsUpdated();
  7578. return this;
  7579. };
  7580. /**
  7581. * Sets the given matrix to the current inverted Matrix
  7582. * @param other defines the target matrix
  7583. * @returns the unmodified current matrix
  7584. */
  7585. Matrix.prototype.invertToRef = function (other) {
  7586. if (this._isIdentity === true) {
  7587. Matrix.IdentityToRef(other);
  7588. return this;
  7589. }
  7590. // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
  7591. var m = this._m;
  7592. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7593. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7594. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7595. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7596. var det_22_33 = m22 * m33 - m32 * m23;
  7597. var det_21_33 = m21 * m33 - m31 * m23;
  7598. var det_21_32 = m21 * m32 - m31 * m22;
  7599. var det_20_33 = m20 * m33 - m30 * m23;
  7600. var det_20_32 = m20 * m32 - m22 * m30;
  7601. var det_20_31 = m20 * m31 - m30 * m21;
  7602. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7603. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7604. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7605. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7606. var det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7607. if (det === 0) {
  7608. // not invertible
  7609. other.copyFrom(this);
  7610. return this;
  7611. }
  7612. var detInv = 1 / det;
  7613. var det_12_33 = m12 * m33 - m32 * m13;
  7614. var det_11_33 = m11 * m33 - m31 * m13;
  7615. var det_11_32 = m11 * m32 - m31 * m12;
  7616. var det_10_33 = m10 * m33 - m30 * m13;
  7617. var det_10_32 = m10 * m32 - m30 * m12;
  7618. var det_10_31 = m10 * m31 - m30 * m11;
  7619. var det_12_23 = m12 * m23 - m22 * m13;
  7620. var det_11_23 = m11 * m23 - m21 * m13;
  7621. var det_11_22 = m11 * m22 - m21 * m12;
  7622. var det_10_23 = m10 * m23 - m20 * m13;
  7623. var det_10_22 = m10 * m22 - m20 * m12;
  7624. var det_10_21 = m10 * m21 - m20 * m11;
  7625. var cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
  7626. var cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
  7627. var cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
  7628. var cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
  7629. var cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
  7630. var cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
  7631. var cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
  7632. var cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
  7633. var cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
  7634. var cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
  7635. var cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
  7636. var cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
  7637. Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other);
  7638. return this;
  7639. };
  7640. /**
  7641. * add a value at the specified position in the current Matrix
  7642. * @param index the index of the value within the matrix. between 0 and 15.
  7643. * @param value the value to be added
  7644. * @returns the current updated matrix
  7645. */
  7646. Matrix.prototype.addAtIndex = function (index, value) {
  7647. this._m[index] += value;
  7648. this._markAsUpdated();
  7649. return this;
  7650. };
  7651. /**
  7652. * mutiply the specified position in the current Matrix by a value
  7653. * @param index the index of the value within the matrix. between 0 and 15.
  7654. * @param value the value to be added
  7655. * @returns the current updated matrix
  7656. */
  7657. Matrix.prototype.multiplyAtIndex = function (index, value) {
  7658. this._m[index] *= value;
  7659. this._markAsUpdated();
  7660. return this;
  7661. };
  7662. /**
  7663. * Inserts the translation vector (using 3 floats) in the current matrix
  7664. * @param x defines the 1st component of the translation
  7665. * @param y defines the 2nd component of the translation
  7666. * @param z defines the 3rd component of the translation
  7667. * @returns the current updated matrix
  7668. */
  7669. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7670. this._m[12] = x;
  7671. this._m[13] = y;
  7672. this._m[14] = z;
  7673. this._markAsUpdated();
  7674. return this;
  7675. };
  7676. /**
  7677. * Inserts the translation vector in the current matrix
  7678. * @param vector3 defines the translation to insert
  7679. * @returns the current updated matrix
  7680. */
  7681. Matrix.prototype.setTranslation = function (vector3) {
  7682. return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
  7683. };
  7684. /**
  7685. * Gets the translation value of the current matrix
  7686. * @returns a new Vector3 as the extracted translation from the matrix
  7687. */
  7688. Matrix.prototype.getTranslation = function () {
  7689. return new Vector3(this._m[12], this._m[13], this._m[14]);
  7690. };
  7691. /**
  7692. * Fill a Vector3 with the extracted translation from the matrix
  7693. * @param result defines the Vector3 where to store the translation
  7694. * @returns the current matrix
  7695. */
  7696. Matrix.prototype.getTranslationToRef = function (result) {
  7697. result.x = this._m[12];
  7698. result.y = this._m[13];
  7699. result.z = this._m[14];
  7700. return this;
  7701. };
  7702. /**
  7703. * Remove rotation and scaling part from the matrix
  7704. * @returns the updated matrix
  7705. */
  7706. Matrix.prototype.removeRotationAndScaling = function () {
  7707. var m = this.m;
  7708. 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, m[12], m[13], m[14], m[15], this);
  7709. this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
  7710. return this;
  7711. };
  7712. /**
  7713. * Multiply two matrices
  7714. * @param other defines the second operand
  7715. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7716. */
  7717. Matrix.prototype.multiply = function (other) {
  7718. var result = new Matrix();
  7719. this.multiplyToRef(other, result);
  7720. return result;
  7721. };
  7722. /**
  7723. * Copy the current matrix from the given one
  7724. * @param other defines the source matrix
  7725. * @returns the current updated matrix
  7726. */
  7727. Matrix.prototype.copyFrom = function (other) {
  7728. other.copyToArray(this._m);
  7729. var o = other;
  7730. this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
  7731. return this;
  7732. };
  7733. /**
  7734. * Populates the given array from the starting index with the current matrix values
  7735. * @param array defines the target array
  7736. * @param offset defines the offset in the target array where to start storing values
  7737. * @returns the current matrix
  7738. */
  7739. Matrix.prototype.copyToArray = function (array, offset) {
  7740. if (offset === void 0) { offset = 0; }
  7741. for (var index = 0; index < 16; index++) {
  7742. array[offset + index] = this._m[index];
  7743. }
  7744. return this;
  7745. };
  7746. /**
  7747. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7748. * @param other defines the second operand
  7749. * @param result defines the matrix where to store the multiplication
  7750. * @returns the current matrix
  7751. */
  7752. Matrix.prototype.multiplyToRef = function (other, result) {
  7753. if (this._isIdentity) {
  7754. result.copyFrom(other);
  7755. return this;
  7756. }
  7757. if (other._isIdentity) {
  7758. result.copyFrom(this);
  7759. return this;
  7760. }
  7761. this.multiplyToArray(other, result._m, 0);
  7762. result._markAsUpdated();
  7763. return this;
  7764. };
  7765. /**
  7766. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  7767. * @param other defines the second operand
  7768. * @param result defines the array where to store the multiplication
  7769. * @param offset defines the offset in the target array where to start storing values
  7770. * @returns the current matrix
  7771. */
  7772. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  7773. var m = this._m;
  7774. var otherM = other.m;
  7775. var tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
  7776. var tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
  7777. var tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
  7778. var tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
  7779. var om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
  7780. var om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
  7781. var om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
  7782. var om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
  7783. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  7784. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  7785. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  7786. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  7787. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  7788. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  7789. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  7790. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  7791. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  7792. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  7793. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  7794. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  7795. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  7796. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  7797. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  7798. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  7799. return this;
  7800. };
  7801. /**
  7802. * Check equality between this matrix and a second one
  7803. * @param value defines the second matrix to compare
  7804. * @returns true is the current matrix and the given one values are strictly equal
  7805. */
  7806. Matrix.prototype.equals = function (value) {
  7807. var other = value;
  7808. if (!other) {
  7809. return false;
  7810. }
  7811. if (this._isIdentity || other._isIdentity) {
  7812. if (!this._isIdentityDirty && !other._isIdentityDirty) {
  7813. return this._isIdentity && other._isIdentity;
  7814. }
  7815. }
  7816. var m = this.m;
  7817. var om = other.m;
  7818. return (m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
  7819. m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
  7820. m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
  7821. m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]);
  7822. };
  7823. /**
  7824. * Clone the current matrix
  7825. * @returns a new matrix from the current matrix
  7826. */
  7827. Matrix.prototype.clone = function () {
  7828. var matrix = new Matrix();
  7829. matrix.copyFrom(this);
  7830. return matrix;
  7831. };
  7832. /**
  7833. * Returns the name of the current matrix class
  7834. * @returns the string "Matrix"
  7835. */
  7836. Matrix.prototype.getClassName = function () {
  7837. return "Matrix";
  7838. };
  7839. /**
  7840. * Gets the hash code of the current matrix
  7841. * @returns the hash code
  7842. */
  7843. Matrix.prototype.getHashCode = function () {
  7844. var hash = this._m[0] || 0;
  7845. for (var i = 1; i < 16; i++) {
  7846. hash = (hash * 397) ^ (this._m[i] || 0);
  7847. }
  7848. return hash;
  7849. };
  7850. /**
  7851. * Decomposes the current Matrix into a translation, rotation and scaling components
  7852. * @param scale defines the scale vector3 given as a reference to update
  7853. * @param rotation defines the rotation quaternion given as a reference to update
  7854. * @param translation defines the translation vector3 given as a reference to update
  7855. * @returns true if operation was successful
  7856. */
  7857. Matrix.prototype.decompose = function (scale, rotation, translation) {
  7858. if (this._isIdentity) {
  7859. if (translation) {
  7860. translation.setAll(0);
  7861. }
  7862. if (scale) {
  7863. scale.setAll(1);
  7864. }
  7865. if (rotation) {
  7866. rotation.copyFromFloats(0, 0, 0, 1);
  7867. }
  7868. return true;
  7869. }
  7870. var m = this._m;
  7871. if (translation) {
  7872. translation.copyFromFloats(m[12], m[13], m[14]);
  7873. }
  7874. scale = scale || MathTmp.Vector3[0];
  7875. scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  7876. scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  7877. scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  7878. if (this.determinant() <= 0) {
  7879. scale.y *= -1;
  7880. }
  7881. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  7882. if (rotation) {
  7883. rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
  7884. }
  7885. return false;
  7886. }
  7887. if (rotation) {
  7888. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  7889. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]);
  7890. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  7891. }
  7892. return true;
  7893. };
  7894. /**
  7895. * Gets specific row of the matrix
  7896. * @param index defines the number of the row to get
  7897. * @returns the index-th row of the current matrix as a new Vector4
  7898. */
  7899. Matrix.prototype.getRow = function (index) {
  7900. if (index < 0 || index > 3) {
  7901. return null;
  7902. }
  7903. var i = index * 4;
  7904. return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
  7905. };
  7906. /**
  7907. * Sets the index-th row of the current matrix to the vector4 values
  7908. * @param index defines the number of the row to set
  7909. * @param row defines the target vector4
  7910. * @returns the updated current matrix
  7911. */
  7912. Matrix.prototype.setRow = function (index, row) {
  7913. return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
  7914. };
  7915. /**
  7916. * Compute the transpose of the matrix
  7917. * @returns the new transposed matrix
  7918. */
  7919. Matrix.prototype.transpose = function () {
  7920. return Matrix.Transpose(this);
  7921. };
  7922. /**
  7923. * Compute the transpose of the matrix and store it in a given matrix
  7924. * @param result defines the target matrix
  7925. * @returns the current matrix
  7926. */
  7927. Matrix.prototype.transposeToRef = function (result) {
  7928. Matrix.TransposeToRef(this, result);
  7929. return this;
  7930. };
  7931. /**
  7932. * Sets the index-th row of the current matrix with the given 4 x float values
  7933. * @param index defines the row index
  7934. * @param x defines the x component to set
  7935. * @param y defines the y component to set
  7936. * @param z defines the z component to set
  7937. * @param w defines the w component to set
  7938. * @returns the updated current matrix
  7939. */
  7940. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  7941. if (index < 0 || index > 3) {
  7942. return this;
  7943. }
  7944. var i = index * 4;
  7945. this._m[i + 0] = x;
  7946. this._m[i + 1] = y;
  7947. this._m[i + 2] = z;
  7948. this._m[i + 3] = w;
  7949. this._markAsUpdated();
  7950. return this;
  7951. };
  7952. /**
  7953. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  7954. * @param scale defines the scale factor
  7955. * @returns a new matrix
  7956. */
  7957. Matrix.prototype.scale = function (scale) {
  7958. var result = new Matrix();
  7959. this.scaleToRef(scale, result);
  7960. return result;
  7961. };
  7962. /**
  7963. * Scale the current matrix values by a factor to a given result matrix
  7964. * @param scale defines the scale factor
  7965. * @param result defines the matrix to store the result
  7966. * @returns the current matrix
  7967. */
  7968. Matrix.prototype.scaleToRef = function (scale, result) {
  7969. for (var index = 0; index < 16; index++) {
  7970. result._m[index] = this._m[index] * scale;
  7971. }
  7972. result._markAsUpdated();
  7973. return this;
  7974. };
  7975. /**
  7976. * Scale the current matrix values by a factor and add the result to a given matrix
  7977. * @param scale defines the scale factor
  7978. * @param result defines the Matrix to store the result
  7979. * @returns the current matrix
  7980. */
  7981. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  7982. for (var index = 0; index < 16; index++) {
  7983. result._m[index] += this._m[index] * scale;
  7984. }
  7985. result._markAsUpdated();
  7986. return this;
  7987. };
  7988. /**
  7989. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  7990. * @param ref matrix to store the result
  7991. */
  7992. Matrix.prototype.toNormalMatrix = function (ref) {
  7993. var tmp = MathTmp.Matrix[0];
  7994. this.invertToRef(tmp);
  7995. tmp.transposeToRef(ref);
  7996. var m = ref._m;
  7997. Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref);
  7998. };
  7999. /**
  8000. * Gets only rotation part of the current matrix
  8001. * @returns a new matrix sets to the extracted rotation matrix from the current one
  8002. */
  8003. Matrix.prototype.getRotationMatrix = function () {
  8004. var result = new Matrix();
  8005. this.getRotationMatrixToRef(result);
  8006. return result;
  8007. };
  8008. /**
  8009. * Extracts the rotation matrix from the current one and sets it as the given "result"
  8010. * @param result defines the target matrix to store data to
  8011. * @returns the current matrix
  8012. */
  8013. Matrix.prototype.getRotationMatrixToRef = function (result) {
  8014. var scale = MathTmp.Vector3[0];
  8015. if (!this.decompose(scale)) {
  8016. Matrix.IdentityToRef(result);
  8017. return this;
  8018. }
  8019. var m = this._m;
  8020. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  8021. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8022. return this;
  8023. };
  8024. /**
  8025. * Toggles model matrix from being right handed to left handed in place and vice versa
  8026. */
  8027. Matrix.prototype.toggleModelMatrixHandInPlace = function () {
  8028. var m = this._m;
  8029. m[2] *= -1;
  8030. m[6] *= -1;
  8031. m[8] *= -1;
  8032. m[9] *= -1;
  8033. m[14] *= -1;
  8034. this._markAsUpdated();
  8035. };
  8036. /**
  8037. * Toggles projection matrix from being right handed to left handed in place and vice versa
  8038. */
  8039. Matrix.prototype.toggleProjectionMatrixHandInPlace = function () {
  8040. var m = this._m;
  8041. m[8] *= -1;
  8042. m[9] *= -1;
  8043. m[10] *= -1;
  8044. m[11] *= -1;
  8045. this._markAsUpdated();
  8046. };
  8047. // Statics
  8048. /**
  8049. * Creates a matrix from an array
  8050. * @param array defines the source array
  8051. * @param offset defines an offset in the source array
  8052. * @returns a new Matrix set from the starting index of the given array
  8053. */
  8054. Matrix.FromArray = function (array, offset) {
  8055. if (offset === void 0) { offset = 0; }
  8056. var result = new Matrix();
  8057. Matrix.FromArrayToRef(array, offset, result);
  8058. return result;
  8059. };
  8060. /**
  8061. * Copy the content of an array into a given matrix
  8062. * @param array defines the source array
  8063. * @param offset defines an offset in the source array
  8064. * @param result defines the target matrix
  8065. */
  8066. Matrix.FromArrayToRef = function (array, offset, result) {
  8067. for (var index = 0; index < 16; index++) {
  8068. result._m[index] = array[index + offset];
  8069. }
  8070. result._markAsUpdated();
  8071. };
  8072. /**
  8073. * Stores an array into a matrix after having multiplied each component by a given factor
  8074. * @param array defines the source array
  8075. * @param offset defines the offset in the source array
  8076. * @param scale defines the scaling factor
  8077. * @param result defines the target matrix
  8078. */
  8079. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  8080. for (var index = 0; index < 16; index++) {
  8081. result._m[index] = array[index + offset] * scale;
  8082. }
  8083. result._markAsUpdated();
  8084. };
  8085. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8086. /**
  8087. * Gets an identity matrix that must not be updated
  8088. */
  8089. get: function () {
  8090. return Matrix._identityReadOnly;
  8091. },
  8092. enumerable: true,
  8093. configurable: true
  8094. });
  8095. /**
  8096. * Stores a list of values (16) inside a given matrix
  8097. * @param initialM11 defines 1st value of 1st row
  8098. * @param initialM12 defines 2nd value of 1st row
  8099. * @param initialM13 defines 3rd value of 1st row
  8100. * @param initialM14 defines 4th value of 1st row
  8101. * @param initialM21 defines 1st value of 2nd row
  8102. * @param initialM22 defines 2nd value of 2nd row
  8103. * @param initialM23 defines 3rd value of 2nd row
  8104. * @param initialM24 defines 4th value of 2nd row
  8105. * @param initialM31 defines 1st value of 3rd row
  8106. * @param initialM32 defines 2nd value of 3rd row
  8107. * @param initialM33 defines 3rd value of 3rd row
  8108. * @param initialM34 defines 4th value of 3rd row
  8109. * @param initialM41 defines 1st value of 4th row
  8110. * @param initialM42 defines 2nd value of 4th row
  8111. * @param initialM43 defines 3rd value of 4th row
  8112. * @param initialM44 defines 4th value of 4th row
  8113. * @param result defines the target matrix
  8114. */
  8115. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8116. var m = result._m;
  8117. m[0] = initialM11;
  8118. m[1] = initialM12;
  8119. m[2] = initialM13;
  8120. m[3] = initialM14;
  8121. m[4] = initialM21;
  8122. m[5] = initialM22;
  8123. m[6] = initialM23;
  8124. m[7] = initialM24;
  8125. m[8] = initialM31;
  8126. m[9] = initialM32;
  8127. m[10] = initialM33;
  8128. m[11] = initialM34;
  8129. m[12] = initialM41;
  8130. m[13] = initialM42;
  8131. m[14] = initialM43;
  8132. m[15] = initialM44;
  8133. result._markAsUpdated();
  8134. };
  8135. /**
  8136. * Creates new matrix from a list of values (16)
  8137. * @param initialM11 defines 1st value of 1st row
  8138. * @param initialM12 defines 2nd value of 1st row
  8139. * @param initialM13 defines 3rd value of 1st row
  8140. * @param initialM14 defines 4th value of 1st row
  8141. * @param initialM21 defines 1st value of 2nd row
  8142. * @param initialM22 defines 2nd value of 2nd row
  8143. * @param initialM23 defines 3rd value of 2nd row
  8144. * @param initialM24 defines 4th value of 2nd row
  8145. * @param initialM31 defines 1st value of 3rd row
  8146. * @param initialM32 defines 2nd value of 3rd row
  8147. * @param initialM33 defines 3rd value of 3rd row
  8148. * @param initialM34 defines 4th value of 3rd row
  8149. * @param initialM41 defines 1st value of 4th row
  8150. * @param initialM42 defines 2nd value of 4th row
  8151. * @param initialM43 defines 3rd value of 4th row
  8152. * @param initialM44 defines 4th value of 4th row
  8153. * @returns the new matrix
  8154. */
  8155. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8156. var result = new Matrix();
  8157. var m = result._m;
  8158. m[0] = initialM11;
  8159. m[1] = initialM12;
  8160. m[2] = initialM13;
  8161. m[3] = initialM14;
  8162. m[4] = initialM21;
  8163. m[5] = initialM22;
  8164. m[6] = initialM23;
  8165. m[7] = initialM24;
  8166. m[8] = initialM31;
  8167. m[9] = initialM32;
  8168. m[10] = initialM33;
  8169. m[11] = initialM34;
  8170. m[12] = initialM41;
  8171. m[13] = initialM42;
  8172. m[14] = initialM43;
  8173. m[15] = initialM44;
  8174. result._markAsUpdated();
  8175. return result;
  8176. };
  8177. /**
  8178. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8179. * @param scale defines the scale vector3
  8180. * @param rotation defines the rotation quaternion
  8181. * @param translation defines the translation vector3
  8182. * @returns a new matrix
  8183. */
  8184. Matrix.Compose = function (scale, rotation, translation) {
  8185. var result = new Matrix();
  8186. Matrix.ComposeToRef(scale, rotation, translation, result);
  8187. return result;
  8188. };
  8189. /**
  8190. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8191. * @param scale defines the scale vector3
  8192. * @param rotation defines the rotation quaternion
  8193. * @param translation defines the translation vector3
  8194. * @param result defines the target matrix
  8195. */
  8196. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8197. Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
  8198. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8199. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8200. result.setTranslation(translation);
  8201. };
  8202. /**
  8203. * Creates a new identity matrix
  8204. * @returns a new identity matrix
  8205. */
  8206. Matrix.Identity = function () {
  8207. var identity = 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);
  8208. identity._updateIdentityStatus(true);
  8209. return identity;
  8210. };
  8211. /**
  8212. * Creates a new identity matrix and stores the result in a given matrix
  8213. * @param result defines the target matrix
  8214. */
  8215. Matrix.IdentityToRef = function (result) {
  8216. 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);
  8217. result._updateIdentityStatus(true);
  8218. };
  8219. /**
  8220. * Creates a new zero matrix
  8221. * @returns a new zero matrix
  8222. */
  8223. Matrix.Zero = function () {
  8224. var zero = 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);
  8225. zero._updateIdentityStatus(false);
  8226. return zero;
  8227. };
  8228. /**
  8229. * Creates a new rotation matrix for "angle" radians around the X axis
  8230. * @param angle defines the angle (in radians) to use
  8231. * @return the new matrix
  8232. */
  8233. Matrix.RotationX = function (angle) {
  8234. var result = new Matrix();
  8235. Matrix.RotationXToRef(angle, result);
  8236. return result;
  8237. };
  8238. /**
  8239. * Creates a new matrix as the invert of a given matrix
  8240. * @param source defines the source matrix
  8241. * @returns the new matrix
  8242. */
  8243. Matrix.Invert = function (source) {
  8244. var result = new Matrix();
  8245. source.invertToRef(result);
  8246. return result;
  8247. };
  8248. /**
  8249. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8250. * @param angle defines the angle (in radians) to use
  8251. * @param result defines the target matrix
  8252. */
  8253. Matrix.RotationXToRef = function (angle, result) {
  8254. var s = Math.sin(angle);
  8255. var c = Math.cos(angle);
  8256. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8257. result._updateIdentityStatus(c === 1 && s === 0);
  8258. };
  8259. /**
  8260. * Creates a new rotation matrix for "angle" radians around the Y axis
  8261. * @param angle defines the angle (in radians) to use
  8262. * @return the new matrix
  8263. */
  8264. Matrix.RotationY = function (angle) {
  8265. var result = new Matrix();
  8266. Matrix.RotationYToRef(angle, result);
  8267. return result;
  8268. };
  8269. /**
  8270. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8271. * @param angle defines the angle (in radians) to use
  8272. * @param result defines the target matrix
  8273. */
  8274. Matrix.RotationYToRef = function (angle, result) {
  8275. var s = Math.sin(angle);
  8276. var c = Math.cos(angle);
  8277. Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8278. result._updateIdentityStatus(c === 1 && s === 0);
  8279. };
  8280. /**
  8281. * Creates a new rotation matrix for "angle" radians around the Z axis
  8282. * @param angle defines the angle (in radians) to use
  8283. * @return the new matrix
  8284. */
  8285. Matrix.RotationZ = function (angle) {
  8286. var result = new Matrix();
  8287. Matrix.RotationZToRef(angle, result);
  8288. return result;
  8289. };
  8290. /**
  8291. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8292. * @param angle defines the angle (in radians) to use
  8293. * @param result defines the target matrix
  8294. */
  8295. Matrix.RotationZToRef = function (angle, result) {
  8296. var s = Math.sin(angle);
  8297. var c = Math.cos(angle);
  8298. Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8299. result._updateIdentityStatus(c === 1 && s === 0);
  8300. };
  8301. /**
  8302. * Creates a new rotation matrix for "angle" radians around the given axis
  8303. * @param axis defines the axis to use
  8304. * @param angle defines the angle (in radians) to use
  8305. * @return the new matrix
  8306. */
  8307. Matrix.RotationAxis = function (axis, angle) {
  8308. var result = new Matrix();
  8309. Matrix.RotationAxisToRef(axis, angle, result);
  8310. return result;
  8311. };
  8312. /**
  8313. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8314. * @param axis defines the axis to use
  8315. * @param angle defines the angle (in radians) to use
  8316. * @param result defines the target matrix
  8317. */
  8318. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8319. var s = Math.sin(-angle);
  8320. var c = Math.cos(-angle);
  8321. var c1 = 1 - c;
  8322. axis.normalize();
  8323. var m = result._m;
  8324. m[0] = (axis.x * axis.x) * c1 + c;
  8325. m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8326. m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8327. m[3] = 0.0;
  8328. m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8329. m[5] = (axis.y * axis.y) * c1 + c;
  8330. m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8331. m[7] = 0.0;
  8332. m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8333. m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8334. m[10] = (axis.z * axis.z) * c1 + c;
  8335. m[11] = 0.0;
  8336. m[12] = 0.0;
  8337. m[13] = 0.0;
  8338. m[14] = 0.0;
  8339. m[15] = 1.0;
  8340. result._markAsUpdated();
  8341. };
  8342. /**
  8343. * Creates a rotation matrix
  8344. * @param yaw defines the yaw angle in radians (Y axis)
  8345. * @param pitch defines the pitch angle in radians (X axis)
  8346. * @param roll defines the roll angle in radians (X axis)
  8347. * @returns the new rotation matrix
  8348. */
  8349. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8350. var result = new Matrix();
  8351. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8352. return result;
  8353. };
  8354. /**
  8355. * Creates a rotation matrix and stores it in a given matrix
  8356. * @param yaw defines the yaw angle in radians (Y axis)
  8357. * @param pitch defines the pitch angle in radians (X axis)
  8358. * @param roll defines the roll angle in radians (X axis)
  8359. * @param result defines the target matrix
  8360. */
  8361. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8362. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
  8363. MathTmp.Quaternion[0].toRotationMatrix(result);
  8364. };
  8365. /**
  8366. * Creates a scaling matrix
  8367. * @param x defines the scale factor on X axis
  8368. * @param y defines the scale factor on Y axis
  8369. * @param z defines the scale factor on Z axis
  8370. * @returns the new matrix
  8371. */
  8372. Matrix.Scaling = function (x, y, z) {
  8373. var result = new Matrix();
  8374. Matrix.ScalingToRef(x, y, z, result);
  8375. return result;
  8376. };
  8377. /**
  8378. * Creates a scaling matrix and stores it in a given matrix
  8379. * @param x defines the scale factor on X axis
  8380. * @param y defines the scale factor on Y axis
  8381. * @param z defines the scale factor on Z axis
  8382. * @param result defines the target matrix
  8383. */
  8384. Matrix.ScalingToRef = function (x, y, z, result) {
  8385. Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8386. result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
  8387. };
  8388. /**
  8389. * Creates a translation matrix
  8390. * @param x defines the translation on X axis
  8391. * @param y defines the translation on Y axis
  8392. * @param z defines the translationon Z axis
  8393. * @returns the new matrix
  8394. */
  8395. Matrix.Translation = function (x, y, z) {
  8396. var result = new Matrix();
  8397. Matrix.TranslationToRef(x, y, z, result);
  8398. return result;
  8399. };
  8400. /**
  8401. * Creates a translation matrix and stores it in a given matrix
  8402. * @param x defines the translation on X axis
  8403. * @param y defines the translation on Y axis
  8404. * @param z defines the translationon Z axis
  8405. * @param result defines the target matrix
  8406. */
  8407. Matrix.TranslationToRef = function (x, y, z, result) {
  8408. 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);
  8409. result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
  8410. };
  8411. /**
  8412. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8413. * @param startValue defines the start value
  8414. * @param endValue defines the end value
  8415. * @param gradient defines the gradient factor
  8416. * @returns the new matrix
  8417. */
  8418. Matrix.Lerp = function (startValue, endValue, gradient) {
  8419. var result = new Matrix();
  8420. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8421. return result;
  8422. };
  8423. /**
  8424. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8425. * @param startValue defines the start value
  8426. * @param endValue defines the end value
  8427. * @param gradient defines the gradient factor
  8428. * @param result defines the Matrix object where to store data
  8429. */
  8430. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8431. for (var index = 0; index < 16; index++) {
  8432. result._m[index] = startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;
  8433. }
  8434. result._markAsUpdated();
  8435. };
  8436. /**
  8437. * Builds a new matrix whose values are computed by:
  8438. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8439. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8440. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8441. * @param startValue defines the first matrix
  8442. * @param endValue defines the second matrix
  8443. * @param gradient defines the gradient between the two matrices
  8444. * @returns the new matrix
  8445. */
  8446. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8447. var result = new Matrix();
  8448. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8449. return result;
  8450. };
  8451. /**
  8452. * Update a matrix to values which are computed by:
  8453. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8454. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8455. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8456. * @param startValue defines the first matrix
  8457. * @param endValue defines the second matrix
  8458. * @param gradient defines the gradient between the two matrices
  8459. * @param result defines the target matrix
  8460. */
  8461. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8462. var startScale = MathTmp.Vector3[0];
  8463. var startRotation = MathTmp.Quaternion[0];
  8464. var startTranslation = MathTmp.Vector3[1];
  8465. startValue.decompose(startScale, startRotation, startTranslation);
  8466. var endScale = MathTmp.Vector3[2];
  8467. var endRotation = MathTmp.Quaternion[1];
  8468. var endTranslation = MathTmp.Vector3[3];
  8469. endValue.decompose(endScale, endRotation, endTranslation);
  8470. var resultScale = MathTmp.Vector3[4];
  8471. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8472. var resultRotation = MathTmp.Quaternion[2];
  8473. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8474. var resultTranslation = MathTmp.Vector3[5];
  8475. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8476. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8477. };
  8478. /**
  8479. * 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"
  8480. * This function works in left handed mode
  8481. * @param eye defines the final position of the entity
  8482. * @param target defines where the entity should look at
  8483. * @param up defines the up vector for the entity
  8484. * @returns the new matrix
  8485. */
  8486. Matrix.LookAtLH = function (eye, target, up) {
  8487. var result = new Matrix();
  8488. Matrix.LookAtLHToRef(eye, target, up, result);
  8489. return result;
  8490. };
  8491. /**
  8492. * 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".
  8493. * This function works in left handed mode
  8494. * @param eye defines the final position of the entity
  8495. * @param target defines where the entity should look at
  8496. * @param up defines the up vector for the entity
  8497. * @param result defines the target matrix
  8498. */
  8499. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8500. var xAxis = MathTmp.Vector3[0];
  8501. var yAxis = MathTmp.Vector3[1];
  8502. var zAxis = MathTmp.Vector3[2];
  8503. // Z axis
  8504. target.subtractToRef(eye, zAxis);
  8505. zAxis.normalize();
  8506. // X axis
  8507. Vector3.CrossToRef(up, zAxis, xAxis);
  8508. var xSquareLength = xAxis.lengthSquared();
  8509. if (xSquareLength === 0) {
  8510. xAxis.x = 1.0;
  8511. }
  8512. else {
  8513. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8514. }
  8515. // Y axis
  8516. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8517. yAxis.normalize();
  8518. // Eye angles
  8519. var ex = -Vector3.Dot(xAxis, eye);
  8520. var ey = -Vector3.Dot(yAxis, eye);
  8521. var ez = -Vector3.Dot(zAxis, eye);
  8522. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8523. };
  8524. /**
  8525. * 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"
  8526. * This function works in right handed mode
  8527. * @param eye defines the final position of the entity
  8528. * @param target defines where the entity should look at
  8529. * @param up defines the up vector for the entity
  8530. * @returns the new matrix
  8531. */
  8532. Matrix.LookAtRH = function (eye, target, up) {
  8533. var result = new Matrix();
  8534. Matrix.LookAtRHToRef(eye, target, up, result);
  8535. return result;
  8536. };
  8537. /**
  8538. * 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".
  8539. * This function works in right handed mode
  8540. * @param eye defines the final position of the entity
  8541. * @param target defines where the entity should look at
  8542. * @param up defines the up vector for the entity
  8543. * @param result defines the target matrix
  8544. */
  8545. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8546. var xAxis = MathTmp.Vector3[0];
  8547. var yAxis = MathTmp.Vector3[1];
  8548. var zAxis = MathTmp.Vector3[2];
  8549. // Z axis
  8550. eye.subtractToRef(target, zAxis);
  8551. zAxis.normalize();
  8552. // X axis
  8553. Vector3.CrossToRef(up, zAxis, xAxis);
  8554. var xSquareLength = xAxis.lengthSquared();
  8555. if (xSquareLength === 0) {
  8556. xAxis.x = 1.0;
  8557. }
  8558. else {
  8559. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8560. }
  8561. // Y axis
  8562. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8563. yAxis.normalize();
  8564. // Eye angles
  8565. var ex = -Vector3.Dot(xAxis, eye);
  8566. var ey = -Vector3.Dot(yAxis, eye);
  8567. var ez = -Vector3.Dot(zAxis, eye);
  8568. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8569. };
  8570. /**
  8571. * Create a left-handed orthographic projection matrix
  8572. * @param width defines the viewport width
  8573. * @param height defines the viewport height
  8574. * @param znear defines the near clip plane
  8575. * @param zfar defines the far clip plane
  8576. * @returns a new matrix as a left-handed orthographic projection matrix
  8577. */
  8578. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8579. var matrix = new Matrix();
  8580. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8581. return matrix;
  8582. };
  8583. /**
  8584. * Store a left-handed orthographic projection to a given matrix
  8585. * @param width defines the viewport width
  8586. * @param height defines the viewport height
  8587. * @param znear defines the near clip plane
  8588. * @param zfar defines the far clip plane
  8589. * @param result defines the target matrix
  8590. */
  8591. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8592. var n = znear;
  8593. var f = zfar;
  8594. var a = 2.0 / width;
  8595. var b = 2.0 / height;
  8596. var c = 2.0 / (f - n);
  8597. var d = -(f + n) / (f - n);
  8598. 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);
  8599. result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
  8600. };
  8601. /**
  8602. * Create a left-handed orthographic projection matrix
  8603. * @param left defines the viewport left coordinate
  8604. * @param right defines the viewport right coordinate
  8605. * @param bottom defines the viewport bottom coordinate
  8606. * @param top defines the viewport top coordinate
  8607. * @param znear defines the near clip plane
  8608. * @param zfar defines the far clip plane
  8609. * @returns a new matrix as a left-handed orthographic projection matrix
  8610. */
  8611. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8612. var matrix = new Matrix();
  8613. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8614. return matrix;
  8615. };
  8616. /**
  8617. * Stores a left-handed orthographic projection into a given matrix
  8618. * @param left defines the viewport left coordinate
  8619. * @param right defines the viewport right coordinate
  8620. * @param bottom defines the viewport bottom coordinate
  8621. * @param top defines the viewport top coordinate
  8622. * @param znear defines the near clip plane
  8623. * @param zfar defines the far clip plane
  8624. * @param result defines the target matrix
  8625. */
  8626. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8627. var n = znear;
  8628. var f = zfar;
  8629. var a = 2.0 / (right - left);
  8630. var b = 2.0 / (top - bottom);
  8631. var c = 2.0 / (f - n);
  8632. var d = -(f + n) / (f - n);
  8633. var i0 = (left + right) / (left - right);
  8634. var i1 = (top + bottom) / (bottom - top);
  8635. 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);
  8636. result._markAsUpdated();
  8637. };
  8638. /**
  8639. * Creates a right-handed orthographic projection matrix
  8640. * @param left defines the viewport left coordinate
  8641. * @param right defines the viewport right coordinate
  8642. * @param bottom defines the viewport bottom coordinate
  8643. * @param top defines the viewport top coordinate
  8644. * @param znear defines the near clip plane
  8645. * @param zfar defines the far clip plane
  8646. * @returns a new matrix as a right-handed orthographic projection matrix
  8647. */
  8648. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8649. var matrix = new Matrix();
  8650. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8651. return matrix;
  8652. };
  8653. /**
  8654. * Stores a right-handed orthographic projection into a given matrix
  8655. * @param left defines the viewport left coordinate
  8656. * @param right defines the viewport right coordinate
  8657. * @param bottom defines the viewport bottom coordinate
  8658. * @param top defines the viewport top coordinate
  8659. * @param znear defines the near clip plane
  8660. * @param zfar defines the far clip plane
  8661. * @param result defines the target matrix
  8662. */
  8663. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8664. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8665. result._m[10] *= -1; // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
  8666. };
  8667. /**
  8668. * Creates a left-handed perspective projection matrix
  8669. * @param width defines the viewport width
  8670. * @param height defines the viewport height
  8671. * @param znear defines the near clip plane
  8672. * @param zfar defines the far clip plane
  8673. * @returns a new matrix as a left-handed perspective projection matrix
  8674. */
  8675. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8676. var matrix = new Matrix();
  8677. var n = znear;
  8678. var f = zfar;
  8679. var a = 2.0 * n / width;
  8680. var b = 2.0 * n / height;
  8681. var c = (f + n) / (f - n);
  8682. var d = -2.0 * f * n / (f - n);
  8683. 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);
  8684. matrix._updateIdentityStatus(false);
  8685. return matrix;
  8686. };
  8687. /**
  8688. * Creates a left-handed perspective projection matrix
  8689. * @param fov defines the horizontal field of view
  8690. * @param aspect defines the aspect ratio
  8691. * @param znear defines the near clip plane
  8692. * @param zfar defines the far clip plane
  8693. * @returns a new matrix as a left-handed perspective projection matrix
  8694. */
  8695. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8696. var matrix = new Matrix();
  8697. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8698. return matrix;
  8699. };
  8700. /**
  8701. * Stores a left-handed perspective projection into a given matrix
  8702. * @param fov defines the horizontal field of view
  8703. * @param aspect defines the aspect ratio
  8704. * @param znear defines the near clip plane
  8705. * @param zfar defines the far clip plane
  8706. * @param result defines the target matrix
  8707. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8708. */
  8709. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8710. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8711. var n = znear;
  8712. var f = zfar;
  8713. var t = 1.0 / (Math.tan(fov * 0.5));
  8714. var a = isVerticalFovFixed ? (t / aspect) : t;
  8715. var b = isVerticalFovFixed ? t : (t * aspect);
  8716. var c = (f + n) / (f - n);
  8717. var d = -2.0 * f * n / (f - n);
  8718. 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);
  8719. result._updateIdentityStatus(false);
  8720. };
  8721. /**
  8722. * Creates a right-handed perspective projection matrix
  8723. * @param fov defines the horizontal field of view
  8724. * @param aspect defines the aspect ratio
  8725. * @param znear defines the near clip plane
  8726. * @param zfar defines the far clip plane
  8727. * @returns a new matrix as a right-handed perspective projection matrix
  8728. */
  8729. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8730. var matrix = new Matrix();
  8731. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8732. return matrix;
  8733. };
  8734. /**
  8735. * Stores a right-handed perspective projection into a given matrix
  8736. * @param fov defines the horizontal field of view
  8737. * @param aspect defines the aspect ratio
  8738. * @param znear defines the near clip plane
  8739. * @param zfar defines the far clip plane
  8740. * @param result defines the target matrix
  8741. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8742. */
  8743. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8744. //alternatively this could be expressed as:
  8745. // m = PerspectiveFovLHToRef
  8746. // m[10] *= -1.0;
  8747. // m[11] *= -1.0;
  8748. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8749. var n = znear;
  8750. var f = zfar;
  8751. var t = 1.0 / (Math.tan(fov * 0.5));
  8752. var a = isVerticalFovFixed ? (t / aspect) : t;
  8753. var b = isVerticalFovFixed ? t : (t * aspect);
  8754. var c = -(f + n) / (f - n);
  8755. var d = -2 * f * n / (f - n);
  8756. 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);
  8757. result._updateIdentityStatus(false);
  8758. };
  8759. /**
  8760. * Stores a perspective projection for WebVR info a given matrix
  8761. * @param fov defines the field of view
  8762. * @param znear defines the near clip plane
  8763. * @param zfar defines the far clip plane
  8764. * @param result defines the target matrix
  8765. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  8766. */
  8767. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  8768. if (rightHanded === void 0) { rightHanded = false; }
  8769. var rightHandedFactor = rightHanded ? -1 : 1;
  8770. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  8771. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  8772. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  8773. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  8774. var xScale = 2.0 / (leftTan + rightTan);
  8775. var yScale = 2.0 / (upTan + downTan);
  8776. var m = result._m;
  8777. m[0] = xScale;
  8778. m[1] = m[2] = m[3] = m[4] = 0.0;
  8779. m[5] = yScale;
  8780. m[6] = m[7] = 0.0;
  8781. m[8] = ((leftTan - rightTan) * xScale * 0.5);
  8782. m[9] = -((upTan - downTan) * yScale * 0.5);
  8783. m[10] = -zfar / (znear - zfar);
  8784. m[11] = 1.0 * rightHandedFactor;
  8785. m[12] = m[13] = m[15] = 0.0;
  8786. m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  8787. result._markAsUpdated();
  8788. };
  8789. /**
  8790. * Computes a complete transformation matrix
  8791. * @param viewport defines the viewport to use
  8792. * @param world defines the world matrix
  8793. * @param view defines the view matrix
  8794. * @param projection defines the projection matrix
  8795. * @param zmin defines the near clip plane
  8796. * @param zmax defines the far clip plane
  8797. * @returns the transformation matrix
  8798. */
  8799. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  8800. var cw = viewport.width;
  8801. var ch = viewport.height;
  8802. var cx = viewport.x;
  8803. var cy = viewport.y;
  8804. 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.0);
  8805. var matrix = MathTmp.Matrix[0];
  8806. world.multiplyToRef(view, matrix);
  8807. matrix.multiplyToRef(projection, matrix);
  8808. return matrix.multiply(viewportMatrix);
  8809. };
  8810. /**
  8811. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  8812. * @param matrix defines the matrix to use
  8813. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  8814. */
  8815. Matrix.GetAsMatrix2x2 = function (matrix) {
  8816. return new Float32Array([
  8817. matrix._m[0], matrix._m[1],
  8818. matrix._m[4], matrix._m[5]
  8819. ]);
  8820. };
  8821. /**
  8822. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  8823. * @param matrix defines the matrix to use
  8824. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  8825. */
  8826. Matrix.GetAsMatrix3x3 = function (matrix) {
  8827. return new Float32Array([
  8828. matrix._m[0], matrix._m[1], matrix._m[2],
  8829. matrix._m[4], matrix._m[5], matrix._m[6],
  8830. matrix._m[8], matrix._m[9], matrix._m[10]
  8831. ]);
  8832. };
  8833. /**
  8834. * Compute the transpose of a given matrix
  8835. * @param matrix defines the matrix to transpose
  8836. * @returns the new matrix
  8837. */
  8838. Matrix.Transpose = function (matrix) {
  8839. var result = new Matrix();
  8840. Matrix.TransposeToRef(matrix, result);
  8841. return result;
  8842. };
  8843. /**
  8844. * Compute the transpose of a matrix and store it in a target matrix
  8845. * @param matrix defines the matrix to transpose
  8846. * @param result defines the target matrix
  8847. */
  8848. Matrix.TransposeToRef = function (matrix, result) {
  8849. var rm = result._m;
  8850. var mm = matrix._m;
  8851. rm[0] = mm[0];
  8852. rm[1] = mm[4];
  8853. rm[2] = mm[8];
  8854. rm[3] = mm[12];
  8855. rm[4] = mm[1];
  8856. rm[5] = mm[5];
  8857. rm[6] = mm[9];
  8858. rm[7] = mm[13];
  8859. rm[8] = mm[2];
  8860. rm[9] = mm[6];
  8861. rm[10] = mm[10];
  8862. rm[11] = mm[14];
  8863. rm[12] = mm[3];
  8864. rm[13] = mm[7];
  8865. rm[14] = mm[11];
  8866. rm[15] = mm[15];
  8867. // identity-ness does not change when transposing
  8868. result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
  8869. };
  8870. /**
  8871. * Computes a reflection matrix from a plane
  8872. * @param plane defines the reflection plane
  8873. * @returns a new matrix
  8874. */
  8875. Matrix.Reflection = function (plane) {
  8876. var matrix = new Matrix();
  8877. Matrix.ReflectionToRef(plane, matrix);
  8878. return matrix;
  8879. };
  8880. /**
  8881. * Computes a reflection matrix from a plane
  8882. * @param plane defines the reflection plane
  8883. * @param result defines the target matrix
  8884. */
  8885. Matrix.ReflectionToRef = function (plane, result) {
  8886. plane.normalize();
  8887. var x = plane.normal.x;
  8888. var y = plane.normal.y;
  8889. var z = plane.normal.z;
  8890. var temp = -2 * x;
  8891. var temp2 = -2 * y;
  8892. var temp3 = -2 * z;
  8893. Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result);
  8894. };
  8895. /**
  8896. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  8897. * @param xaxis defines the value of the 1st axis
  8898. * @param yaxis defines the value of the 2nd axis
  8899. * @param zaxis defines the value of the 3rd axis
  8900. * @param result defines the target matrix
  8901. */
  8902. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  8903. Matrix.FromValuesToRef(xaxis.x, xaxis.y, xaxis.z, 0.0, yaxis.x, yaxis.y, yaxis.z, 0.0, zaxis.x, zaxis.y, zaxis.z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8904. };
  8905. /**
  8906. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  8907. * @param quat defines the quaternion to use
  8908. * @param result defines the target matrix
  8909. */
  8910. Matrix.FromQuaternionToRef = function (quat, result) {
  8911. var xx = quat.x * quat.x;
  8912. var yy = quat.y * quat.y;
  8913. var zz = quat.z * quat.z;
  8914. var xy = quat.x * quat.y;
  8915. var zw = quat.z * quat.w;
  8916. var zx = quat.z * quat.x;
  8917. var yw = quat.y * quat.w;
  8918. var yz = quat.y * quat.z;
  8919. var xw = quat.x * quat.w;
  8920. result._m[0] = 1.0 - (2.0 * (yy + zz));
  8921. result._m[1] = 2.0 * (xy + zw);
  8922. result._m[2] = 2.0 * (zx - yw);
  8923. result._m[3] = 0.0;
  8924. result._m[4] = 2.0 * (xy - zw);
  8925. result._m[5] = 1.0 - (2.0 * (zz + xx));
  8926. result._m[6] = 2.0 * (yz + xw);
  8927. result._m[7] = 0.0;
  8928. result._m[8] = 2.0 * (zx + yw);
  8929. result._m[9] = 2.0 * (yz - xw);
  8930. result._m[10] = 1.0 - (2.0 * (yy + xx));
  8931. result._m[11] = 0.0;
  8932. result._m[12] = 0.0;
  8933. result._m[13] = 0.0;
  8934. result._m[14] = 0.0;
  8935. result._m[15] = 1.0;
  8936. result._markAsUpdated();
  8937. };
  8938. Matrix._updateFlagSeed = 0;
  8939. Matrix._identityReadOnly = Matrix.Identity();
  8940. return Matrix;
  8941. }());
  8942. BABYLON.Matrix = Matrix;
  8943. /**
  8944. * Represens a plane by the equation ax + by + cz + d = 0
  8945. */
  8946. var Plane = /** @class */ (function () {
  8947. /**
  8948. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  8949. * @param a a component of the plane
  8950. * @param b b component of the plane
  8951. * @param c c component of the plane
  8952. * @param d d component of the plane
  8953. */
  8954. function Plane(a, b, c, d) {
  8955. this.normal = new Vector3(a, b, c);
  8956. this.d = d;
  8957. }
  8958. /**
  8959. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  8960. */
  8961. Plane.prototype.asArray = function () {
  8962. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  8963. };
  8964. // Methods
  8965. /**
  8966. * @returns a new plane copied from the current Plane.
  8967. */
  8968. Plane.prototype.clone = function () {
  8969. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  8970. };
  8971. /**
  8972. * @returns the string "Plane".
  8973. */
  8974. Plane.prototype.getClassName = function () {
  8975. return "Plane";
  8976. };
  8977. /**
  8978. * @returns the Plane hash code.
  8979. */
  8980. Plane.prototype.getHashCode = function () {
  8981. var hash = this.normal.getHashCode();
  8982. hash = (hash * 397) ^ (this.d || 0);
  8983. return hash;
  8984. };
  8985. /**
  8986. * Normalize the current Plane in place.
  8987. * @returns the updated Plane.
  8988. */
  8989. Plane.prototype.normalize = function () {
  8990. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  8991. var magnitude = 0.0;
  8992. if (norm !== 0) {
  8993. magnitude = 1.0 / norm;
  8994. }
  8995. this.normal.x *= magnitude;
  8996. this.normal.y *= magnitude;
  8997. this.normal.z *= magnitude;
  8998. this.d *= magnitude;
  8999. return this;
  9000. };
  9001. /**
  9002. * Applies a transformation the plane and returns the result
  9003. * @param transformation the transformation matrix to be applied to the plane
  9004. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  9005. */
  9006. Plane.prototype.transform = function (transformation) {
  9007. var transposedMatrix = MathTmp.Matrix[0];
  9008. Matrix.TransposeToRef(transformation, transposedMatrix);
  9009. var m = transposedMatrix.m;
  9010. var x = this.normal.x;
  9011. var y = this.normal.y;
  9012. var z = this.normal.z;
  9013. var d = this.d;
  9014. var normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
  9015. var normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
  9016. var normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
  9017. var finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
  9018. return new Plane(normalX, normalY, normalZ, finalD);
  9019. };
  9020. /**
  9021. * Calcualtte the dot product between the point and the plane normal
  9022. * @param point point to calculate the dot product with
  9023. * @returns the dot product (float) of the point coordinates and the plane normal.
  9024. */
  9025. Plane.prototype.dotCoordinate = function (point) {
  9026. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  9027. };
  9028. /**
  9029. * Updates the current Plane from the plane defined by the three given points.
  9030. * @param point1 one of the points used to contruct the plane
  9031. * @param point2 one of the points used to contruct the plane
  9032. * @param point3 one of the points used to contruct the plane
  9033. * @returns the updated Plane.
  9034. */
  9035. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9036. var x1 = point2.x - point1.x;
  9037. var y1 = point2.y - point1.y;
  9038. var z1 = point2.z - point1.z;
  9039. var x2 = point3.x - point1.x;
  9040. var y2 = point3.y - point1.y;
  9041. var z2 = point3.z - point1.z;
  9042. var yz = (y1 * z2) - (z1 * y2);
  9043. var xz = (z1 * x2) - (x1 * z2);
  9044. var xy = (x1 * y2) - (y1 * x2);
  9045. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9046. var invPyth;
  9047. if (pyth !== 0) {
  9048. invPyth = 1.0 / pyth;
  9049. }
  9050. else {
  9051. invPyth = 0.0;
  9052. }
  9053. this.normal.x = yz * invPyth;
  9054. this.normal.y = xz * invPyth;
  9055. this.normal.z = xy * invPyth;
  9056. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9057. return this;
  9058. };
  9059. /**
  9060. * Checks if the plane is facing a given direction
  9061. * @param direction the direction to check if the plane is facing
  9062. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9063. * @returns True is the vector "direction" is the same side than the plane normal.
  9064. */
  9065. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9066. var dot = Vector3.Dot(this.normal, direction);
  9067. return (dot <= epsilon);
  9068. };
  9069. /**
  9070. * Calculates the distance to a point
  9071. * @param point point to calculate distance to
  9072. * @returns the signed distance (float) from the given point to the Plane.
  9073. */
  9074. Plane.prototype.signedDistanceTo = function (point) {
  9075. return Vector3.Dot(point, this.normal) + this.d;
  9076. };
  9077. // Statics
  9078. /**
  9079. * Creates a plane from an array
  9080. * @param array the array to create a plane from
  9081. * @returns a new Plane from the given array.
  9082. */
  9083. Plane.FromArray = function (array) {
  9084. return new Plane(array[0], array[1], array[2], array[3]);
  9085. };
  9086. /**
  9087. * Creates a plane from three points
  9088. * @param point1 point used to create the plane
  9089. * @param point2 point used to create the plane
  9090. * @param point3 point used to create the plane
  9091. * @returns a new Plane defined by the three given points.
  9092. */
  9093. Plane.FromPoints = function (point1, point2, point3) {
  9094. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9095. result.copyFromPoints(point1, point2, point3);
  9096. return result;
  9097. };
  9098. /**
  9099. * Creates a plane from an origin point and a normal
  9100. * @param origin origin of the plane to be constructed
  9101. * @param normal normal of the plane to be constructed
  9102. * @returns a new Plane the normal vector to this plane at the given origin point.
  9103. * Note : the vector "normal" is updated because normalized.
  9104. */
  9105. Plane.FromPositionAndNormal = function (origin, normal) {
  9106. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9107. normal.normalize();
  9108. result.normal = normal;
  9109. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9110. return result;
  9111. };
  9112. /**
  9113. * Calculates the distance from a plane and a point
  9114. * @param origin origin of the plane to be constructed
  9115. * @param normal normal of the plane to be constructed
  9116. * @param point point to calculate distance to
  9117. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9118. */
  9119. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9120. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9121. return Vector3.Dot(point, normal) + d;
  9122. };
  9123. return Plane;
  9124. }());
  9125. BABYLON.Plane = Plane;
  9126. /**
  9127. * Class used to represent a viewport on screen
  9128. */
  9129. var Viewport = /** @class */ (function () {
  9130. /**
  9131. * Creates a Viewport object located at (x, y) and sized (width, height)
  9132. * @param x defines viewport left coordinate
  9133. * @param y defines viewport top coordinate
  9134. * @param width defines the viewport width
  9135. * @param height defines the viewport height
  9136. */
  9137. function Viewport(
  9138. /** viewport left coordinate */
  9139. x,
  9140. /** viewport top coordinate */
  9141. y,
  9142. /**viewport width */
  9143. width,
  9144. /** viewport height */
  9145. height) {
  9146. this.x = x;
  9147. this.y = y;
  9148. this.width = width;
  9149. this.height = height;
  9150. }
  9151. /**
  9152. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9153. * @param renderWidthOrEngine defines either an engine or the rendering width
  9154. * @param renderHeight defines the rendering height
  9155. * @returns a new Viewport
  9156. */
  9157. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9158. if (renderWidthOrEngine.getRenderWidth) {
  9159. var engine = renderWidthOrEngine;
  9160. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9161. }
  9162. var renderWidth = renderWidthOrEngine;
  9163. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9164. };
  9165. /**
  9166. * Returns a new Viewport copied from the current one
  9167. * @returns a new Viewport
  9168. */
  9169. Viewport.prototype.clone = function () {
  9170. return new Viewport(this.x, this.y, this.width, this.height);
  9171. };
  9172. return Viewport;
  9173. }());
  9174. BABYLON.Viewport = Viewport;
  9175. /**
  9176. * Reprasents a camera frustum
  9177. */
  9178. var Frustum = /** @class */ (function () {
  9179. function Frustum() {
  9180. }
  9181. /**
  9182. * Gets the planes representing the frustum
  9183. * @param transform matrix to be applied to the returned planes
  9184. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9185. */
  9186. Frustum.GetPlanes = function (transform) {
  9187. var frustumPlanes = [];
  9188. for (var index = 0; index < 6; index++) {
  9189. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9190. }
  9191. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9192. return frustumPlanes;
  9193. };
  9194. /**
  9195. * Gets the near frustum plane transformed by the transform matrix
  9196. * @param transform transformation matrix to be applied to the resulting frustum plane
  9197. * @param frustumPlane the resuling frustum plane
  9198. */
  9199. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9200. var m = transform.m;
  9201. frustumPlane.normal.x = m[3] + m[2];
  9202. frustumPlane.normal.y = m[7] + m[6];
  9203. frustumPlane.normal.z = m[11] + m[10];
  9204. frustumPlane.d = m[15] + m[14];
  9205. frustumPlane.normalize();
  9206. };
  9207. /**
  9208. * Gets the far frustum plane transformed by the transform matrix
  9209. * @param transform transformation matrix to be applied to the resulting frustum plane
  9210. * @param frustumPlane the resuling frustum plane
  9211. */
  9212. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9213. var m = transform.m;
  9214. frustumPlane.normal.x = m[3] - m[2];
  9215. frustumPlane.normal.y = m[7] - m[6];
  9216. frustumPlane.normal.z = m[11] - m[10];
  9217. frustumPlane.d = m[15] - m[14];
  9218. frustumPlane.normalize();
  9219. };
  9220. /**
  9221. * Gets the left frustum plane transformed by the transform matrix
  9222. * @param transform transformation matrix to be applied to the resulting frustum plane
  9223. * @param frustumPlane the resuling frustum plane
  9224. */
  9225. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9226. var m = transform.m;
  9227. frustumPlane.normal.x = m[3] + m[0];
  9228. frustumPlane.normal.y = m[7] + m[4];
  9229. frustumPlane.normal.z = m[11] + m[8];
  9230. frustumPlane.d = m[15] + m[12];
  9231. frustumPlane.normalize();
  9232. };
  9233. /**
  9234. * Gets the right frustum plane transformed by the transform matrix
  9235. * @param transform transformation matrix to be applied to the resulting frustum plane
  9236. * @param frustumPlane the resuling frustum plane
  9237. */
  9238. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9239. var m = transform.m;
  9240. frustumPlane.normal.x = m[3] - m[0];
  9241. frustumPlane.normal.y = m[7] - m[4];
  9242. frustumPlane.normal.z = m[11] - m[8];
  9243. frustumPlane.d = m[15] - m[12];
  9244. frustumPlane.normalize();
  9245. };
  9246. /**
  9247. * Gets the top frustum plane transformed by the transform matrix
  9248. * @param transform transformation matrix to be applied to the resulting frustum plane
  9249. * @param frustumPlane the resuling frustum plane
  9250. */
  9251. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9252. var m = transform.m;
  9253. frustumPlane.normal.x = m[3] - m[1];
  9254. frustumPlane.normal.y = m[7] - m[5];
  9255. frustumPlane.normal.z = m[11] - m[9];
  9256. frustumPlane.d = m[15] - m[13];
  9257. frustumPlane.normalize();
  9258. };
  9259. /**
  9260. * Gets the bottom frustum plane transformed by the transform matrix
  9261. * @param transform transformation matrix to be applied to the resulting frustum plane
  9262. * @param frustumPlane the resuling frustum plane
  9263. */
  9264. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9265. var m = transform.m;
  9266. frustumPlane.normal.x = m[3] + m[1];
  9267. frustumPlane.normal.y = m[7] + m[5];
  9268. frustumPlane.normal.z = m[11] + m[9];
  9269. frustumPlane.d = m[15] + m[13];
  9270. frustumPlane.normalize();
  9271. };
  9272. /**
  9273. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9274. * @param transform transformation matrix to be applied to the resulting frustum planes
  9275. * @param frustumPlanes the resuling frustum planes
  9276. */
  9277. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9278. // Near
  9279. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9280. // Far
  9281. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9282. // Left
  9283. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9284. // Right
  9285. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9286. // Top
  9287. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9288. // Bottom
  9289. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9290. };
  9291. return Frustum;
  9292. }());
  9293. BABYLON.Frustum = Frustum;
  9294. /** Defines supported spaces */
  9295. var Space;
  9296. (function (Space) {
  9297. /** Local (object) space */
  9298. Space[Space["LOCAL"] = 0] = "LOCAL";
  9299. /** World space */
  9300. Space[Space["WORLD"] = 1] = "WORLD";
  9301. /** Bone space */
  9302. Space[Space["BONE"] = 2] = "BONE";
  9303. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9304. /** Defines the 3 main axes */
  9305. var Axis = /** @class */ (function () {
  9306. function Axis() {
  9307. }
  9308. /** X axis */
  9309. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9310. /** Y axis */
  9311. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9312. /** Z axis */
  9313. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9314. return Axis;
  9315. }());
  9316. BABYLON.Axis = Axis;
  9317. /** Class used to represent a Bezier curve */
  9318. var BezierCurve = /** @class */ (function () {
  9319. function BezierCurve() {
  9320. }
  9321. /**
  9322. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9323. * @param t defines the time
  9324. * @param x1 defines the left coordinate on X axis
  9325. * @param y1 defines the left coordinate on Y axis
  9326. * @param x2 defines the right coordinate on X axis
  9327. * @param y2 defines the right coordinate on Y axis
  9328. * @returns the interpolated value
  9329. */
  9330. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9331. // Extract X (which is equal to time here)
  9332. var f0 = 1 - 3 * x2 + 3 * x1;
  9333. var f1 = 3 * x2 - 6 * x1;
  9334. var f2 = 3 * x1;
  9335. var refinedT = t;
  9336. for (var i = 0; i < 5; i++) {
  9337. var refinedT2 = refinedT * refinedT;
  9338. var refinedT3 = refinedT2 * refinedT;
  9339. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9340. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9341. refinedT -= (x - t) * slope;
  9342. refinedT = Math.min(1, Math.max(0, refinedT));
  9343. }
  9344. // Resolve cubic bezier for the given x
  9345. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9346. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9347. Math.pow(refinedT, 3);
  9348. };
  9349. return BezierCurve;
  9350. }());
  9351. BABYLON.BezierCurve = BezierCurve;
  9352. /**
  9353. * Defines potential orientation for back face culling
  9354. */
  9355. var Orientation;
  9356. (function (Orientation) {
  9357. /**
  9358. * Clockwise
  9359. */
  9360. Orientation[Orientation["CW"] = 0] = "CW";
  9361. /** Counter clockwise */
  9362. Orientation[Orientation["CCW"] = 1] = "CCW";
  9363. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9364. /**
  9365. * Defines angle representation
  9366. */
  9367. var Angle = /** @class */ (function () {
  9368. /**
  9369. * Creates an Angle object of "radians" radians (float).
  9370. */
  9371. function Angle(radians) {
  9372. this._radians = radians;
  9373. if (this._radians < 0.0) {
  9374. this._radians += (2.0 * Math.PI);
  9375. }
  9376. }
  9377. /**
  9378. * Get value in degrees
  9379. * @returns the Angle value in degrees (float)
  9380. */
  9381. Angle.prototype.degrees = function () {
  9382. return this._radians * 180.0 / Math.PI;
  9383. };
  9384. /**
  9385. * Get value in radians
  9386. * @returns the Angle value in radians (float)
  9387. */
  9388. Angle.prototype.radians = function () {
  9389. return this._radians;
  9390. };
  9391. /**
  9392. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9393. * @param a defines first vector
  9394. * @param b defines second vector
  9395. * @returns a new Angle
  9396. */
  9397. Angle.BetweenTwoPoints = function (a, b) {
  9398. var delta = b.subtract(a);
  9399. var theta = Math.atan2(delta.y, delta.x);
  9400. return new Angle(theta);
  9401. };
  9402. /**
  9403. * Gets a new Angle object from the given float in radians
  9404. * @param radians defines the angle value in radians
  9405. * @returns a new Angle
  9406. */
  9407. Angle.FromRadians = function (radians) {
  9408. return new Angle(radians);
  9409. };
  9410. /**
  9411. * Gets a new Angle object from the given float in degrees
  9412. * @param degrees defines the angle value in degrees
  9413. * @returns a new Angle
  9414. */
  9415. Angle.FromDegrees = function (degrees) {
  9416. return new Angle(degrees * Math.PI / 180.0);
  9417. };
  9418. return Angle;
  9419. }());
  9420. BABYLON.Angle = Angle;
  9421. /**
  9422. * This represents an arc in a 2d space.
  9423. */
  9424. var Arc2 = /** @class */ (function () {
  9425. /**
  9426. * Creates an Arc object from the three given points : start, middle and end.
  9427. * @param startPoint Defines the start point of the arc
  9428. * @param midPoint Defines the midlle point of the arc
  9429. * @param endPoint Defines the end point of the arc
  9430. */
  9431. function Arc2(
  9432. /** Defines the start point of the arc */
  9433. startPoint,
  9434. /** Defines the mid point of the arc */
  9435. midPoint,
  9436. /** Defines the end point of the arc */
  9437. endPoint) {
  9438. this.startPoint = startPoint;
  9439. this.midPoint = midPoint;
  9440. this.endPoint = endPoint;
  9441. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9442. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9443. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9444. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9445. 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);
  9446. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9447. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9448. var a1 = this.startAngle.degrees();
  9449. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9450. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9451. // angles correction
  9452. if (a2 - a1 > +180.0) {
  9453. a2 -= 360.0;
  9454. }
  9455. if (a2 - a1 < -180.0) {
  9456. a2 += 360.0;
  9457. }
  9458. if (a3 - a2 > +180.0) {
  9459. a3 -= 360.0;
  9460. }
  9461. if (a3 - a2 < -180.0) {
  9462. a3 += 360.0;
  9463. }
  9464. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9465. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9466. }
  9467. return Arc2;
  9468. }());
  9469. BABYLON.Arc2 = Arc2;
  9470. /**
  9471. * Represents a 2D path made up of multiple 2D points
  9472. */
  9473. var Path2 = /** @class */ (function () {
  9474. /**
  9475. * Creates a Path2 object from the starting 2D coordinates x and y.
  9476. * @param x the starting points x value
  9477. * @param y the starting points y value
  9478. */
  9479. function Path2(x, y) {
  9480. this._points = new Array();
  9481. this._length = 0.0;
  9482. /**
  9483. * If the path start and end point are the same
  9484. */
  9485. this.closed = false;
  9486. this._points.push(new Vector2(x, y));
  9487. }
  9488. /**
  9489. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9490. * @param x the added points x value
  9491. * @param y the added points y value
  9492. * @returns the updated Path2.
  9493. */
  9494. Path2.prototype.addLineTo = function (x, y) {
  9495. if (this.closed) {
  9496. return this;
  9497. }
  9498. var newPoint = new Vector2(x, y);
  9499. var previousPoint = this._points[this._points.length - 1];
  9500. this._points.push(newPoint);
  9501. this._length += newPoint.subtract(previousPoint).length();
  9502. return this;
  9503. };
  9504. /**
  9505. * 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.
  9506. * @param midX middle point x value
  9507. * @param midY middle point y value
  9508. * @param endX end point x value
  9509. * @param endY end point y value
  9510. * @param numberOfSegments (default: 36)
  9511. * @returns the updated Path2.
  9512. */
  9513. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9514. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9515. if (this.closed) {
  9516. return this;
  9517. }
  9518. var startPoint = this._points[this._points.length - 1];
  9519. var midPoint = new Vector2(midX, midY);
  9520. var endPoint = new Vector2(endX, endY);
  9521. var arc = new Arc2(startPoint, midPoint, endPoint);
  9522. var increment = arc.angle.radians() / numberOfSegments;
  9523. if (arc.orientation === Orientation.CW) {
  9524. increment *= -1;
  9525. }
  9526. var currentAngle = arc.startAngle.radians() + increment;
  9527. for (var i = 0; i < numberOfSegments; i++) {
  9528. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9529. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9530. this.addLineTo(x, y);
  9531. currentAngle += increment;
  9532. }
  9533. return this;
  9534. };
  9535. /**
  9536. * Closes the Path2.
  9537. * @returns the Path2.
  9538. */
  9539. Path2.prototype.close = function () {
  9540. this.closed = true;
  9541. return this;
  9542. };
  9543. /**
  9544. * Gets the sum of the distance between each sequential point in the path
  9545. * @returns the Path2 total length (float).
  9546. */
  9547. Path2.prototype.length = function () {
  9548. var result = this._length;
  9549. if (!this.closed) {
  9550. var lastPoint = this._points[this._points.length - 1];
  9551. var firstPoint = this._points[0];
  9552. result += (firstPoint.subtract(lastPoint).length());
  9553. }
  9554. return result;
  9555. };
  9556. /**
  9557. * Gets the points which construct the path
  9558. * @returns the Path2 internal array of points.
  9559. */
  9560. Path2.prototype.getPoints = function () {
  9561. return this._points;
  9562. };
  9563. /**
  9564. * Retreives the point at the distance aways from the starting point
  9565. * @param normalizedLengthPosition the length along the path to retreive the point from
  9566. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9567. */
  9568. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9569. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9570. return Vector2.Zero();
  9571. }
  9572. var lengthPosition = normalizedLengthPosition * this.length();
  9573. var previousOffset = 0;
  9574. for (var i = 0; i < this._points.length; i++) {
  9575. var j = (i + 1) % this._points.length;
  9576. var a = this._points[i];
  9577. var b = this._points[j];
  9578. var bToA = b.subtract(a);
  9579. var nextOffset = (bToA.length() + previousOffset);
  9580. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9581. var dir = bToA.normalize();
  9582. var localOffset = lengthPosition - previousOffset;
  9583. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9584. }
  9585. previousOffset = nextOffset;
  9586. }
  9587. return Vector2.Zero();
  9588. };
  9589. /**
  9590. * Creates a new path starting from an x and y position
  9591. * @param x starting x value
  9592. * @param y starting y value
  9593. * @returns a new Path2 starting at the coordinates (x, y).
  9594. */
  9595. Path2.StartingAt = function (x, y) {
  9596. return new Path2(x, y);
  9597. };
  9598. return Path2;
  9599. }());
  9600. BABYLON.Path2 = Path2;
  9601. /**
  9602. * Represents a 3D path made up of multiple 3D points
  9603. */
  9604. var Path3D = /** @class */ (function () {
  9605. /**
  9606. * new Path3D(path, normal, raw)
  9607. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9608. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  9609. * @param path an array of Vector3, the curve axis of the Path3D
  9610. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9611. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9612. */
  9613. function Path3D(
  9614. /**
  9615. * an array of Vector3, the curve axis of the Path3D
  9616. */
  9617. path, firstNormal, raw) {
  9618. if (firstNormal === void 0) { firstNormal = null; }
  9619. this.path = path;
  9620. this._curve = new Array();
  9621. this._distances = new Array();
  9622. this._tangents = new Array();
  9623. this._normals = new Array();
  9624. this._binormals = new Array();
  9625. for (var p = 0; p < path.length; p++) {
  9626. this._curve[p] = path[p].clone(); // hard copy
  9627. }
  9628. this._raw = raw || false;
  9629. this._compute(firstNormal);
  9630. }
  9631. /**
  9632. * Returns the Path3D array of successive Vector3 designing its curve.
  9633. * @returns the Path3D array of successive Vector3 designing its curve.
  9634. */
  9635. Path3D.prototype.getCurve = function () {
  9636. return this._curve;
  9637. };
  9638. /**
  9639. * Returns an array populated with tangent vectors on each Path3D curve point.
  9640. * @returns an array populated with tangent vectors on each Path3D curve point.
  9641. */
  9642. Path3D.prototype.getTangents = function () {
  9643. return this._tangents;
  9644. };
  9645. /**
  9646. * Returns an array populated with normal vectors on each Path3D curve point.
  9647. * @returns an array populated with normal vectors on each Path3D curve point.
  9648. */
  9649. Path3D.prototype.getNormals = function () {
  9650. return this._normals;
  9651. };
  9652. /**
  9653. * Returns an array populated with binormal vectors on each Path3D curve point.
  9654. * @returns an array populated with binormal vectors on each Path3D curve point.
  9655. */
  9656. Path3D.prototype.getBinormals = function () {
  9657. return this._binormals;
  9658. };
  9659. /**
  9660. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9661. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9662. */
  9663. Path3D.prototype.getDistances = function () {
  9664. return this._distances;
  9665. };
  9666. /**
  9667. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9668. * @param path path which all values are copied into the curves points
  9669. * @param firstNormal which should be projected onto the curve
  9670. * @returns the same object updated.
  9671. */
  9672. Path3D.prototype.update = function (path, firstNormal) {
  9673. if (firstNormal === void 0) { firstNormal = null; }
  9674. for (var p = 0; p < path.length; p++) {
  9675. this._curve[p].x = path[p].x;
  9676. this._curve[p].y = path[p].y;
  9677. this._curve[p].z = path[p].z;
  9678. }
  9679. this._compute(firstNormal);
  9680. return this;
  9681. };
  9682. // private function compute() : computes tangents, normals and binormals
  9683. Path3D.prototype._compute = function (firstNormal) {
  9684. var l = this._curve.length;
  9685. // first and last tangents
  9686. this._tangents[0] = this._getFirstNonNullVector(0);
  9687. if (!this._raw) {
  9688. this._tangents[0].normalize();
  9689. }
  9690. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9691. if (!this._raw) {
  9692. this._tangents[l - 1].normalize();
  9693. }
  9694. // normals and binormals at first point : arbitrary vector with _normalVector()
  9695. var tg0 = this._tangents[0];
  9696. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9697. this._normals[0] = pp0;
  9698. if (!this._raw) {
  9699. this._normals[0].normalize();
  9700. }
  9701. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9702. if (!this._raw) {
  9703. this._binormals[0].normalize();
  9704. }
  9705. this._distances[0] = 0.0;
  9706. // normals and binormals : next points
  9707. var prev; // previous vector (segment)
  9708. var cur; // current vector (segment)
  9709. var curTang; // current tangent
  9710. // previous normal
  9711. var prevBinor; // previous binormal
  9712. for (var i = 1; i < l; i++) {
  9713. // tangents
  9714. prev = this._getLastNonNullVector(i);
  9715. if (i < l - 1) {
  9716. cur = this._getFirstNonNullVector(i);
  9717. this._tangents[i] = prev.add(cur);
  9718. this._tangents[i].normalize();
  9719. }
  9720. this._distances[i] = this._distances[i - 1] + prev.length();
  9721. // normals and binormals
  9722. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9723. curTang = this._tangents[i];
  9724. prevBinor = this._binormals[i - 1];
  9725. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9726. if (!this._raw) {
  9727. this._normals[i].normalize();
  9728. }
  9729. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9730. if (!this._raw) {
  9731. this._binormals[i].normalize();
  9732. }
  9733. }
  9734. };
  9735. // private function getFirstNonNullVector(index)
  9736. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9737. Path3D.prototype._getFirstNonNullVector = function (index) {
  9738. var i = 1;
  9739. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9740. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9741. i++;
  9742. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9743. }
  9744. return nNVector;
  9745. };
  9746. // private function getLastNonNullVector(index)
  9747. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9748. Path3D.prototype._getLastNonNullVector = function (index) {
  9749. var i = 1;
  9750. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9751. while (nLVector.length() === 0 && index > i + 1) {
  9752. i++;
  9753. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9754. }
  9755. return nLVector;
  9756. };
  9757. // private function normalVector(v0, vt, va) :
  9758. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  9759. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  9760. Path3D.prototype._normalVector = function (v0, vt, va) {
  9761. var normal0;
  9762. var tgl = vt.length();
  9763. if (tgl === 0.0) {
  9764. tgl = 1.0;
  9765. }
  9766. if (va === undefined || va === null) {
  9767. var point;
  9768. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  9769. point = new Vector3(0.0, -1.0, 0.0);
  9770. }
  9771. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  9772. point = new Vector3(1.0, 0.0, 0.0);
  9773. }
  9774. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  9775. point = new Vector3(0.0, 0.0, 1.0);
  9776. }
  9777. else {
  9778. point = Vector3.Zero();
  9779. }
  9780. normal0 = Vector3.Cross(vt, point);
  9781. }
  9782. else {
  9783. normal0 = Vector3.Cross(vt, va);
  9784. Vector3.CrossToRef(normal0, vt, normal0);
  9785. }
  9786. normal0.normalize();
  9787. return normal0;
  9788. };
  9789. return Path3D;
  9790. }());
  9791. BABYLON.Path3D = Path3D;
  9792. /**
  9793. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9794. * A Curve3 is designed from a series of successive Vector3.
  9795. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  9796. */
  9797. var Curve3 = /** @class */ (function () {
  9798. /**
  9799. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9800. * A Curve3 is designed from a series of successive Vector3.
  9801. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  9802. * @param points points which make up the curve
  9803. */
  9804. function Curve3(points) {
  9805. this._length = 0.0;
  9806. this._points = points;
  9807. this._length = this._computeLength(points);
  9808. }
  9809. /**
  9810. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  9811. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  9812. * @param v1 (Vector3) the control point
  9813. * @param v2 (Vector3) the end point of the Quadratic Bezier
  9814. * @param nbPoints (integer) the wanted number of points in the curve
  9815. * @returns the created Curve3
  9816. */
  9817. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  9818. nbPoints = nbPoints > 2 ? nbPoints : 3;
  9819. var bez = new Array();
  9820. var equation = function (t, val0, val1, val2) {
  9821. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  9822. return res;
  9823. };
  9824. for (var i = 0; i <= nbPoints; i++) {
  9825. 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)));
  9826. }
  9827. return new Curve3(bez);
  9828. };
  9829. /**
  9830. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  9831. * @param v0 (Vector3) the origin point of the Cubic Bezier
  9832. * @param v1 (Vector3) the first control point
  9833. * @param v2 (Vector3) the second control point
  9834. * @param v3 (Vector3) the end point of the Cubic Bezier
  9835. * @param nbPoints (integer) the wanted number of points in the curve
  9836. * @returns the created Curve3
  9837. */
  9838. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  9839. nbPoints = nbPoints > 3 ? nbPoints : 4;
  9840. var bez = new Array();
  9841. var equation = function (t, val0, val1, val2, val3) {
  9842. 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;
  9843. return res;
  9844. };
  9845. for (var i = 0; i <= nbPoints; i++) {
  9846. 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)));
  9847. }
  9848. return new Curve3(bez);
  9849. };
  9850. /**
  9851. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  9852. * @param p1 (Vector3) the origin point of the Hermite Spline
  9853. * @param t1 (Vector3) the tangent vector at the origin point
  9854. * @param p2 (Vector3) the end point of the Hermite Spline
  9855. * @param t2 (Vector3) the tangent vector at the end point
  9856. * @param nbPoints (integer) the wanted number of points in the curve
  9857. * @returns the created Curve3
  9858. */
  9859. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  9860. var hermite = new Array();
  9861. var step = 1.0 / nbPoints;
  9862. for (var i = 0; i <= nbPoints; i++) {
  9863. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  9864. }
  9865. return new Curve3(hermite);
  9866. };
  9867. /**
  9868. * Returns a Curve3 object along a CatmullRom Spline curve :
  9869. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  9870. * @param nbPoints (integer) the wanted number of points between each curve control points
  9871. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  9872. * @returns the created Curve3
  9873. */
  9874. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  9875. var catmullRom = new Array();
  9876. var step = 1.0 / nbPoints;
  9877. var amount = 0.0;
  9878. if (closed) {
  9879. var pointsCount = points.length;
  9880. for (var i = 0; i < pointsCount; i++) {
  9881. amount = 0;
  9882. for (var c = 0; c < nbPoints; c++) {
  9883. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  9884. amount += step;
  9885. }
  9886. }
  9887. catmullRom.push(catmullRom[0]);
  9888. }
  9889. else {
  9890. var totalPoints = new Array();
  9891. totalPoints.push(points[0].clone());
  9892. Array.prototype.push.apply(totalPoints, points);
  9893. totalPoints.push(points[points.length - 1].clone());
  9894. for (var i = 0; i < totalPoints.length - 3; i++) {
  9895. amount = 0;
  9896. for (var c = 0; c < nbPoints; c++) {
  9897. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9898. amount += step;
  9899. }
  9900. }
  9901. i--;
  9902. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9903. }
  9904. return new Curve3(catmullRom);
  9905. };
  9906. /**
  9907. * @returns the Curve3 stored array of successive Vector3
  9908. */
  9909. Curve3.prototype.getPoints = function () {
  9910. return this._points;
  9911. };
  9912. /**
  9913. * @returns the computed length (float) of the curve.
  9914. */
  9915. Curve3.prototype.length = function () {
  9916. return this._length;
  9917. };
  9918. /**
  9919. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  9920. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  9921. * curveA and curveB keep unchanged.
  9922. * @param curve the curve to continue from this curve
  9923. * @returns the newly constructed curve
  9924. */
  9925. Curve3.prototype.continue = function (curve) {
  9926. var lastPoint = this._points[this._points.length - 1];
  9927. var continuedPoints = this._points.slice();
  9928. var curvePoints = curve.getPoints();
  9929. for (var i = 1; i < curvePoints.length; i++) {
  9930. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  9931. }
  9932. var continuedCurve = new Curve3(continuedPoints);
  9933. return continuedCurve;
  9934. };
  9935. Curve3.prototype._computeLength = function (path) {
  9936. var l = 0;
  9937. for (var i = 1; i < path.length; i++) {
  9938. l += (path[i].subtract(path[i - 1])).length();
  9939. }
  9940. return l;
  9941. };
  9942. return Curve3;
  9943. }());
  9944. BABYLON.Curve3 = Curve3;
  9945. // Vertex formats
  9946. /**
  9947. * Contains position and normal vectors for a vertex
  9948. */
  9949. var PositionNormalVertex = /** @class */ (function () {
  9950. /**
  9951. * Creates a PositionNormalVertex
  9952. * @param position the position of the vertex (defaut: 0,0,0)
  9953. * @param normal the normal of the vertex (defaut: 0,1,0)
  9954. */
  9955. function PositionNormalVertex(
  9956. /** the position of the vertex (defaut: 0,0,0) */
  9957. position,
  9958. /** the normal of the vertex (defaut: 0,1,0) */
  9959. normal) {
  9960. if (position === void 0) { position = Vector3.Zero(); }
  9961. if (normal === void 0) { normal = Vector3.Up(); }
  9962. this.position = position;
  9963. this.normal = normal;
  9964. }
  9965. /**
  9966. * Clones the PositionNormalVertex
  9967. * @returns the cloned PositionNormalVertex
  9968. */
  9969. PositionNormalVertex.prototype.clone = function () {
  9970. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  9971. };
  9972. return PositionNormalVertex;
  9973. }());
  9974. BABYLON.PositionNormalVertex = PositionNormalVertex;
  9975. /**
  9976. * Contains position, normal and uv vectors for a vertex
  9977. */
  9978. var PositionNormalTextureVertex = /** @class */ (function () {
  9979. /**
  9980. * Creates a PositionNormalTextureVertex
  9981. * @param position the position of the vertex (defaut: 0,0,0)
  9982. * @param normal the normal of the vertex (defaut: 0,1,0)
  9983. * @param uv the uv of the vertex (default: 0,0)
  9984. */
  9985. function PositionNormalTextureVertex(
  9986. /** the position of the vertex (defaut: 0,0,0) */
  9987. position,
  9988. /** the normal of the vertex (defaut: 0,1,0) */
  9989. normal,
  9990. /** the uv of the vertex (default: 0,0) */
  9991. uv) {
  9992. if (position === void 0) { position = Vector3.Zero(); }
  9993. if (normal === void 0) { normal = Vector3.Up(); }
  9994. if (uv === void 0) { uv = Vector2.Zero(); }
  9995. this.position = position;
  9996. this.normal = normal;
  9997. this.uv = uv;
  9998. }
  9999. /**
  10000. * Clones the PositionNormalTextureVertex
  10001. * @returns the cloned PositionNormalTextureVertex
  10002. */
  10003. PositionNormalTextureVertex.prototype.clone = function () {
  10004. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  10005. };
  10006. return PositionNormalTextureVertex;
  10007. }());
  10008. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  10009. // Temporary pre-allocated objects for engine internal use
  10010. // usage in any internal function :
  10011. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  10012. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  10013. /**
  10014. * @hidden
  10015. */
  10016. var Tmp = /** @class */ (function () {
  10017. function Tmp() {
  10018. }
  10019. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  10020. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  10021. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  10022. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  10023. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  10024. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  10025. Tmp.Matrix = BABYLON.Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  10026. return Tmp;
  10027. }());
  10028. BABYLON.Tmp = Tmp;
  10029. /**
  10030. * @hidden
  10031. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  10032. */
  10033. var MathTmp = /** @class */ (function () {
  10034. function MathTmp() {
  10035. }
  10036. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  10037. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10038. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10039. return MathTmp;
  10040. }());
  10041. })(BABYLON || (BABYLON = {}));
  10042. //# sourceMappingURL=babylon.math.js.map
  10043. var BABYLON;
  10044. (function (BABYLON) {
  10045. /**
  10046. * Scalar computation library
  10047. */
  10048. var Scalar = /** @class */ (function () {
  10049. function Scalar() {
  10050. }
  10051. /**
  10052. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10053. * @param a number
  10054. * @param b number
  10055. * @param epsilon (default = 1.401298E-45)
  10056. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10057. */
  10058. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10059. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10060. var num = a - b;
  10061. return -epsilon <= num && num <= epsilon;
  10062. };
  10063. /**
  10064. * Returns a string : the upper case translation of the number i to hexadecimal.
  10065. * @param i number
  10066. * @returns the upper case translation of the number i to hexadecimal.
  10067. */
  10068. Scalar.ToHex = function (i) {
  10069. var str = i.toString(16);
  10070. if (i <= 15) {
  10071. return ("0" + str).toUpperCase();
  10072. }
  10073. return str.toUpperCase();
  10074. };
  10075. /**
  10076. * Returns -1 if value is negative and +1 is value is positive.
  10077. * @param value the value
  10078. * @returns the value itself if it's equal to zero.
  10079. */
  10080. Scalar.Sign = function (value) {
  10081. value = +value; // convert to a number
  10082. if (value === 0 || isNaN(value)) {
  10083. return value;
  10084. }
  10085. return value > 0 ? 1 : -1;
  10086. };
  10087. /**
  10088. * Returns the value itself if it's between min and max.
  10089. * Returns min if the value is lower than min.
  10090. * Returns max if the value is greater than max.
  10091. * @param value the value to clmap
  10092. * @param min the min value to clamp to (default: 0)
  10093. * @param max the max value to clamp to (default: 1)
  10094. * @returns the clamped value
  10095. */
  10096. Scalar.Clamp = function (value, min, max) {
  10097. if (min === void 0) { min = 0; }
  10098. if (max === void 0) { max = 1; }
  10099. return Math.min(max, Math.max(min, value));
  10100. };
  10101. /**
  10102. * the log2 of value.
  10103. * @param value the value to compute log2 of
  10104. * @returns the log2 of value.
  10105. */
  10106. Scalar.Log2 = function (value) {
  10107. return Math.log(value) * Math.LOG2E;
  10108. };
  10109. /**
  10110. * Loops the value, so that it is never larger than length and never smaller than 0.
  10111. *
  10112. * This is similar to the modulo operator but it works with floating point numbers.
  10113. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10114. * With t = 5 and length = 2.5, the result would be 0.0.
  10115. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10116. * @param value the value
  10117. * @param length the length
  10118. * @returns the looped value
  10119. */
  10120. Scalar.Repeat = function (value, length) {
  10121. return value - Math.floor(value / length) * length;
  10122. };
  10123. /**
  10124. * Normalize the value between 0.0 and 1.0 using min and max values
  10125. * @param value value to normalize
  10126. * @param min max to normalize between
  10127. * @param max min to normalize between
  10128. * @returns the normalized value
  10129. */
  10130. Scalar.Normalize = function (value, min, max) {
  10131. return (value - min) / (max - min);
  10132. };
  10133. /**
  10134. * Denormalize the value from 0.0 and 1.0 using min and max values
  10135. * @param normalized value to denormalize
  10136. * @param min max to denormalize between
  10137. * @param max min to denormalize between
  10138. * @returns the denormalized value
  10139. */
  10140. Scalar.Denormalize = function (normalized, min, max) {
  10141. return (normalized * (max - min) + min);
  10142. };
  10143. /**
  10144. * Calculates the shortest difference between two given angles given in degrees.
  10145. * @param current current angle in degrees
  10146. * @param target target angle in degrees
  10147. * @returns the delta
  10148. */
  10149. Scalar.DeltaAngle = function (current, target) {
  10150. var num = Scalar.Repeat(target - current, 360.0);
  10151. if (num > 180.0) {
  10152. num -= 360.0;
  10153. }
  10154. return num;
  10155. };
  10156. /**
  10157. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10158. * @param tx value
  10159. * @param length length
  10160. * @returns The returned value will move back and forth between 0 and length
  10161. */
  10162. Scalar.PingPong = function (tx, length) {
  10163. var t = Scalar.Repeat(tx, length * 2.0);
  10164. return length - Math.abs(t - length);
  10165. };
  10166. /**
  10167. * Interpolates between min and max with smoothing at the limits.
  10168. *
  10169. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10170. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10171. * @param from from
  10172. * @param to to
  10173. * @param tx value
  10174. * @returns the smooth stepped value
  10175. */
  10176. Scalar.SmoothStep = function (from, to, tx) {
  10177. var t = Scalar.Clamp(tx);
  10178. t = -2.0 * t * t * t + 3.0 * t * t;
  10179. return to * t + from * (1.0 - t);
  10180. };
  10181. /**
  10182. * Moves a value current towards target.
  10183. *
  10184. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10185. * Negative values of maxDelta pushes the value away from target.
  10186. * @param current current value
  10187. * @param target target value
  10188. * @param maxDelta max distance to move
  10189. * @returns resulting value
  10190. */
  10191. Scalar.MoveTowards = function (current, target, maxDelta) {
  10192. var result = 0;
  10193. if (Math.abs(target - current) <= maxDelta) {
  10194. result = target;
  10195. }
  10196. else {
  10197. result = current + Scalar.Sign(target - current) * maxDelta;
  10198. }
  10199. return result;
  10200. };
  10201. /**
  10202. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10203. *
  10204. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10205. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10206. * @param current current value
  10207. * @param target target value
  10208. * @param maxDelta max distance to move
  10209. * @returns resulting angle
  10210. */
  10211. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10212. var num = Scalar.DeltaAngle(current, target);
  10213. var result = 0;
  10214. if (-maxDelta < num && num < maxDelta) {
  10215. result = target;
  10216. }
  10217. else {
  10218. target = current + num;
  10219. result = Scalar.MoveTowards(current, target, maxDelta);
  10220. }
  10221. return result;
  10222. };
  10223. /**
  10224. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10225. * @param start start value
  10226. * @param end target value
  10227. * @param amount amount to lerp between
  10228. * @returns the lerped value
  10229. */
  10230. Scalar.Lerp = function (start, end, amount) {
  10231. return start + ((end - start) * amount);
  10232. };
  10233. /**
  10234. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10235. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10236. * @param start start value
  10237. * @param end target value
  10238. * @param amount amount to lerp between
  10239. * @returns the lerped value
  10240. */
  10241. Scalar.LerpAngle = function (start, end, amount) {
  10242. var num = Scalar.Repeat(end - start, 360.0);
  10243. if (num > 180.0) {
  10244. num -= 360.0;
  10245. }
  10246. return start + num * Scalar.Clamp(amount);
  10247. };
  10248. /**
  10249. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10250. * @param a start value
  10251. * @param b target value
  10252. * @param value value between a and b
  10253. * @returns the inverseLerp value
  10254. */
  10255. Scalar.InverseLerp = function (a, b, value) {
  10256. var result = 0;
  10257. if (a != b) {
  10258. result = Scalar.Clamp((value - a) / (b - a));
  10259. }
  10260. else {
  10261. result = 0.0;
  10262. }
  10263. return result;
  10264. };
  10265. /**
  10266. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10267. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10268. * @param value1 spline value
  10269. * @param tangent1 spline value
  10270. * @param value2 spline value
  10271. * @param tangent2 spline value
  10272. * @param amount input value
  10273. * @returns hermite result
  10274. */
  10275. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10276. var squared = amount * amount;
  10277. var cubed = amount * squared;
  10278. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10279. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10280. var part3 = (cubed - (2.0 * squared)) + amount;
  10281. var part4 = cubed - squared;
  10282. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10283. };
  10284. /**
  10285. * Returns a random float number between and min and max values
  10286. * @param min min value of random
  10287. * @param max max value of random
  10288. * @returns random value
  10289. */
  10290. Scalar.RandomRange = function (min, max) {
  10291. if (min === max) {
  10292. return min;
  10293. }
  10294. return ((Math.random() * (max - min)) + min);
  10295. };
  10296. /**
  10297. * This function returns percentage of a number in a given range.
  10298. *
  10299. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10300. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10301. * @param number to convert to percentage
  10302. * @param min min range
  10303. * @param max max range
  10304. * @returns the percentage
  10305. */
  10306. Scalar.RangeToPercent = function (number, min, max) {
  10307. return ((number - min) / (max - min));
  10308. };
  10309. /**
  10310. * This function returns number that corresponds to the percentage in a given range.
  10311. *
  10312. * PercentToRange(0.34,0,100) will return 34.
  10313. * @param percent to convert to number
  10314. * @param min min range
  10315. * @param max max range
  10316. * @returns the number
  10317. */
  10318. Scalar.PercentToRange = function (percent, min, max) {
  10319. return ((max - min) * percent + min);
  10320. };
  10321. /**
  10322. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10323. * @param angle The angle to normalize in radian.
  10324. * @return The converted angle.
  10325. */
  10326. Scalar.NormalizeRadians = function (angle) {
  10327. // More precise but slower version kept for reference.
  10328. // angle = angle % Tools.TwoPi;
  10329. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10330. //if (angle > Math.PI) {
  10331. // angle -= Tools.TwoPi;
  10332. //}
  10333. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10334. return angle;
  10335. };
  10336. /**
  10337. * Two pi constants convenient for computation.
  10338. */
  10339. Scalar.TwoPi = Math.PI * 2;
  10340. return Scalar;
  10341. }());
  10342. BABYLON.Scalar = Scalar;
  10343. })(BABYLON || (BABYLON = {}));
  10344. //# sourceMappingURL=babylon.math.scalar.js.map
  10345. //# sourceMappingURL=babylon.mixins.js.map
  10346. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10347. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10348. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10349. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10350. //# sourceMappingURL=babylon.webgl2.js.map
  10351. var BABYLON;
  10352. (function (BABYLON) {
  10353. var __decoratorInitialStore = {};
  10354. var __mergedStore = {};
  10355. var _copySource = function (creationFunction, source, instanciate) {
  10356. var destination = creationFunction();
  10357. // Tags
  10358. if (BABYLON.Tags) {
  10359. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10360. }
  10361. var classStore = getMergedStore(destination);
  10362. // Properties
  10363. for (var property in classStore) {
  10364. var propertyDescriptor = classStore[property];
  10365. var sourceProperty = source[property];
  10366. var propertyType = propertyDescriptor.type;
  10367. if (sourceProperty !== undefined && sourceProperty !== null) {
  10368. switch (propertyType) {
  10369. case 0: // Value
  10370. case 6: // Mesh reference
  10371. case 11: // Camera reference
  10372. destination[property] = sourceProperty;
  10373. break;
  10374. case 1: // Texture
  10375. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10376. break;
  10377. case 2: // Color3
  10378. case 3: // FresnelParameters
  10379. case 4: // Vector2
  10380. case 5: // Vector3
  10381. case 7: // Color Curves
  10382. case 10: // Quaternion
  10383. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10384. break;
  10385. }
  10386. }
  10387. }
  10388. return destination;
  10389. };
  10390. function getDirectStore(target) {
  10391. var classKey = target.getClassName();
  10392. if (!__decoratorInitialStore[classKey]) {
  10393. __decoratorInitialStore[classKey] = {};
  10394. }
  10395. return __decoratorInitialStore[classKey];
  10396. }
  10397. /**
  10398. * Return the list of properties flagged as serializable
  10399. * @param target: host object
  10400. */
  10401. function getMergedStore(target) {
  10402. var classKey = target.getClassName();
  10403. if (__mergedStore[classKey]) {
  10404. return __mergedStore[classKey];
  10405. }
  10406. __mergedStore[classKey] = {};
  10407. var store = __mergedStore[classKey];
  10408. var currentTarget = target;
  10409. var currentKey = classKey;
  10410. while (currentKey) {
  10411. var initialStore = __decoratorInitialStore[currentKey];
  10412. for (var property in initialStore) {
  10413. store[property] = initialStore[property];
  10414. }
  10415. var parent_1 = void 0;
  10416. var done = false;
  10417. do {
  10418. parent_1 = Object.getPrototypeOf(currentTarget);
  10419. if (!parent_1.getClassName) {
  10420. done = true;
  10421. break;
  10422. }
  10423. if (parent_1.getClassName() !== currentKey) {
  10424. break;
  10425. }
  10426. currentTarget = parent_1;
  10427. } while (parent_1);
  10428. if (done) {
  10429. break;
  10430. }
  10431. currentKey = parent_1.getClassName();
  10432. currentTarget = parent_1;
  10433. }
  10434. return store;
  10435. }
  10436. function generateSerializableMember(type, sourceName) {
  10437. return function (target, propertyKey) {
  10438. var classStore = getDirectStore(target);
  10439. if (!classStore[propertyKey]) {
  10440. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10441. }
  10442. };
  10443. }
  10444. function generateExpandMember(setCallback, targetKey) {
  10445. if (targetKey === void 0) { targetKey = null; }
  10446. return function (target, propertyKey) {
  10447. var key = targetKey || ("_" + propertyKey);
  10448. Object.defineProperty(target, propertyKey, {
  10449. get: function () {
  10450. return this[key];
  10451. },
  10452. set: function (value) {
  10453. if (this[key] === value) {
  10454. return;
  10455. }
  10456. this[key] = value;
  10457. target[setCallback].apply(this);
  10458. },
  10459. enumerable: true,
  10460. configurable: true
  10461. });
  10462. };
  10463. }
  10464. function expandToProperty(callback, targetKey) {
  10465. if (targetKey === void 0) { targetKey = null; }
  10466. return generateExpandMember(callback, targetKey);
  10467. }
  10468. BABYLON.expandToProperty = expandToProperty;
  10469. function serialize(sourceName) {
  10470. return generateSerializableMember(0, sourceName); // value member
  10471. }
  10472. BABYLON.serialize = serialize;
  10473. function serializeAsTexture(sourceName) {
  10474. return generateSerializableMember(1, sourceName); // texture member
  10475. }
  10476. BABYLON.serializeAsTexture = serializeAsTexture;
  10477. function serializeAsColor3(sourceName) {
  10478. return generateSerializableMember(2, sourceName); // color3 member
  10479. }
  10480. BABYLON.serializeAsColor3 = serializeAsColor3;
  10481. function serializeAsFresnelParameters(sourceName) {
  10482. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10483. }
  10484. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10485. function serializeAsVector2(sourceName) {
  10486. return generateSerializableMember(4, sourceName); // vector2 member
  10487. }
  10488. BABYLON.serializeAsVector2 = serializeAsVector2;
  10489. function serializeAsVector3(sourceName) {
  10490. return generateSerializableMember(5, sourceName); // vector3 member
  10491. }
  10492. BABYLON.serializeAsVector3 = serializeAsVector3;
  10493. function serializeAsMeshReference(sourceName) {
  10494. return generateSerializableMember(6, sourceName); // mesh reference member
  10495. }
  10496. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10497. function serializeAsColorCurves(sourceName) {
  10498. return generateSerializableMember(7, sourceName); // color curves
  10499. }
  10500. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10501. function serializeAsColor4(sourceName) {
  10502. return generateSerializableMember(8, sourceName); // color 4
  10503. }
  10504. BABYLON.serializeAsColor4 = serializeAsColor4;
  10505. function serializeAsImageProcessingConfiguration(sourceName) {
  10506. return generateSerializableMember(9, sourceName); // image processing
  10507. }
  10508. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10509. function serializeAsQuaternion(sourceName) {
  10510. return generateSerializableMember(10, sourceName); // quaternion member
  10511. }
  10512. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10513. /**
  10514. * Decorator used to define property that can be serialized as reference to a camera
  10515. * @param sourceName defines the name of the property to decorate
  10516. */
  10517. function serializeAsCameraReference(sourceName) {
  10518. return generateSerializableMember(11, sourceName); // camera reference member
  10519. }
  10520. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10521. /**
  10522. * Class used to help serialization objects
  10523. */
  10524. var SerializationHelper = /** @class */ (function () {
  10525. function SerializationHelper() {
  10526. }
  10527. /**
  10528. * Static function used to serialized a specific entity
  10529. * @param entity defines the entity to serialize
  10530. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10531. * @returns a JSON compatible object representing the serialization of the entity
  10532. */
  10533. SerializationHelper.Serialize = function (entity, serializationObject) {
  10534. if (!serializationObject) {
  10535. serializationObject = {};
  10536. }
  10537. // Tags
  10538. if (BABYLON.Tags) {
  10539. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10540. }
  10541. var serializedProperties = getMergedStore(entity);
  10542. // Properties
  10543. for (var property in serializedProperties) {
  10544. var propertyDescriptor = serializedProperties[property];
  10545. var targetPropertyName = propertyDescriptor.sourceName || property;
  10546. var propertyType = propertyDescriptor.type;
  10547. var sourceProperty = entity[property];
  10548. if (sourceProperty !== undefined && sourceProperty !== null) {
  10549. switch (propertyType) {
  10550. case 0: // Value
  10551. serializationObject[targetPropertyName] = sourceProperty;
  10552. break;
  10553. case 1: // Texture
  10554. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10555. break;
  10556. case 2: // Color3
  10557. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10558. break;
  10559. case 3: // FresnelParameters
  10560. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10561. break;
  10562. case 4: // Vector2
  10563. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10564. break;
  10565. case 5: // Vector3
  10566. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10567. break;
  10568. case 6: // Mesh reference
  10569. serializationObject[targetPropertyName] = sourceProperty.id;
  10570. break;
  10571. case 7: // Color Curves
  10572. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10573. break;
  10574. case 8: // Color 4
  10575. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10576. break;
  10577. case 9: // Image Processing
  10578. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10579. break;
  10580. case 10: // Quaternion
  10581. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10582. break;
  10583. case 11: // Camera reference
  10584. serializationObject[targetPropertyName] = sourceProperty.id;
  10585. break;
  10586. }
  10587. }
  10588. }
  10589. return serializationObject;
  10590. };
  10591. /**
  10592. * Creates a new entity from a serialization data object
  10593. * @param creationFunction defines a function used to instanciated the new entity
  10594. * @param source defines the source serialization data
  10595. * @param scene defines the hosting scene
  10596. * @param rootUrl defines the root url for resources
  10597. * @returns a new entity
  10598. */
  10599. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10600. if (rootUrl === void 0) { rootUrl = null; }
  10601. var destination = creationFunction();
  10602. if (!rootUrl) {
  10603. rootUrl = "";
  10604. }
  10605. // Tags
  10606. if (BABYLON.Tags) {
  10607. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10608. }
  10609. var classStore = getMergedStore(destination);
  10610. // Properties
  10611. for (var property in classStore) {
  10612. var propertyDescriptor = classStore[property];
  10613. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10614. var propertyType = propertyDescriptor.type;
  10615. if (sourceProperty !== undefined && sourceProperty !== null) {
  10616. var dest = destination;
  10617. switch (propertyType) {
  10618. case 0: // Value
  10619. dest[property] = sourceProperty;
  10620. break;
  10621. case 1: // Texture
  10622. if (scene) {
  10623. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10624. }
  10625. break;
  10626. case 2: // Color3
  10627. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10628. break;
  10629. case 3: // FresnelParameters
  10630. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10631. break;
  10632. case 4: // Vector2
  10633. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10634. break;
  10635. case 5: // Vector3
  10636. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10637. break;
  10638. case 6: // Mesh reference
  10639. if (scene) {
  10640. dest[property] = scene.getLastMeshByID(sourceProperty);
  10641. }
  10642. break;
  10643. case 7: // Color Curves
  10644. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10645. break;
  10646. case 8: // Color 4
  10647. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10648. break;
  10649. case 9: // Image Processing
  10650. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10651. break;
  10652. case 10: // Quaternion
  10653. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10654. break;
  10655. case 11: // Camera reference
  10656. if (scene) {
  10657. dest[property] = scene.getCameraByID(sourceProperty);
  10658. }
  10659. break;
  10660. }
  10661. }
  10662. }
  10663. return destination;
  10664. };
  10665. /**
  10666. * Clones an object
  10667. * @param creationFunction defines the function used to instanciate the new object
  10668. * @param source defines the source object
  10669. * @returns the cloned object
  10670. */
  10671. SerializationHelper.Clone = function (creationFunction, source) {
  10672. return _copySource(creationFunction, source, false);
  10673. };
  10674. /**
  10675. * Instanciates a new object based on a source one (some data will be shared between both object)
  10676. * @param creationFunction defines the function used to instanciate the new object
  10677. * @param source defines the source object
  10678. * @returns the new object
  10679. */
  10680. SerializationHelper.Instanciate = function (creationFunction, source) {
  10681. return _copySource(creationFunction, source, true);
  10682. };
  10683. return SerializationHelper;
  10684. }());
  10685. BABYLON.SerializationHelper = SerializationHelper;
  10686. })(BABYLON || (BABYLON = {}));
  10687. //# sourceMappingURL=babylon.decorators.js.map
  10688. var BABYLON;
  10689. (function (BABYLON) {
  10690. /**
  10691. * Wrapper class for promise with external resolve and reject.
  10692. */
  10693. var Deferred = /** @class */ (function () {
  10694. /**
  10695. * Constructor for this deferred object.
  10696. */
  10697. function Deferred() {
  10698. var _this = this;
  10699. this.promise = new Promise(function (resolve, reject) {
  10700. _this._resolve = resolve;
  10701. _this._reject = reject;
  10702. });
  10703. }
  10704. Object.defineProperty(Deferred.prototype, "resolve", {
  10705. /**
  10706. * The resolve method of the promise associated with this deferred object.
  10707. */
  10708. get: function () {
  10709. return this._resolve;
  10710. },
  10711. enumerable: true,
  10712. configurable: true
  10713. });
  10714. Object.defineProperty(Deferred.prototype, "reject", {
  10715. /**
  10716. * The reject method of the promise associated with this deferred object.
  10717. */
  10718. get: function () {
  10719. return this._reject;
  10720. },
  10721. enumerable: true,
  10722. configurable: true
  10723. });
  10724. return Deferred;
  10725. }());
  10726. BABYLON.Deferred = Deferred;
  10727. })(BABYLON || (BABYLON = {}));
  10728. //# sourceMappingURL=babylon.deferred.js.map
  10729. var BABYLON;
  10730. (function (BABYLON) {
  10731. /**
  10732. * A class serves as a medium between the observable and its observers
  10733. */
  10734. var EventState = /** @class */ (function () {
  10735. /**
  10736. * Create a new EventState
  10737. * @param mask defines the mask associated with this state
  10738. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10739. * @param target defines the original target of the state
  10740. * @param currentTarget defines the current target of the state
  10741. */
  10742. function EventState(mask, skipNextObservers, target, currentTarget) {
  10743. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10744. this.initalize(mask, skipNextObservers, target, currentTarget);
  10745. }
  10746. /**
  10747. * Initialize the current event state
  10748. * @param mask defines the mask associated with this state
  10749. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10750. * @param target defines the original target of the state
  10751. * @param currentTarget defines the current target of the state
  10752. * @returns the current event state
  10753. */
  10754. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10755. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10756. this.mask = mask;
  10757. this.skipNextObservers = skipNextObservers;
  10758. this.target = target;
  10759. this.currentTarget = currentTarget;
  10760. return this;
  10761. };
  10762. return EventState;
  10763. }());
  10764. BABYLON.EventState = EventState;
  10765. /**
  10766. * Represent an Observer registered to a given Observable object.
  10767. */
  10768. var Observer = /** @class */ (function () {
  10769. /**
  10770. * Creates a new observer
  10771. * @param callback defines the callback to call when the observer is notified
  10772. * @param mask defines the mask of the observer (used to filter notifications)
  10773. * @param scope defines the current scope used to restore the JS context
  10774. */
  10775. function Observer(
  10776. /**
  10777. * Defines the callback to call when the observer is notified
  10778. */
  10779. callback,
  10780. /**
  10781. * Defines the mask of the observer (used to filter notifications)
  10782. */
  10783. mask,
  10784. /**
  10785. * Defines the current scope used to restore the JS context
  10786. */
  10787. scope) {
  10788. if (scope === void 0) { scope = null; }
  10789. this.callback = callback;
  10790. this.mask = mask;
  10791. this.scope = scope;
  10792. /** @hidden */
  10793. this._willBeUnregistered = false;
  10794. /**
  10795. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  10796. */
  10797. this.unregisterOnNextCall = false;
  10798. }
  10799. return Observer;
  10800. }());
  10801. BABYLON.Observer = Observer;
  10802. /**
  10803. * Represent a list of observers registered to multiple Observables object.
  10804. */
  10805. var MultiObserver = /** @class */ (function () {
  10806. function MultiObserver() {
  10807. }
  10808. /**
  10809. * Release associated resources
  10810. */
  10811. MultiObserver.prototype.dispose = function () {
  10812. if (this._observers && this._observables) {
  10813. for (var index = 0; index < this._observers.length; index++) {
  10814. this._observables[index].remove(this._observers[index]);
  10815. }
  10816. }
  10817. this._observers = null;
  10818. this._observables = null;
  10819. };
  10820. /**
  10821. * Raise a callback when one of the observable will notify
  10822. * @param observables defines a list of observables to watch
  10823. * @param callback defines the callback to call on notification
  10824. * @param mask defines the mask used to filter notifications
  10825. * @param scope defines the current scope used to restore the JS context
  10826. * @returns the new MultiObserver
  10827. */
  10828. MultiObserver.Watch = function (observables, callback, mask, scope) {
  10829. if (mask === void 0) { mask = -1; }
  10830. if (scope === void 0) { scope = null; }
  10831. var result = new MultiObserver();
  10832. result._observers = new Array();
  10833. result._observables = observables;
  10834. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  10835. var observable = observables_1[_i];
  10836. var observer = observable.add(callback, mask, false, scope);
  10837. if (observer) {
  10838. result._observers.push(observer);
  10839. }
  10840. }
  10841. return result;
  10842. };
  10843. return MultiObserver;
  10844. }());
  10845. BABYLON.MultiObserver = MultiObserver;
  10846. /**
  10847. * The Observable class is a simple implementation of the Observable pattern.
  10848. *
  10849. * 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.
  10850. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  10851. * 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).
  10852. * 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.
  10853. */
  10854. var Observable = /** @class */ (function () {
  10855. /**
  10856. * Creates a new observable
  10857. * @param onObserverAdded defines a callback to call when a new observer is added
  10858. */
  10859. function Observable(onObserverAdded) {
  10860. this._observers = new Array();
  10861. this._eventState = new EventState(0);
  10862. if (onObserverAdded) {
  10863. this._onObserverAdded = onObserverAdded;
  10864. }
  10865. }
  10866. /**
  10867. * Create a new Observer with the specified callback
  10868. * @param callback the callback that will be executed for that Observer
  10869. * @param mask the mask used to filter observers
  10870. * @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.
  10871. * @param scope optional scope for the callback to be called from
  10872. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  10873. * @returns the new observer created for the callback
  10874. */
  10875. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  10876. if (mask === void 0) { mask = -1; }
  10877. if (insertFirst === void 0) { insertFirst = false; }
  10878. if (scope === void 0) { scope = null; }
  10879. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  10880. if (!callback) {
  10881. return null;
  10882. }
  10883. var observer = new Observer(callback, mask, scope);
  10884. observer.unregisterOnNextCall = unregisterOnFirstCall;
  10885. if (insertFirst) {
  10886. this._observers.unshift(observer);
  10887. }
  10888. else {
  10889. this._observers.push(observer);
  10890. }
  10891. if (this._onObserverAdded) {
  10892. this._onObserverAdded(observer);
  10893. }
  10894. return observer;
  10895. };
  10896. /**
  10897. * Create a new Observer with the specified callback and unregisters after the next notification
  10898. * @param callback the callback that will be executed for that Observer
  10899. * @returns the new observer created for the callback
  10900. */
  10901. Observable.prototype.addOnce = function (callback) {
  10902. return this.add(callback, undefined, undefined, undefined, true);
  10903. };
  10904. /**
  10905. * Remove an Observer from the Observable object
  10906. * @param observer the instance of the Observer to remove
  10907. * @returns false if it doesn't belong to this Observable
  10908. */
  10909. Observable.prototype.remove = function (observer) {
  10910. if (!observer) {
  10911. return false;
  10912. }
  10913. var index = this._observers.indexOf(observer);
  10914. if (index !== -1) {
  10915. this._deferUnregister(observer);
  10916. return true;
  10917. }
  10918. return false;
  10919. };
  10920. /**
  10921. * Remove a callback from the Observable object
  10922. * @param callback the callback to remove
  10923. * @param scope optional scope. If used only the callbacks with this scope will be removed
  10924. * @returns false if it doesn't belong to this Observable
  10925. */
  10926. Observable.prototype.removeCallback = function (callback, scope) {
  10927. for (var index = 0; index < this._observers.length; index++) {
  10928. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  10929. this._deferUnregister(this._observers[index]);
  10930. return true;
  10931. }
  10932. }
  10933. return false;
  10934. };
  10935. Observable.prototype._deferUnregister = function (observer) {
  10936. var _this = this;
  10937. observer.unregisterOnNextCall = false;
  10938. observer._willBeUnregistered = true;
  10939. BABYLON.Tools.SetImmediate(function () {
  10940. _this._remove(observer);
  10941. });
  10942. };
  10943. // This should only be called when not iterating over _observers to avoid callback skipping.
  10944. // Removes an observer from the _observer Array.
  10945. Observable.prototype._remove = function (observer) {
  10946. if (!observer) {
  10947. return false;
  10948. }
  10949. var index = this._observers.indexOf(observer);
  10950. if (index !== -1) {
  10951. this._observers.splice(index, 1);
  10952. return true;
  10953. }
  10954. return false;
  10955. };
  10956. /**
  10957. * Notify all Observers by calling their respective callback with the given data
  10958. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  10959. * @param eventData defines the data to send to all observers
  10960. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  10961. * @param target defines the original target of the state
  10962. * @param currentTarget defines the current target of the state
  10963. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  10964. */
  10965. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  10966. if (mask === void 0) { mask = -1; }
  10967. if (!this._observers.length) {
  10968. return true;
  10969. }
  10970. var state = this._eventState;
  10971. state.mask = mask;
  10972. state.target = target;
  10973. state.currentTarget = currentTarget;
  10974. state.skipNextObservers = false;
  10975. state.lastReturnValue = eventData;
  10976. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  10977. var obs = _a[_i];
  10978. if (obs._willBeUnregistered) {
  10979. continue;
  10980. }
  10981. if (obs.mask & mask) {
  10982. if (obs.scope) {
  10983. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  10984. }
  10985. else {
  10986. state.lastReturnValue = obs.callback(eventData, state);
  10987. }
  10988. if (obs.unregisterOnNextCall) {
  10989. this._deferUnregister(obs);
  10990. }
  10991. }
  10992. if (state.skipNextObservers) {
  10993. return false;
  10994. }
  10995. }
  10996. return true;
  10997. };
  10998. /**
  10999. * Calling this will execute each callback, expecting it to be a promise or return a value.
  11000. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  11001. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  11002. * and it is crucial that all callbacks will be executed.
  11003. * The order of the callbacks is kept, callbacks are not executed parallel.
  11004. *
  11005. * @param eventData The data to be sent to each callback
  11006. * @param mask is used to filter observers defaults to -1
  11007. * @param target defines the callback target (see EventState)
  11008. * @param currentTarget defines he current object in the bubbling phase
  11009. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  11010. */
  11011. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  11012. var _this = this;
  11013. if (mask === void 0) { mask = -1; }
  11014. // create an empty promise
  11015. var p = Promise.resolve(eventData);
  11016. // no observers? return this promise.
  11017. if (!this._observers.length) {
  11018. return p;
  11019. }
  11020. var state = this._eventState;
  11021. state.mask = mask;
  11022. state.target = target;
  11023. state.currentTarget = currentTarget;
  11024. state.skipNextObservers = false;
  11025. // execute one callback after another (not using Promise.all, the order is important)
  11026. this._observers.forEach(function (obs) {
  11027. if (state.skipNextObservers) {
  11028. return;
  11029. }
  11030. if (obs._willBeUnregistered) {
  11031. return;
  11032. }
  11033. if (obs.mask & mask) {
  11034. if (obs.scope) {
  11035. p = p.then(function (lastReturnedValue) {
  11036. state.lastReturnValue = lastReturnedValue;
  11037. return obs.callback.apply(obs.scope, [eventData, state]);
  11038. });
  11039. }
  11040. else {
  11041. p = p.then(function (lastReturnedValue) {
  11042. state.lastReturnValue = lastReturnedValue;
  11043. return obs.callback(eventData, state);
  11044. });
  11045. }
  11046. if (obs.unregisterOnNextCall) {
  11047. _this._deferUnregister(obs);
  11048. }
  11049. }
  11050. });
  11051. // return the eventData
  11052. return p.then(function () { return eventData; });
  11053. };
  11054. /**
  11055. * Notify a specific observer
  11056. * @param observer defines the observer to notify
  11057. * @param eventData defines the data to be sent to each callback
  11058. * @param mask is used to filter observers defaults to -1
  11059. */
  11060. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11061. if (mask === void 0) { mask = -1; }
  11062. var state = this._eventState;
  11063. state.mask = mask;
  11064. state.skipNextObservers = false;
  11065. observer.callback(eventData, state);
  11066. };
  11067. /**
  11068. * Gets a boolean indicating if the observable has at least one observer
  11069. * @returns true is the Observable has at least one Observer registered
  11070. */
  11071. Observable.prototype.hasObservers = function () {
  11072. return this._observers.length > 0;
  11073. };
  11074. /**
  11075. * Clear the list of observers
  11076. */
  11077. Observable.prototype.clear = function () {
  11078. this._observers = new Array();
  11079. this._onObserverAdded = null;
  11080. };
  11081. /**
  11082. * Clone the current observable
  11083. * @returns a new observable
  11084. */
  11085. Observable.prototype.clone = function () {
  11086. var result = new Observable();
  11087. result._observers = this._observers.slice(0);
  11088. return result;
  11089. };
  11090. /**
  11091. * Does this observable handles observer registered with a given mask
  11092. * @param mask defines the mask to be tested
  11093. * @return whether or not one observer registered with the given mask is handeled
  11094. **/
  11095. Observable.prototype.hasSpecificMask = function (mask) {
  11096. if (mask === void 0) { mask = -1; }
  11097. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11098. var obs = _a[_i];
  11099. if (obs.mask & mask || obs.mask === mask) {
  11100. return true;
  11101. }
  11102. }
  11103. return false;
  11104. };
  11105. return Observable;
  11106. }());
  11107. BABYLON.Observable = Observable;
  11108. })(BABYLON || (BABYLON = {}));
  11109. //# sourceMappingURL=babylon.observable.js.map
  11110. var BABYLON;
  11111. (function (BABYLON) {
  11112. /**
  11113. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11114. */
  11115. var SmartArray = /** @class */ (function () {
  11116. /**
  11117. * Instantiates a Smart Array.
  11118. * @param capacity defines the default capacity of the array.
  11119. */
  11120. function SmartArray(capacity) {
  11121. /**
  11122. * The active length of the array.
  11123. */
  11124. this.length = 0;
  11125. this.data = new Array(capacity);
  11126. this._id = SmartArray._GlobalId++;
  11127. }
  11128. /**
  11129. * Pushes a value at the end of the active data.
  11130. * @param value defines the object to push in the array.
  11131. */
  11132. SmartArray.prototype.push = function (value) {
  11133. this.data[this.length++] = value;
  11134. if (this.length > this.data.length) {
  11135. this.data.length *= 2;
  11136. }
  11137. };
  11138. /**
  11139. * Iterates over the active data and apply the lambda to them.
  11140. * @param func defines the action to apply on each value.
  11141. */
  11142. SmartArray.prototype.forEach = function (func) {
  11143. for (var index = 0; index < this.length; index++) {
  11144. func(this.data[index]);
  11145. }
  11146. };
  11147. /**
  11148. * Sorts the full sets of data.
  11149. * @param compareFn defines the comparison function to apply.
  11150. */
  11151. SmartArray.prototype.sort = function (compareFn) {
  11152. this.data.sort(compareFn);
  11153. };
  11154. /**
  11155. * Resets the active data to an empty array.
  11156. */
  11157. SmartArray.prototype.reset = function () {
  11158. this.length = 0;
  11159. };
  11160. /**
  11161. * Releases all the data from the array as well as the array.
  11162. */
  11163. SmartArray.prototype.dispose = function () {
  11164. this.reset();
  11165. if (this.data) {
  11166. this.data.length = 0;
  11167. this.data = [];
  11168. }
  11169. };
  11170. /**
  11171. * Concats the active data with a given array.
  11172. * @param array defines the data to concatenate with.
  11173. */
  11174. SmartArray.prototype.concat = function (array) {
  11175. if (array.length === 0) {
  11176. return;
  11177. }
  11178. if (this.length + array.length > this.data.length) {
  11179. this.data.length = (this.length + array.length) * 2;
  11180. }
  11181. for (var index = 0; index < array.length; index++) {
  11182. this.data[this.length++] = (array.data || array)[index];
  11183. }
  11184. };
  11185. /**
  11186. * Returns the position of a value in the active data.
  11187. * @param value defines the value to find the index for
  11188. * @returns the index if found in the active data otherwise -1
  11189. */
  11190. SmartArray.prototype.indexOf = function (value) {
  11191. var position = this.data.indexOf(value);
  11192. if (position >= this.length) {
  11193. return -1;
  11194. }
  11195. return position;
  11196. };
  11197. /**
  11198. * Returns whether an element is part of the active data.
  11199. * @param value defines the value to look for
  11200. * @returns true if found in the active data otherwise false
  11201. */
  11202. SmartArray.prototype.contains = function (value) {
  11203. return this.indexOf(value) !== -1;
  11204. };
  11205. // Statics
  11206. SmartArray._GlobalId = 0;
  11207. return SmartArray;
  11208. }());
  11209. BABYLON.SmartArray = SmartArray;
  11210. /**
  11211. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11212. * The data in this array can only be present once
  11213. */
  11214. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11215. __extends(SmartArrayNoDuplicate, _super);
  11216. function SmartArrayNoDuplicate() {
  11217. var _this = _super !== null && _super.apply(this, arguments) || this;
  11218. _this._duplicateId = 0;
  11219. return _this;
  11220. }
  11221. /**
  11222. * Pushes a value at the end of the active data.
  11223. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11224. * @param value defines the object to push in the array.
  11225. */
  11226. SmartArrayNoDuplicate.prototype.push = function (value) {
  11227. _super.prototype.push.call(this, value);
  11228. if (!value.__smartArrayFlags) {
  11229. value.__smartArrayFlags = {};
  11230. }
  11231. value.__smartArrayFlags[this._id] = this._duplicateId;
  11232. };
  11233. /**
  11234. * Pushes a value at the end of the active data.
  11235. * If the data is already present, it won t be added again
  11236. * @param value defines the object to push in the array.
  11237. * @returns true if added false if it was already present
  11238. */
  11239. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11240. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11241. return false;
  11242. }
  11243. this.push(value);
  11244. return true;
  11245. };
  11246. /**
  11247. * Resets the active data to an empty array.
  11248. */
  11249. SmartArrayNoDuplicate.prototype.reset = function () {
  11250. _super.prototype.reset.call(this);
  11251. this._duplicateId++;
  11252. };
  11253. /**
  11254. * Concats the active data with a given array.
  11255. * This ensures no dupplicate will be present in the result.
  11256. * @param array defines the data to concatenate with.
  11257. */
  11258. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11259. if (array.length === 0) {
  11260. return;
  11261. }
  11262. if (this.length + array.length > this.data.length) {
  11263. this.data.length = (this.length + array.length) * 2;
  11264. }
  11265. for (var index = 0; index < array.length; index++) {
  11266. var item = (array.data || array)[index];
  11267. this.pushNoDuplicate(item);
  11268. }
  11269. };
  11270. return SmartArrayNoDuplicate;
  11271. }(SmartArray));
  11272. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11273. })(BABYLON || (BABYLON = {}));
  11274. //# sourceMappingURL=babylon.smartArray.js.map
  11275. var BABYLON;
  11276. (function (BABYLON) {
  11277. var PromiseStates;
  11278. (function (PromiseStates) {
  11279. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11280. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11281. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11282. })(PromiseStates || (PromiseStates = {}));
  11283. var FulFillmentAgregator = /** @class */ (function () {
  11284. function FulFillmentAgregator() {
  11285. this.count = 0;
  11286. this.target = 0;
  11287. this.results = [];
  11288. }
  11289. return FulFillmentAgregator;
  11290. }());
  11291. var InternalPromise = /** @class */ (function () {
  11292. function InternalPromise(resolver) {
  11293. var _this = this;
  11294. this._state = PromiseStates.Pending;
  11295. this._children = new Array();
  11296. this._rejectWasConsumed = false;
  11297. if (!resolver) {
  11298. return;
  11299. }
  11300. try {
  11301. resolver(function (value) {
  11302. _this._resolve(value);
  11303. }, function (reason) {
  11304. _this._reject(reason);
  11305. });
  11306. }
  11307. catch (e) {
  11308. this._reject(e);
  11309. }
  11310. }
  11311. Object.defineProperty(InternalPromise.prototype, "_result", {
  11312. get: function () {
  11313. return this._resultValue;
  11314. },
  11315. set: function (value) {
  11316. this._resultValue = value;
  11317. if (this._parent && this._parent._result === undefined) {
  11318. this._parent._result = value;
  11319. }
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. InternalPromise.prototype.catch = function (onRejected) {
  11325. return this.then(undefined, onRejected);
  11326. };
  11327. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11328. var _this = this;
  11329. var newPromise = new InternalPromise();
  11330. newPromise._onFulfilled = onFulfilled;
  11331. newPromise._onRejected = onRejected;
  11332. // Composition
  11333. this._children.push(newPromise);
  11334. newPromise._parent = this;
  11335. if (this._state !== PromiseStates.Pending) {
  11336. BABYLON.Tools.SetImmediate(function () {
  11337. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11338. var returnedValue = newPromise._resolve(_this._result);
  11339. if (returnedValue !== undefined && returnedValue !== null) {
  11340. if (returnedValue._state !== undefined) {
  11341. var returnedPromise = returnedValue;
  11342. newPromise._children.push(returnedPromise);
  11343. returnedPromise._parent = newPromise;
  11344. newPromise = returnedPromise;
  11345. }
  11346. else {
  11347. newPromise._result = returnedValue;
  11348. }
  11349. }
  11350. }
  11351. else {
  11352. newPromise._reject(_this._reason);
  11353. }
  11354. });
  11355. }
  11356. return newPromise;
  11357. };
  11358. InternalPromise.prototype._moveChildren = function (children) {
  11359. var _this = this;
  11360. var _a;
  11361. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11362. this._children.forEach(function (child) {
  11363. child._parent = _this;
  11364. });
  11365. if (this._state === PromiseStates.Fulfilled) {
  11366. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11367. var child = _b[_i];
  11368. child._resolve(this._result);
  11369. }
  11370. }
  11371. else if (this._state === PromiseStates.Rejected) {
  11372. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11373. var child = _d[_c];
  11374. child._reject(this._reason);
  11375. }
  11376. }
  11377. };
  11378. InternalPromise.prototype._resolve = function (value) {
  11379. try {
  11380. this._state = PromiseStates.Fulfilled;
  11381. var returnedValue = null;
  11382. if (this._onFulfilled) {
  11383. returnedValue = this._onFulfilled(value);
  11384. }
  11385. if (returnedValue !== undefined && returnedValue !== null) {
  11386. if (returnedValue._state !== undefined) {
  11387. // Transmit children
  11388. var returnedPromise = returnedValue;
  11389. returnedPromise._parent = this;
  11390. returnedPromise._moveChildren(this._children);
  11391. value = returnedPromise._result;
  11392. }
  11393. else {
  11394. value = returnedValue;
  11395. }
  11396. }
  11397. this._result = value;
  11398. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11399. var child = _a[_i];
  11400. child._resolve(value);
  11401. }
  11402. this._children.length = 0;
  11403. delete this._onFulfilled;
  11404. delete this._onRejected;
  11405. }
  11406. catch (e) {
  11407. this._reject(e, true);
  11408. }
  11409. };
  11410. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11411. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11412. this._state = PromiseStates.Rejected;
  11413. this._reason = reason;
  11414. if (this._onRejected && !onLocalThrow) {
  11415. try {
  11416. this._onRejected(reason);
  11417. this._rejectWasConsumed = true;
  11418. }
  11419. catch (e) {
  11420. reason = e;
  11421. }
  11422. }
  11423. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11424. var child = _a[_i];
  11425. if (this._rejectWasConsumed) {
  11426. child._resolve(null);
  11427. }
  11428. else {
  11429. child._reject(reason);
  11430. }
  11431. }
  11432. this._children.length = 0;
  11433. delete this._onFulfilled;
  11434. delete this._onRejected;
  11435. };
  11436. InternalPromise.resolve = function (value) {
  11437. var newPromise = new InternalPromise();
  11438. newPromise._resolve(value);
  11439. return newPromise;
  11440. };
  11441. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11442. promise.then(function (value) {
  11443. agregator.results[index] = value;
  11444. agregator.count++;
  11445. if (agregator.count === agregator.target) {
  11446. agregator.rootPromise._resolve(agregator.results);
  11447. }
  11448. return null;
  11449. }, function (reason) {
  11450. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11451. agregator.rootPromise._reject(reason);
  11452. }
  11453. });
  11454. };
  11455. InternalPromise.all = function (promises) {
  11456. var newPromise = new InternalPromise();
  11457. var agregator = new FulFillmentAgregator();
  11458. agregator.target = promises.length;
  11459. agregator.rootPromise = newPromise;
  11460. if (promises.length) {
  11461. for (var index = 0; index < promises.length; index++) {
  11462. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11463. }
  11464. }
  11465. else {
  11466. newPromise._resolve([]);
  11467. }
  11468. return newPromise;
  11469. };
  11470. InternalPromise.race = function (promises) {
  11471. var newPromise = new InternalPromise();
  11472. if (promises.length) {
  11473. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11474. var promise = promises_1[_i];
  11475. promise.then(function (value) {
  11476. if (newPromise) {
  11477. newPromise._resolve(value);
  11478. newPromise = null;
  11479. }
  11480. return null;
  11481. }, function (reason) {
  11482. if (newPromise) {
  11483. newPromise._reject(reason);
  11484. newPromise = null;
  11485. }
  11486. });
  11487. }
  11488. }
  11489. return newPromise;
  11490. };
  11491. return InternalPromise;
  11492. }());
  11493. /**
  11494. * Helper class that provides a small promise polyfill
  11495. */
  11496. var PromisePolyfill = /** @class */ (function () {
  11497. function PromisePolyfill() {
  11498. }
  11499. /**
  11500. * Static function used to check if the polyfill is required
  11501. * If this is the case then the function will inject the polyfill to window.Promise
  11502. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11503. */
  11504. PromisePolyfill.Apply = function (force) {
  11505. if (force === void 0) { force = false; }
  11506. if (force || typeof Promise === 'undefined') {
  11507. var root = window;
  11508. root.Promise = InternalPromise;
  11509. }
  11510. };
  11511. return PromisePolyfill;
  11512. }());
  11513. BABYLON.PromisePolyfill = PromisePolyfill;
  11514. })(BABYLON || (BABYLON = {}));
  11515. //# sourceMappingURL=babylon.promise.js.map
  11516. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11517. var BABYLON;
  11518. (function (BABYLON) {
  11519. /**
  11520. * Helper class to push actions to a pool of workers.
  11521. */
  11522. var WorkerPool = /** @class */ (function () {
  11523. /**
  11524. * Constructor
  11525. * @param workers Array of workers to use for actions
  11526. */
  11527. function WorkerPool(workers) {
  11528. this._pendingActions = new Array();
  11529. this._workerInfos = workers.map(function (worker) { return ({
  11530. worker: worker,
  11531. active: false
  11532. }); });
  11533. }
  11534. /**
  11535. * Terminates all workers and clears any pending actions.
  11536. */
  11537. WorkerPool.prototype.dispose = function () {
  11538. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11539. var workerInfo = _a[_i];
  11540. workerInfo.worker.terminate();
  11541. }
  11542. delete this._workerInfos;
  11543. delete this._pendingActions;
  11544. };
  11545. /**
  11546. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11547. * pended until a worker has completed its action.
  11548. * @param action The action to perform. Call onComplete when the action is complete.
  11549. */
  11550. WorkerPool.prototype.push = function (action) {
  11551. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11552. var workerInfo = _a[_i];
  11553. if (!workerInfo.active) {
  11554. this._execute(workerInfo, action);
  11555. return;
  11556. }
  11557. }
  11558. this._pendingActions.push(action);
  11559. };
  11560. WorkerPool.prototype._execute = function (workerInfo, action) {
  11561. var _this = this;
  11562. workerInfo.active = true;
  11563. action(workerInfo.worker, function () {
  11564. workerInfo.active = false;
  11565. var nextAction = _this._pendingActions.shift();
  11566. if (nextAction) {
  11567. _this._execute(workerInfo, nextAction);
  11568. }
  11569. });
  11570. };
  11571. return WorkerPool;
  11572. }());
  11573. BABYLON.WorkerPool = WorkerPool;
  11574. })(BABYLON || (BABYLON = {}));
  11575. //# sourceMappingURL=babylon.workerPool.js.map
  11576. var BABYLON;
  11577. (function (BABYLON) {
  11578. /**
  11579. * @hidden
  11580. **/
  11581. var _AlphaState = /** @class */ (function () {
  11582. /**
  11583. * Initializes the state.
  11584. */
  11585. function _AlphaState() {
  11586. this._isAlphaBlendDirty = false;
  11587. this._isBlendFunctionParametersDirty = false;
  11588. this._isBlendEquationParametersDirty = false;
  11589. this._isBlendConstantsDirty = false;
  11590. this._alphaBlend = false;
  11591. this._blendFunctionParameters = new Array(4);
  11592. this._blendEquationParameters = new Array(2);
  11593. this._blendConstants = new Array(4);
  11594. this.reset();
  11595. }
  11596. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11597. get: function () {
  11598. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11604. get: function () {
  11605. return this._alphaBlend;
  11606. },
  11607. set: function (value) {
  11608. if (this._alphaBlend === value) {
  11609. return;
  11610. }
  11611. this._alphaBlend = value;
  11612. this._isAlphaBlendDirty = true;
  11613. },
  11614. enumerable: true,
  11615. configurable: true
  11616. });
  11617. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11618. if (this._blendConstants[0] === r &&
  11619. this._blendConstants[1] === g &&
  11620. this._blendConstants[2] === b &&
  11621. this._blendConstants[3] === a) {
  11622. return;
  11623. }
  11624. this._blendConstants[0] = r;
  11625. this._blendConstants[1] = g;
  11626. this._blendConstants[2] = b;
  11627. this._blendConstants[3] = a;
  11628. this._isBlendConstantsDirty = true;
  11629. };
  11630. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11631. if (this._blendFunctionParameters[0] === value0 &&
  11632. this._blendFunctionParameters[1] === value1 &&
  11633. this._blendFunctionParameters[2] === value2 &&
  11634. this._blendFunctionParameters[3] === value3) {
  11635. return;
  11636. }
  11637. this._blendFunctionParameters[0] = value0;
  11638. this._blendFunctionParameters[1] = value1;
  11639. this._blendFunctionParameters[2] = value2;
  11640. this._blendFunctionParameters[3] = value3;
  11641. this._isBlendFunctionParametersDirty = true;
  11642. };
  11643. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11644. if (this._blendEquationParameters[0] === rgb &&
  11645. this._blendEquationParameters[1] === alpha) {
  11646. return;
  11647. }
  11648. this._blendEquationParameters[0] = rgb;
  11649. this._blendEquationParameters[1] = alpha;
  11650. this._isBlendEquationParametersDirty = true;
  11651. };
  11652. _AlphaState.prototype.reset = function () {
  11653. this._alphaBlend = false;
  11654. this._blendFunctionParameters[0] = null;
  11655. this._blendFunctionParameters[1] = null;
  11656. this._blendFunctionParameters[2] = null;
  11657. this._blendFunctionParameters[3] = null;
  11658. this._blendEquationParameters[0] = null;
  11659. this._blendEquationParameters[1] = null;
  11660. this._blendConstants[0] = null;
  11661. this._blendConstants[1] = null;
  11662. this._blendConstants[2] = null;
  11663. this._blendConstants[3] = null;
  11664. this._isAlphaBlendDirty = true;
  11665. this._isBlendFunctionParametersDirty = false;
  11666. this._isBlendEquationParametersDirty = false;
  11667. this._isBlendConstantsDirty = false;
  11668. };
  11669. _AlphaState.prototype.apply = function (gl) {
  11670. if (!this.isDirty) {
  11671. return;
  11672. }
  11673. // Alpha blend
  11674. if (this._isAlphaBlendDirty) {
  11675. if (this._alphaBlend) {
  11676. gl.enable(gl.BLEND);
  11677. }
  11678. else {
  11679. gl.disable(gl.BLEND);
  11680. }
  11681. this._isAlphaBlendDirty = false;
  11682. }
  11683. // Alpha function
  11684. if (this._isBlendFunctionParametersDirty) {
  11685. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11686. this._isBlendFunctionParametersDirty = false;
  11687. }
  11688. // Alpha equation
  11689. if (this._isBlendEquationParametersDirty) {
  11690. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11691. this._isBlendEquationParametersDirty = false;
  11692. }
  11693. // Constants
  11694. if (this._isBlendConstantsDirty) {
  11695. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11696. this._isBlendConstantsDirty = false;
  11697. }
  11698. };
  11699. return _AlphaState;
  11700. }());
  11701. BABYLON._AlphaState = _AlphaState;
  11702. })(BABYLON || (BABYLON = {}));
  11703. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11704. var BABYLON;
  11705. (function (BABYLON) {
  11706. /**
  11707. * @hidden
  11708. **/
  11709. var _DepthCullingState = /** @class */ (function () {
  11710. /**
  11711. * Initializes the state.
  11712. */
  11713. function _DepthCullingState() {
  11714. this._isDepthTestDirty = false;
  11715. this._isDepthMaskDirty = false;
  11716. this._isDepthFuncDirty = false;
  11717. this._isCullFaceDirty = false;
  11718. this._isCullDirty = false;
  11719. this._isZOffsetDirty = false;
  11720. this._isFrontFaceDirty = false;
  11721. this.reset();
  11722. }
  11723. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11724. get: function () {
  11725. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11731. get: function () {
  11732. return this._zOffset;
  11733. },
  11734. set: function (value) {
  11735. if (this._zOffset === value) {
  11736. return;
  11737. }
  11738. this._zOffset = value;
  11739. this._isZOffsetDirty = true;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11745. get: function () {
  11746. return this._cullFace;
  11747. },
  11748. set: function (value) {
  11749. if (this._cullFace === value) {
  11750. return;
  11751. }
  11752. this._cullFace = value;
  11753. this._isCullFaceDirty = true;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11759. get: function () {
  11760. return this._cull;
  11761. },
  11762. set: function (value) {
  11763. if (this._cull === value) {
  11764. return;
  11765. }
  11766. this._cull = value;
  11767. this._isCullDirty = true;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11773. get: function () {
  11774. return this._depthFunc;
  11775. },
  11776. set: function (value) {
  11777. if (this._depthFunc === value) {
  11778. return;
  11779. }
  11780. this._depthFunc = value;
  11781. this._isDepthFuncDirty = true;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11787. get: function () {
  11788. return this._depthMask;
  11789. },
  11790. set: function (value) {
  11791. if (this._depthMask === value) {
  11792. return;
  11793. }
  11794. this._depthMask = value;
  11795. this._isDepthMaskDirty = true;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11801. get: function () {
  11802. return this._depthTest;
  11803. },
  11804. set: function (value) {
  11805. if (this._depthTest === value) {
  11806. return;
  11807. }
  11808. this._depthTest = value;
  11809. this._isDepthTestDirty = true;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11815. get: function () {
  11816. return this._frontFace;
  11817. },
  11818. set: function (value) {
  11819. if (this._frontFace === value) {
  11820. return;
  11821. }
  11822. this._frontFace = value;
  11823. this._isFrontFaceDirty = true;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. _DepthCullingState.prototype.reset = function () {
  11829. this._depthMask = true;
  11830. this._depthTest = true;
  11831. this._depthFunc = null;
  11832. this._cullFace = null;
  11833. this._cull = null;
  11834. this._zOffset = 0;
  11835. this._frontFace = null;
  11836. this._isDepthTestDirty = true;
  11837. this._isDepthMaskDirty = true;
  11838. this._isDepthFuncDirty = false;
  11839. this._isCullFaceDirty = false;
  11840. this._isCullDirty = false;
  11841. this._isZOffsetDirty = false;
  11842. this._isFrontFaceDirty = false;
  11843. };
  11844. _DepthCullingState.prototype.apply = function (gl) {
  11845. if (!this.isDirty) {
  11846. return;
  11847. }
  11848. // Cull
  11849. if (this._isCullDirty) {
  11850. if (this.cull) {
  11851. gl.enable(gl.CULL_FACE);
  11852. }
  11853. else {
  11854. gl.disable(gl.CULL_FACE);
  11855. }
  11856. this._isCullDirty = false;
  11857. }
  11858. // Cull face
  11859. if (this._isCullFaceDirty) {
  11860. gl.cullFace(this.cullFace);
  11861. this._isCullFaceDirty = false;
  11862. }
  11863. // Depth mask
  11864. if (this._isDepthMaskDirty) {
  11865. gl.depthMask(this.depthMask);
  11866. this._isDepthMaskDirty = false;
  11867. }
  11868. // Depth test
  11869. if (this._isDepthTestDirty) {
  11870. if (this.depthTest) {
  11871. gl.enable(gl.DEPTH_TEST);
  11872. }
  11873. else {
  11874. gl.disable(gl.DEPTH_TEST);
  11875. }
  11876. this._isDepthTestDirty = false;
  11877. }
  11878. // Depth func
  11879. if (this._isDepthFuncDirty) {
  11880. gl.depthFunc(this.depthFunc);
  11881. this._isDepthFuncDirty = false;
  11882. }
  11883. // zOffset
  11884. if (this._isZOffsetDirty) {
  11885. if (this.zOffset) {
  11886. gl.enable(gl.POLYGON_OFFSET_FILL);
  11887. gl.polygonOffset(this.zOffset, 0);
  11888. }
  11889. else {
  11890. gl.disable(gl.POLYGON_OFFSET_FILL);
  11891. }
  11892. this._isZOffsetDirty = false;
  11893. }
  11894. // Front face
  11895. if (this._isFrontFaceDirty) {
  11896. gl.frontFace(this.frontFace);
  11897. this._isFrontFaceDirty = false;
  11898. }
  11899. };
  11900. return _DepthCullingState;
  11901. }());
  11902. BABYLON._DepthCullingState = _DepthCullingState;
  11903. })(BABYLON || (BABYLON = {}));
  11904. //# sourceMappingURL=babylon.depthCullingState.js.map
  11905. var BABYLON;
  11906. (function (BABYLON) {
  11907. /**
  11908. * @hidden
  11909. **/
  11910. var _StencilState = /** @class */ (function () {
  11911. function _StencilState() {
  11912. this._isStencilTestDirty = false;
  11913. this._isStencilMaskDirty = false;
  11914. this._isStencilFuncDirty = false;
  11915. this._isStencilOpDirty = false;
  11916. this.reset();
  11917. }
  11918. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11919. get: function () {
  11920. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11926. get: function () {
  11927. return this._stencilFunc;
  11928. },
  11929. set: function (value) {
  11930. if (this._stencilFunc === value) {
  11931. return;
  11932. }
  11933. this._stencilFunc = value;
  11934. this._isStencilFuncDirty = true;
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11940. get: function () {
  11941. return this._stencilFuncRef;
  11942. },
  11943. set: function (value) {
  11944. if (this._stencilFuncRef === value) {
  11945. return;
  11946. }
  11947. this._stencilFuncRef = value;
  11948. this._isStencilFuncDirty = true;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11954. get: function () {
  11955. return this._stencilFuncMask;
  11956. },
  11957. set: function (value) {
  11958. if (this._stencilFuncMask === value) {
  11959. return;
  11960. }
  11961. this._stencilFuncMask = value;
  11962. this._isStencilFuncDirty = true;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11968. get: function () {
  11969. return this._stencilOpStencilFail;
  11970. },
  11971. set: function (value) {
  11972. if (this._stencilOpStencilFail === value) {
  11973. return;
  11974. }
  11975. this._stencilOpStencilFail = value;
  11976. this._isStencilOpDirty = true;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11982. get: function () {
  11983. return this._stencilOpDepthFail;
  11984. },
  11985. set: function (value) {
  11986. if (this._stencilOpDepthFail === value) {
  11987. return;
  11988. }
  11989. this._stencilOpDepthFail = value;
  11990. this._isStencilOpDirty = true;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11996. get: function () {
  11997. return this._stencilOpStencilDepthPass;
  11998. },
  11999. set: function (value) {
  12000. if (this._stencilOpStencilDepthPass === value) {
  12001. return;
  12002. }
  12003. this._stencilOpStencilDepthPass = value;
  12004. this._isStencilOpDirty = true;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  12010. get: function () {
  12011. return this._stencilMask;
  12012. },
  12013. set: function (value) {
  12014. if (this._stencilMask === value) {
  12015. return;
  12016. }
  12017. this._stencilMask = value;
  12018. this._isStencilMaskDirty = true;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12024. get: function () {
  12025. return this._stencilTest;
  12026. },
  12027. set: function (value) {
  12028. if (this._stencilTest === value) {
  12029. return;
  12030. }
  12031. this._stencilTest = value;
  12032. this._isStencilTestDirty = true;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. _StencilState.prototype.reset = function () {
  12038. this._stencilTest = false;
  12039. this._stencilMask = 0xFF;
  12040. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12041. this._stencilFuncRef = 1;
  12042. this._stencilFuncMask = 0xFF;
  12043. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12044. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12045. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12046. this._isStencilTestDirty = true;
  12047. this._isStencilMaskDirty = true;
  12048. this._isStencilFuncDirty = true;
  12049. this._isStencilOpDirty = true;
  12050. };
  12051. _StencilState.prototype.apply = function (gl) {
  12052. if (!this.isDirty) {
  12053. return;
  12054. }
  12055. // Stencil test
  12056. if (this._isStencilTestDirty) {
  12057. if (this.stencilTest) {
  12058. gl.enable(gl.STENCIL_TEST);
  12059. }
  12060. else {
  12061. gl.disable(gl.STENCIL_TEST);
  12062. }
  12063. this._isStencilTestDirty = false;
  12064. }
  12065. // Stencil mask
  12066. if (this._isStencilMaskDirty) {
  12067. gl.stencilMask(this.stencilMask);
  12068. this._isStencilMaskDirty = false;
  12069. }
  12070. // Stencil func
  12071. if (this._isStencilFuncDirty) {
  12072. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12073. this._isStencilFuncDirty = false;
  12074. }
  12075. // Stencil op
  12076. if (this._isStencilOpDirty) {
  12077. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12078. this._isStencilOpDirty = false;
  12079. }
  12080. };
  12081. return _StencilState;
  12082. }());
  12083. BABYLON._StencilState = _StencilState;
  12084. })(BABYLON || (BABYLON = {}));
  12085. //# sourceMappingURL=babylon.stencilState.js.map
  12086. var __assign = (this && this.__assign) || function () {
  12087. __assign = Object.assign || function(t) {
  12088. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12089. s = arguments[i];
  12090. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12091. t[p] = s[p];
  12092. }
  12093. return t;
  12094. };
  12095. return __assign.apply(this, arguments);
  12096. };
  12097. var BABYLON;
  12098. (function (BABYLON) {
  12099. /**
  12100. * Keeps track of all the buffer info used in engine.
  12101. */
  12102. var BufferPointer = /** @class */ (function () {
  12103. function BufferPointer() {
  12104. }
  12105. return BufferPointer;
  12106. }());
  12107. /**
  12108. * Interface for attribute information associated with buffer instanciation
  12109. */
  12110. var InstancingAttributeInfo = /** @class */ (function () {
  12111. function InstancingAttributeInfo() {
  12112. }
  12113. return InstancingAttributeInfo;
  12114. }());
  12115. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12116. /**
  12117. * Define options used to create a render target texture
  12118. */
  12119. var RenderTargetCreationOptions = /** @class */ (function () {
  12120. function RenderTargetCreationOptions() {
  12121. }
  12122. return RenderTargetCreationOptions;
  12123. }());
  12124. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12125. /**
  12126. * Define options used to create a depth texture
  12127. */
  12128. var DepthTextureCreationOptions = /** @class */ (function () {
  12129. function DepthTextureCreationOptions() {
  12130. }
  12131. return DepthTextureCreationOptions;
  12132. }());
  12133. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12134. /**
  12135. * Class used to describe the capabilities of the engine relatively to the current browser
  12136. */
  12137. var EngineCapabilities = /** @class */ (function () {
  12138. function EngineCapabilities() {
  12139. }
  12140. return EngineCapabilities;
  12141. }());
  12142. BABYLON.EngineCapabilities = EngineCapabilities;
  12143. /**
  12144. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12145. */
  12146. var Engine = /** @class */ (function () {
  12147. /**
  12148. * Creates a new engine
  12149. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  12150. * @param antialias defines enable antialiasing (default: false)
  12151. * @param options defines further options to be sent to the getContext() function
  12152. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12153. */
  12154. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12155. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12156. var _this = this;
  12157. // Public members
  12158. /**
  12159. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12160. */
  12161. this.forcePOTTextures = false;
  12162. /**
  12163. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12164. */
  12165. this.isFullscreen = false;
  12166. /**
  12167. * Gets a boolean indicating if the pointer is currently locked
  12168. */
  12169. this.isPointerLock = false;
  12170. /**
  12171. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12172. */
  12173. this.cullBackFaces = true;
  12174. /**
  12175. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12176. */
  12177. this.renderEvenInBackground = true;
  12178. /**
  12179. * Gets or sets a boolean indicating that cache can be kept between frames
  12180. */
  12181. this.preventCacheWipeBetweenFrames = false;
  12182. /**
  12183. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12184. **/
  12185. this.enableOfflineSupport = false;
  12186. /**
  12187. * 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)
  12188. **/
  12189. this.disableManifestCheck = false;
  12190. /**
  12191. * Gets the list of created scenes
  12192. */
  12193. this.scenes = new Array();
  12194. /**
  12195. * Gets the list of created postprocesses
  12196. */
  12197. this.postProcesses = new Array();
  12198. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12199. this.validateShaderPrograms = false;
  12200. // Observables
  12201. /**
  12202. * Observable event triggered each time the rendering canvas is resized
  12203. */
  12204. this.onResizeObservable = new BABYLON.Observable();
  12205. /**
  12206. * Observable event triggered each time the canvas loses focus
  12207. */
  12208. this.onCanvasBlurObservable = new BABYLON.Observable();
  12209. /**
  12210. * Observable event triggered each time the canvas gains focus
  12211. */
  12212. this.onCanvasFocusObservable = new BABYLON.Observable();
  12213. /**
  12214. * Observable event triggered each time the canvas receives pointerout event
  12215. */
  12216. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12217. /**
  12218. * Observable event triggered before each texture is initialized
  12219. */
  12220. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12221. //WebVR
  12222. this._vrDisplay = undefined;
  12223. this._vrSupported = false;
  12224. this._vrExclusivePointerMode = false;
  12225. // Uniform buffers list
  12226. /**
  12227. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12228. */
  12229. this.disableUniformBuffers = false;
  12230. /** @hidden */
  12231. this._uniformBuffers = new Array();
  12232. // Observables
  12233. /**
  12234. * Observable raised when the engine begins a new frame
  12235. */
  12236. this.onBeginFrameObservable = new BABYLON.Observable();
  12237. /**
  12238. * If set, will be used to request the next animation frame for the render loop
  12239. */
  12240. this.customAnimationFrameRequester = null;
  12241. /**
  12242. * Observable raised when the engine ends the current frame
  12243. */
  12244. this.onEndFrameObservable = new BABYLON.Observable();
  12245. /**
  12246. * Observable raised when the engine is about to compile a shader
  12247. */
  12248. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12249. /**
  12250. * Observable raised when the engine has jsut compiled a shader
  12251. */
  12252. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12253. this._windowIsBackground = false;
  12254. this._webGLVersion = 1.0;
  12255. /** @hidden */
  12256. this._badOS = false;
  12257. /** @hidden */
  12258. this._badDesktopOS = false;
  12259. /**
  12260. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12261. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12262. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12263. */
  12264. this.disableTextureBindingOptimization = false;
  12265. /**
  12266. * Observable signaled when VR display mode changes
  12267. */
  12268. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12269. /**
  12270. * Observable signaled when VR request present is complete
  12271. */
  12272. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12273. /**
  12274. * Observable signaled when VR request present starts
  12275. */
  12276. this.onVRRequestPresentStart = new BABYLON.Observable();
  12277. this._colorWrite = true;
  12278. /** @hidden */
  12279. this._drawCalls = new BABYLON.PerfCounter();
  12280. /** @hidden */
  12281. this._textureCollisions = new BABYLON.PerfCounter();
  12282. this._renderingQueueLaunched = false;
  12283. this._activeRenderLoops = new Array();
  12284. // Deterministic lockstepMaxSteps
  12285. this._deterministicLockstep = false;
  12286. this._lockstepMaxSteps = 4;
  12287. // Lost context
  12288. /**
  12289. * Observable signaled when a context lost event is raised
  12290. */
  12291. this.onContextLostObservable = new BABYLON.Observable();
  12292. /**
  12293. * Observable signaled when a context restored event is raised
  12294. */
  12295. this.onContextRestoredObservable = new BABYLON.Observable();
  12296. this._contextWasLost = false;
  12297. this._doNotHandleContextLost = false;
  12298. // FPS
  12299. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12300. this._fps = 60;
  12301. this._deltaTime = 0;
  12302. /**
  12303. * Turn this value on if you want to pause FPS computation when in background
  12304. */
  12305. this.disablePerformanceMonitorInBackground = false;
  12306. // States
  12307. /** @hidden */
  12308. this._depthCullingState = new BABYLON._DepthCullingState();
  12309. /** @hidden */
  12310. this._stencilState = new BABYLON._StencilState();
  12311. /** @hidden */
  12312. this._alphaState = new BABYLON._AlphaState();
  12313. /** @hidden */
  12314. this._alphaMode = Engine.ALPHA_DISABLE;
  12315. // Cache
  12316. this._internalTexturesCache = new Array();
  12317. /** @hidden */
  12318. this._activeChannel = 0;
  12319. this._currentTextureChannel = -1;
  12320. /** @hidden */
  12321. this._boundTexturesCache = {};
  12322. this._compiledEffects = {};
  12323. this._vertexAttribArraysEnabled = [];
  12324. this._uintIndicesCurrentlySet = false;
  12325. this._currentBoundBuffer = new Array();
  12326. /** @hidden */
  12327. this._currentFramebuffer = null;
  12328. this._currentBufferPointers = new Array();
  12329. this._currentInstanceLocations = new Array();
  12330. this._currentInstanceBuffers = new Array();
  12331. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12332. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12333. this._vaoRecordInProgress = false;
  12334. this._mustWipeVertexAttributes = false;
  12335. this._nextFreeTextureSlots = new Array();
  12336. this._maxSimultaneousTextures = 0;
  12337. this._activeRequests = new Array();
  12338. // Hardware supported Compressed Textures
  12339. this._texturesSupported = new Array();
  12340. /**
  12341. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12342. */
  12343. this.premultipliedAlpha = true;
  12344. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12345. this._onVRFullScreenTriggered = function () {
  12346. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12347. //get the old size before we change
  12348. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12349. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12350. //get the width and height, change the render size
  12351. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12352. _this.setHardwareScalingLevel(1);
  12353. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12354. }
  12355. else {
  12356. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12357. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12358. }
  12359. };
  12360. this._unpackFlipYCached = null;
  12361. /**
  12362. * In case you are sharing the context with other applications, it might
  12363. * be interested to not cache the unpack flip y state to ensure a consistent
  12364. * value would be set.
  12365. */
  12366. this.enableUnpackFlipYCached = true;
  12367. this._boundUniforms = {};
  12368. // Register promises
  12369. BABYLON.PromisePolyfill.Apply();
  12370. var canvas = null;
  12371. Engine.Instances.push(this);
  12372. if (!canvasOrContext) {
  12373. return;
  12374. }
  12375. options = options || {};
  12376. if (canvasOrContext.getContext) {
  12377. canvas = canvasOrContext;
  12378. this._renderingCanvas = canvas;
  12379. if (antialias != null) {
  12380. options.antialias = antialias;
  12381. }
  12382. if (options.deterministicLockstep === undefined) {
  12383. options.deterministicLockstep = false;
  12384. }
  12385. if (options.lockstepMaxSteps === undefined) {
  12386. options.lockstepMaxSteps = 4;
  12387. }
  12388. if (options.preserveDrawingBuffer === undefined) {
  12389. options.preserveDrawingBuffer = false;
  12390. }
  12391. if (options.audioEngine === undefined) {
  12392. options.audioEngine = true;
  12393. }
  12394. if (options.stencil === undefined) {
  12395. options.stencil = true;
  12396. }
  12397. if (options.premultipliedAlpha === false) {
  12398. this.premultipliedAlpha = false;
  12399. }
  12400. this._deterministicLockstep = options.deterministicLockstep;
  12401. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12402. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12403. // Exceptions
  12404. if (navigator && navigator.userAgent) {
  12405. var ua = navigator.userAgent;
  12406. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12407. var exception = _a[_i];
  12408. var key = exception.key;
  12409. var targets = exception.targets;
  12410. if (ua.indexOf(key) > -1) {
  12411. if (exception.capture && exception.captureConstraint) {
  12412. var capture = exception.capture;
  12413. var constraint = exception.captureConstraint;
  12414. var regex = new RegExp(capture);
  12415. var matches = regex.exec(ua);
  12416. if (matches && matches.length > 0) {
  12417. var capturedValue = parseInt(matches[matches.length - 1]);
  12418. if (capturedValue >= constraint) {
  12419. continue;
  12420. }
  12421. }
  12422. }
  12423. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12424. var target = targets_1[_b];
  12425. switch (target) {
  12426. case "uniformBuffer":
  12427. this.disableUniformBuffers = true;
  12428. break;
  12429. case "textureBindingOptimization":
  12430. this.disableTextureBindingOptimization = true;
  12431. break;
  12432. }
  12433. }
  12434. }
  12435. }
  12436. }
  12437. // GL
  12438. if (!options.disableWebGL2Support) {
  12439. try {
  12440. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12441. if (this._gl) {
  12442. this._webGLVersion = 2.0;
  12443. // Prevent weird browsers to lie :-)
  12444. if (!this._gl.deleteQuery) {
  12445. this._webGLVersion = 1.0;
  12446. }
  12447. }
  12448. }
  12449. catch (e) {
  12450. // Do nothing
  12451. }
  12452. }
  12453. if (!this._gl) {
  12454. if (!canvas) {
  12455. throw new Error("The provided canvas is null or undefined.");
  12456. }
  12457. try {
  12458. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12459. }
  12460. catch (e) {
  12461. throw new Error("WebGL not supported");
  12462. }
  12463. }
  12464. if (!this._gl) {
  12465. throw new Error("WebGL not supported");
  12466. }
  12467. this._onCanvasFocus = function () {
  12468. _this.onCanvasFocusObservable.notifyObservers(_this);
  12469. };
  12470. this._onCanvasBlur = function () {
  12471. _this.onCanvasBlurObservable.notifyObservers(_this);
  12472. };
  12473. canvas.addEventListener("focus", this._onCanvasFocus);
  12474. canvas.addEventListener("blur", this._onCanvasBlur);
  12475. this._onBlur = function () {
  12476. if (_this.disablePerformanceMonitorInBackground) {
  12477. _this._performanceMonitor.disable();
  12478. }
  12479. _this._windowIsBackground = true;
  12480. };
  12481. this._onFocus = function () {
  12482. if (_this.disablePerformanceMonitorInBackground) {
  12483. _this._performanceMonitor.enable();
  12484. }
  12485. _this._windowIsBackground = false;
  12486. };
  12487. this._onCanvasPointerOut = function (ev) {
  12488. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12489. };
  12490. window.addEventListener("blur", this._onBlur);
  12491. window.addEventListener("focus", this._onFocus);
  12492. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12493. // Context lost
  12494. if (!this._doNotHandleContextLost) {
  12495. this._onContextLost = function (evt) {
  12496. evt.preventDefault();
  12497. _this._contextWasLost = true;
  12498. BABYLON.Tools.Warn("WebGL context lost.");
  12499. _this.onContextLostObservable.notifyObservers(_this);
  12500. };
  12501. this._onContextRestored = function (evt) {
  12502. // Adding a timeout to avoid race condition at browser level
  12503. setTimeout(function () {
  12504. // Rebuild gl context
  12505. _this._initGLContext();
  12506. // Rebuild effects
  12507. _this._rebuildEffects();
  12508. // Rebuild textures
  12509. _this._rebuildInternalTextures();
  12510. // Rebuild buffers
  12511. _this._rebuildBuffers();
  12512. // Cache
  12513. _this.wipeCaches(true);
  12514. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12515. _this.onContextRestoredObservable.notifyObservers(_this);
  12516. _this._contextWasLost = false;
  12517. }, 0);
  12518. };
  12519. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12520. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12521. }
  12522. }
  12523. else {
  12524. this._gl = canvasOrContext;
  12525. this._renderingCanvas = this._gl.canvas;
  12526. if (this._gl.renderbufferStorageMultisample) {
  12527. this._webGLVersion = 2.0;
  12528. }
  12529. var attributes = this._gl.getContextAttributes();
  12530. if (attributes) {
  12531. options.stencil = attributes.stencil;
  12532. }
  12533. }
  12534. // Viewport
  12535. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12536. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12537. this.resize();
  12538. this._isStencilEnable = options.stencil ? true : false;
  12539. this._initGLContext();
  12540. if (canvas) {
  12541. // Fullscreen
  12542. this._onFullscreenChange = function () {
  12543. if (document.fullscreen !== undefined) {
  12544. _this.isFullscreen = document.fullscreen;
  12545. }
  12546. else if (document.mozFullScreen !== undefined) {
  12547. _this.isFullscreen = document.mozFullScreen;
  12548. }
  12549. else if (document.webkitIsFullScreen !== undefined) {
  12550. _this.isFullscreen = document.webkitIsFullScreen;
  12551. }
  12552. else if (document.msIsFullScreen !== undefined) {
  12553. _this.isFullscreen = document.msIsFullScreen;
  12554. }
  12555. // Pointer lock
  12556. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12557. canvas.requestPointerLock = canvas.requestPointerLock ||
  12558. canvas.msRequestPointerLock ||
  12559. canvas.mozRequestPointerLock ||
  12560. canvas.webkitRequestPointerLock;
  12561. if (canvas.requestPointerLock) {
  12562. canvas.requestPointerLock();
  12563. }
  12564. }
  12565. };
  12566. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12567. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12568. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12569. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12570. // Pointer lock
  12571. this._onPointerLockChange = function () {
  12572. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12573. document.webkitPointerLockElement === canvas ||
  12574. document.msPointerLockElement === canvas ||
  12575. document.pointerLockElement === canvas);
  12576. };
  12577. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12578. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12579. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12580. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12581. this._onVRDisplayPointerRestricted = function () {
  12582. if (canvas) {
  12583. canvas.requestPointerLock();
  12584. }
  12585. };
  12586. this._onVRDisplayPointerUnrestricted = function () {
  12587. document.exitPointerLock();
  12588. };
  12589. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12590. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12591. }
  12592. // Create Audio Engine if needed.
  12593. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12594. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12595. }
  12596. // Prepare buffer pointers
  12597. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12598. this._currentBufferPointers[i] = new BufferPointer();
  12599. }
  12600. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12601. // Load WebVR Devices
  12602. if (options.autoEnableWebVR) {
  12603. this.initWebVR();
  12604. }
  12605. // Detect if we are running on a faulty buggy OS.
  12606. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12607. // Detect if we are running on a faulty buggy desktop OS.
  12608. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12609. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12610. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12611. }
  12612. Object.defineProperty(Engine, "LastCreatedEngine", {
  12613. /**
  12614. * Gets the latest created engine
  12615. */
  12616. get: function () {
  12617. if (Engine.Instances.length === 0) {
  12618. return null;
  12619. }
  12620. return Engine.Instances[Engine.Instances.length - 1];
  12621. },
  12622. enumerable: true,
  12623. configurable: true
  12624. });
  12625. Object.defineProperty(Engine, "LastCreatedScene", {
  12626. /**
  12627. * Gets the latest created scene
  12628. */
  12629. get: function () {
  12630. var lastCreatedEngine = Engine.LastCreatedEngine;
  12631. if (!lastCreatedEngine) {
  12632. return null;
  12633. }
  12634. if (lastCreatedEngine.scenes.length === 0) {
  12635. return null;
  12636. }
  12637. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12638. },
  12639. enumerable: true,
  12640. configurable: true
  12641. });
  12642. /**
  12643. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12644. * @param flag defines which part of the materials must be marked as dirty
  12645. * @param predicate defines a predicate used to filter which materials should be affected
  12646. */
  12647. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12648. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12649. var engine = Engine.Instances[engineIndex];
  12650. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12651. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12652. }
  12653. }
  12654. };
  12655. Object.defineProperty(Engine, "Version", {
  12656. /**
  12657. * Returns the current version of the framework
  12658. */
  12659. get: function () {
  12660. return "4.0.0-alpha.4";
  12661. },
  12662. enumerable: true,
  12663. configurable: true
  12664. });
  12665. Object.defineProperty(Engine.prototype, "description", {
  12666. /**
  12667. * Returns a string describing the current engine
  12668. */
  12669. get: function () {
  12670. var description = "WebGL" + this.webGLVersion;
  12671. if (this._caps.parallelShaderCompile) {
  12672. description += " - Parallel shader compilation";
  12673. }
  12674. return description;
  12675. },
  12676. enumerable: true,
  12677. configurable: true
  12678. });
  12679. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12680. /**
  12681. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12682. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12683. */
  12684. get: function () {
  12685. return this._vrExclusivePointerMode;
  12686. },
  12687. enumerable: true,
  12688. configurable: true
  12689. });
  12690. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12691. /**
  12692. * Gets a boolean indicating that the engine supports uniform buffers
  12693. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12694. */
  12695. get: function () {
  12696. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12697. },
  12698. enumerable: true,
  12699. configurable: true
  12700. });
  12701. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12702. /**
  12703. * Gets a boolean indicating that only power of 2 textures are supported
  12704. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12705. */
  12706. get: function () {
  12707. return this._webGLVersion < 2 || this.forcePOTTextures;
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12713. /**
  12714. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12715. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12716. */
  12717. get: function () {
  12718. return this._doNotHandleContextLost;
  12719. },
  12720. set: function (value) {
  12721. this._doNotHandleContextLost = value;
  12722. },
  12723. enumerable: true,
  12724. configurable: true
  12725. });
  12726. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12727. /**
  12728. * Gets the performance monitor attached to this engine
  12729. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12730. */
  12731. get: function () {
  12732. return this._performanceMonitor;
  12733. },
  12734. enumerable: true,
  12735. configurable: true
  12736. });
  12737. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12738. /**
  12739. * Gets the list of texture formats supported
  12740. */
  12741. get: function () {
  12742. return this._texturesSupported;
  12743. },
  12744. enumerable: true,
  12745. configurable: true
  12746. });
  12747. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12748. /**
  12749. * Gets the list of texture formats in use
  12750. */
  12751. get: function () {
  12752. return this._textureFormatInUse;
  12753. },
  12754. enumerable: true,
  12755. configurable: true
  12756. });
  12757. Object.defineProperty(Engine.prototype, "currentViewport", {
  12758. /**
  12759. * Gets the current viewport
  12760. */
  12761. get: function () {
  12762. return this._cachedViewport;
  12763. },
  12764. enumerable: true,
  12765. configurable: true
  12766. });
  12767. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12768. /**
  12769. * Gets the default empty texture
  12770. */
  12771. get: function () {
  12772. if (!this._emptyTexture) {
  12773. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12774. }
  12775. return this._emptyTexture;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12781. /**
  12782. * Gets the default empty 3D texture
  12783. */
  12784. get: function () {
  12785. if (!this._emptyTexture3D) {
  12786. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12787. }
  12788. return this._emptyTexture3D;
  12789. },
  12790. enumerable: true,
  12791. configurable: true
  12792. });
  12793. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12794. /**
  12795. * Gets the default empty cube texture
  12796. */
  12797. get: function () {
  12798. if (!this._emptyCubeTexture) {
  12799. var faceData = new Uint8Array(4);
  12800. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12801. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12802. }
  12803. return this._emptyCubeTexture;
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. Engine.prototype._rebuildInternalTextures = function () {
  12809. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12810. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12811. var internalTexture = currentState_1[_i];
  12812. internalTexture._rebuild();
  12813. }
  12814. };
  12815. Engine.prototype._rebuildEffects = function () {
  12816. for (var key in this._compiledEffects) {
  12817. var effect = this._compiledEffects[key];
  12818. effect._prepareEffect();
  12819. }
  12820. BABYLON.Effect.ResetCache();
  12821. };
  12822. /**
  12823. * Gets a boolean indicating if all created effects are ready
  12824. * @returns true if all effects are ready
  12825. */
  12826. Engine.prototype.areAllEffectsReady = function () {
  12827. for (var key in this._compiledEffects) {
  12828. var effect = this._compiledEffects[key];
  12829. if (!effect.isReady()) {
  12830. return false;
  12831. }
  12832. }
  12833. return true;
  12834. };
  12835. Engine.prototype._rebuildBuffers = function () {
  12836. // Index / Vertex
  12837. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12838. var scene = _a[_i];
  12839. scene.resetCachedMaterial();
  12840. scene._rebuildGeometries();
  12841. scene._rebuildTextures();
  12842. }
  12843. // Uniforms
  12844. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12845. var uniformBuffer = _c[_b];
  12846. uniformBuffer._rebuild();
  12847. }
  12848. };
  12849. Engine.prototype._initGLContext = function () {
  12850. // Caps
  12851. this._caps = new EngineCapabilities();
  12852. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12853. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12854. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12855. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12856. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12857. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12858. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12859. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12860. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12861. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12862. // Infos
  12863. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12864. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12865. if (rendererInfo != null) {
  12866. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12867. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12868. }
  12869. if (!this._glVendor) {
  12870. this._glVendor = "Unknown vendor";
  12871. }
  12872. if (!this._glRenderer) {
  12873. this._glRenderer = "Unknown renderer";
  12874. }
  12875. // Constants
  12876. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12877. if (this._gl.RGBA16F !== 0x881A) {
  12878. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12879. }
  12880. if (this._gl.RGBA32F !== 0x8814) {
  12881. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12882. }
  12883. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12884. this._gl.DEPTH24_STENCIL8 = 35056;
  12885. }
  12886. // Extensions
  12887. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12888. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12889. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12890. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12891. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12892. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12893. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12894. 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');
  12895. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12896. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12897. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12898. this._caps.highPrecisionShaderSupported = false;
  12899. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12900. if (this._caps.timerQuery) {
  12901. if (this._webGLVersion === 1) {
  12902. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12903. }
  12904. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12905. }
  12906. // Checks if some of the format renders first to allow the use of webgl inspector.
  12907. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12908. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12909. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12910. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12911. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12912. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12913. if (this._webGLVersion > 1) {
  12914. this._gl.HALF_FLOAT_OES = 0x140B;
  12915. }
  12916. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12917. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12918. // Draw buffers
  12919. if (this._webGLVersion > 1) {
  12920. this._caps.drawBuffersExtension = true;
  12921. }
  12922. else {
  12923. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12924. if (drawBuffersExtension !== null) {
  12925. this._caps.drawBuffersExtension = true;
  12926. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12927. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12928. for (var i = 0; i < 16; i++) {
  12929. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12930. }
  12931. }
  12932. else {
  12933. this._caps.drawBuffersExtension = false;
  12934. }
  12935. }
  12936. // Shader compiler threads
  12937. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  12938. if (this._caps.parallelShaderCompile) {
  12939. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  12940. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  12941. }
  12942. // Depth Texture
  12943. if (this._webGLVersion > 1) {
  12944. this._caps.depthTextureExtension = true;
  12945. }
  12946. else {
  12947. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12948. if (depthTextureExtension != null) {
  12949. this._caps.depthTextureExtension = true;
  12950. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12951. }
  12952. }
  12953. // Vertex array object
  12954. if (this._webGLVersion > 1) {
  12955. this._caps.vertexArrayObject = true;
  12956. }
  12957. else {
  12958. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12959. if (vertexArrayObjectExtension != null) {
  12960. this._caps.vertexArrayObject = true;
  12961. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12962. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12963. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12964. }
  12965. else {
  12966. this._caps.vertexArrayObject = false;
  12967. }
  12968. }
  12969. // Instances count
  12970. if (this._webGLVersion > 1) {
  12971. this._caps.instancedArrays = true;
  12972. }
  12973. else {
  12974. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12975. if (instanceExtension != null) {
  12976. this._caps.instancedArrays = true;
  12977. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12978. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12979. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12980. }
  12981. else {
  12982. this._caps.instancedArrays = false;
  12983. }
  12984. }
  12985. // Intelligently add supported compressed formats in order to check for.
  12986. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12987. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12988. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12989. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12990. if (this._caps.astc) {
  12991. this.texturesSupported.push('-astc.ktx');
  12992. }
  12993. if (this._caps.s3tc) {
  12994. this.texturesSupported.push('-dxt.ktx');
  12995. }
  12996. if (this._caps.pvrtc) {
  12997. this.texturesSupported.push('-pvrtc.ktx');
  12998. }
  12999. if (this._caps.etc2) {
  13000. this.texturesSupported.push('-etc2.ktx');
  13001. }
  13002. if (this._caps.etc1) {
  13003. this.texturesSupported.push('-etc1.ktx');
  13004. }
  13005. if (this._gl.getShaderPrecisionFormat) {
  13006. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  13007. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  13008. if (vertex_highp && fragment_highp) {
  13009. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  13010. }
  13011. }
  13012. // Depth buffer
  13013. this.setDepthBuffer(true);
  13014. this.setDepthFunctionToLessOrEqual();
  13015. this.setDepthWrite(true);
  13016. // Texture maps
  13017. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  13018. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13019. this._nextFreeTextureSlots.push(slot);
  13020. }
  13021. };
  13022. Object.defineProperty(Engine.prototype, "webGLVersion", {
  13023. /**
  13024. * Gets version of the current webGL context
  13025. */
  13026. get: function () {
  13027. return this._webGLVersion;
  13028. },
  13029. enumerable: true,
  13030. configurable: true
  13031. });
  13032. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  13033. /**
  13034. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  13035. */
  13036. get: function () {
  13037. return this._isStencilEnable;
  13038. },
  13039. enumerable: true,
  13040. configurable: true
  13041. });
  13042. Engine.prototype._prepareWorkingCanvas = function () {
  13043. if (this._workingCanvas) {
  13044. return;
  13045. }
  13046. this._workingCanvas = document.createElement("canvas");
  13047. var context = this._workingCanvas.getContext("2d");
  13048. if (context) {
  13049. this._workingContext = context;
  13050. }
  13051. };
  13052. /**
  13053. * Reset the texture cache to empty state
  13054. */
  13055. Engine.prototype.resetTextureCache = function () {
  13056. for (var key in this._boundTexturesCache) {
  13057. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13058. continue;
  13059. }
  13060. var boundTexture = this._boundTexturesCache[key];
  13061. if (boundTexture) {
  13062. this._removeDesignatedSlot(boundTexture);
  13063. }
  13064. this._boundTexturesCache[key] = null;
  13065. }
  13066. if (!this.disableTextureBindingOptimization) {
  13067. this._nextFreeTextureSlots = [];
  13068. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13069. this._nextFreeTextureSlots.push(slot);
  13070. }
  13071. }
  13072. this._currentTextureChannel = -1;
  13073. };
  13074. /**
  13075. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13076. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13077. * @returns true if engine is in deterministic lock step mode
  13078. */
  13079. Engine.prototype.isDeterministicLockStep = function () {
  13080. return this._deterministicLockstep;
  13081. };
  13082. /**
  13083. * Gets the max steps when engine is running in deterministic lock step
  13084. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13085. * @returns the max steps
  13086. */
  13087. Engine.prototype.getLockstepMaxSteps = function () {
  13088. return this._lockstepMaxSteps;
  13089. };
  13090. /**
  13091. * Gets an object containing information about the current webGL context
  13092. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13093. */
  13094. Engine.prototype.getGlInfo = function () {
  13095. return {
  13096. vendor: this._glVendor,
  13097. renderer: this._glRenderer,
  13098. version: this._glVersion
  13099. };
  13100. };
  13101. /**
  13102. * Gets current aspect ratio
  13103. * @param camera defines the camera to use to get the aspect ratio
  13104. * @param useScreen defines if screen size must be used (or the current render target if any)
  13105. * @returns a number defining the aspect ratio
  13106. */
  13107. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13108. if (useScreen === void 0) { useScreen = false; }
  13109. var viewport = camera.viewport;
  13110. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13111. };
  13112. /**
  13113. * Gets current screen aspect ratio
  13114. * @returns a number defining the aspect ratio
  13115. */
  13116. Engine.prototype.getScreenAspectRatio = function () {
  13117. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13118. };
  13119. /**
  13120. * Gets the current render width
  13121. * @param useScreen defines if screen size must be used (or the current render target if any)
  13122. * @returns a number defining the current render width
  13123. */
  13124. Engine.prototype.getRenderWidth = function (useScreen) {
  13125. if (useScreen === void 0) { useScreen = false; }
  13126. if (!useScreen && this._currentRenderTarget) {
  13127. return this._currentRenderTarget.width;
  13128. }
  13129. return this._gl.drawingBufferWidth;
  13130. };
  13131. /**
  13132. * Gets the current render height
  13133. * @param useScreen defines if screen size must be used (or the current render target if any)
  13134. * @returns a number defining the current render height
  13135. */
  13136. Engine.prototype.getRenderHeight = function (useScreen) {
  13137. if (useScreen === void 0) { useScreen = false; }
  13138. if (!useScreen && this._currentRenderTarget) {
  13139. return this._currentRenderTarget.height;
  13140. }
  13141. return this._gl.drawingBufferHeight;
  13142. };
  13143. /**
  13144. * Gets the HTML canvas attached with the current webGL context
  13145. * @returns a HTML canvas
  13146. */
  13147. Engine.prototype.getRenderingCanvas = function () {
  13148. return this._renderingCanvas;
  13149. };
  13150. /**
  13151. * Gets the client rect of the HTML canvas attached with the current webGL context
  13152. * @returns a client rectanglee
  13153. */
  13154. Engine.prototype.getRenderingCanvasClientRect = function () {
  13155. if (!this._renderingCanvas) {
  13156. return null;
  13157. }
  13158. return this._renderingCanvas.getBoundingClientRect();
  13159. };
  13160. /**
  13161. * Defines the hardware scaling level.
  13162. * By default the hardware scaling level is computed from the window device ratio.
  13163. * 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.
  13164. * @param level defines the level to use
  13165. */
  13166. Engine.prototype.setHardwareScalingLevel = function (level) {
  13167. this._hardwareScalingLevel = level;
  13168. this.resize();
  13169. };
  13170. /**
  13171. * Gets the current hardware scaling level.
  13172. * By default the hardware scaling level is computed from the window device ratio.
  13173. * 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.
  13174. * @returns a number indicating the current hardware scaling level
  13175. */
  13176. Engine.prototype.getHardwareScalingLevel = function () {
  13177. return this._hardwareScalingLevel;
  13178. };
  13179. /**
  13180. * Gets the list of loaded textures
  13181. * @returns an array containing all loaded textures
  13182. */
  13183. Engine.prototype.getLoadedTexturesCache = function () {
  13184. return this._internalTexturesCache;
  13185. };
  13186. /**
  13187. * Gets the object containing all engine capabilities
  13188. * @returns the EngineCapabilities object
  13189. */
  13190. Engine.prototype.getCaps = function () {
  13191. return this._caps;
  13192. };
  13193. /**
  13194. * Gets the current depth function
  13195. * @returns a number defining the depth function
  13196. */
  13197. Engine.prototype.getDepthFunction = function () {
  13198. return this._depthCullingState.depthFunc;
  13199. };
  13200. /**
  13201. * Sets the current depth function
  13202. * @param depthFunc defines the function to use
  13203. */
  13204. Engine.prototype.setDepthFunction = function (depthFunc) {
  13205. this._depthCullingState.depthFunc = depthFunc;
  13206. };
  13207. /**
  13208. * Sets the current depth function to GREATER
  13209. */
  13210. Engine.prototype.setDepthFunctionToGreater = function () {
  13211. this._depthCullingState.depthFunc = this._gl.GREATER;
  13212. };
  13213. /**
  13214. * Sets the current depth function to GEQUAL
  13215. */
  13216. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13217. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13218. };
  13219. /**
  13220. * Sets the current depth function to LESS
  13221. */
  13222. Engine.prototype.setDepthFunctionToLess = function () {
  13223. this._depthCullingState.depthFunc = this._gl.LESS;
  13224. };
  13225. /**
  13226. * Sets the current depth function to LEQUAL
  13227. */
  13228. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13229. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13230. };
  13231. /**
  13232. * Gets a boolean indicating if stencil buffer is enabled
  13233. * @returns the current stencil buffer state
  13234. */
  13235. Engine.prototype.getStencilBuffer = function () {
  13236. return this._stencilState.stencilTest;
  13237. };
  13238. /**
  13239. * Enable or disable the stencil buffer
  13240. * @param enable defines if the stencil buffer must be enabled or disabled
  13241. */
  13242. Engine.prototype.setStencilBuffer = function (enable) {
  13243. this._stencilState.stencilTest = enable;
  13244. };
  13245. /**
  13246. * Gets the current stencil mask
  13247. * @returns a number defining the new stencil mask to use
  13248. */
  13249. Engine.prototype.getStencilMask = function () {
  13250. return this._stencilState.stencilMask;
  13251. };
  13252. /**
  13253. * Sets the current stencil mask
  13254. * @param mask defines the new stencil mask to use
  13255. */
  13256. Engine.prototype.setStencilMask = function (mask) {
  13257. this._stencilState.stencilMask = mask;
  13258. };
  13259. /**
  13260. * Gets the current stencil function
  13261. * @returns a number defining the stencil function to use
  13262. */
  13263. Engine.prototype.getStencilFunction = function () {
  13264. return this._stencilState.stencilFunc;
  13265. };
  13266. /**
  13267. * Gets the current stencil reference value
  13268. * @returns a number defining the stencil reference value to use
  13269. */
  13270. Engine.prototype.getStencilFunctionReference = function () {
  13271. return this._stencilState.stencilFuncRef;
  13272. };
  13273. /**
  13274. * Gets the current stencil mask
  13275. * @returns a number defining the stencil mask to use
  13276. */
  13277. Engine.prototype.getStencilFunctionMask = function () {
  13278. return this._stencilState.stencilFuncMask;
  13279. };
  13280. /**
  13281. * Sets the current stencil function
  13282. * @param stencilFunc defines the new stencil function to use
  13283. */
  13284. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13285. this._stencilState.stencilFunc = stencilFunc;
  13286. };
  13287. /**
  13288. * Sets the current stencil reference
  13289. * @param reference defines the new stencil reference to use
  13290. */
  13291. Engine.prototype.setStencilFunctionReference = function (reference) {
  13292. this._stencilState.stencilFuncRef = reference;
  13293. };
  13294. /**
  13295. * Sets the current stencil mask
  13296. * @param mask defines the new stencil mask to use
  13297. */
  13298. Engine.prototype.setStencilFunctionMask = function (mask) {
  13299. this._stencilState.stencilFuncMask = mask;
  13300. };
  13301. /**
  13302. * Gets the current stencil operation when stencil fails
  13303. * @returns a number defining stencil operation to use when stencil fails
  13304. */
  13305. Engine.prototype.getStencilOperationFail = function () {
  13306. return this._stencilState.stencilOpStencilFail;
  13307. };
  13308. /**
  13309. * Gets the current stencil operation when depth fails
  13310. * @returns a number defining stencil operation to use when depth fails
  13311. */
  13312. Engine.prototype.getStencilOperationDepthFail = function () {
  13313. return this._stencilState.stencilOpDepthFail;
  13314. };
  13315. /**
  13316. * Gets the current stencil operation when stencil passes
  13317. * @returns a number defining stencil operation to use when stencil passes
  13318. */
  13319. Engine.prototype.getStencilOperationPass = function () {
  13320. return this._stencilState.stencilOpStencilDepthPass;
  13321. };
  13322. /**
  13323. * Sets the stencil operation to use when stencil fails
  13324. * @param operation defines the stencil operation to use when stencil fails
  13325. */
  13326. Engine.prototype.setStencilOperationFail = function (operation) {
  13327. this._stencilState.stencilOpStencilFail = operation;
  13328. };
  13329. /**
  13330. * Sets the stencil operation to use when depth fails
  13331. * @param operation defines the stencil operation to use when depth fails
  13332. */
  13333. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13334. this._stencilState.stencilOpDepthFail = operation;
  13335. };
  13336. /**
  13337. * Sets the stencil operation to use when stencil passes
  13338. * @param operation defines the stencil operation to use when stencil passes
  13339. */
  13340. Engine.prototype.setStencilOperationPass = function (operation) {
  13341. this._stencilState.stencilOpStencilDepthPass = operation;
  13342. };
  13343. /**
  13344. * Sets a boolean indicating if the dithering state is enabled or disabled
  13345. * @param value defines the dithering state
  13346. */
  13347. Engine.prototype.setDitheringState = function (value) {
  13348. if (value) {
  13349. this._gl.enable(this._gl.DITHER);
  13350. }
  13351. else {
  13352. this._gl.disable(this._gl.DITHER);
  13353. }
  13354. };
  13355. /**
  13356. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13357. * @param value defines the rasterizer state
  13358. */
  13359. Engine.prototype.setRasterizerState = function (value) {
  13360. if (value) {
  13361. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13362. }
  13363. else {
  13364. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13365. }
  13366. };
  13367. /**
  13368. * stop executing a render loop function and remove it from the execution array
  13369. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13370. */
  13371. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13372. if (!renderFunction) {
  13373. this._activeRenderLoops = [];
  13374. return;
  13375. }
  13376. var index = this._activeRenderLoops.indexOf(renderFunction);
  13377. if (index >= 0) {
  13378. this._activeRenderLoops.splice(index, 1);
  13379. }
  13380. };
  13381. /** @hidden */
  13382. Engine.prototype._renderLoop = function () {
  13383. if (!this._contextWasLost) {
  13384. var shouldRender = true;
  13385. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13386. shouldRender = false;
  13387. }
  13388. if (shouldRender) {
  13389. // Start new frame
  13390. this.beginFrame();
  13391. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13392. var renderFunction = this._activeRenderLoops[index];
  13393. renderFunction();
  13394. }
  13395. // Present
  13396. this.endFrame();
  13397. }
  13398. }
  13399. if (this._activeRenderLoops.length > 0) {
  13400. // Register new frame
  13401. if (this.customAnimationFrameRequester) {
  13402. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13403. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13404. }
  13405. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13406. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13407. }
  13408. else {
  13409. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13410. }
  13411. }
  13412. else {
  13413. this._renderingQueueLaunched = false;
  13414. }
  13415. };
  13416. /**
  13417. * Register and execute a render loop. The engine can have more than one render function
  13418. * @param renderFunction defines the function to continuously execute
  13419. */
  13420. Engine.prototype.runRenderLoop = function (renderFunction) {
  13421. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13422. return;
  13423. }
  13424. this._activeRenderLoops.push(renderFunction);
  13425. if (!this._renderingQueueLaunched) {
  13426. this._renderingQueueLaunched = true;
  13427. this._bindedRenderFunction = this._renderLoop.bind(this);
  13428. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13429. }
  13430. };
  13431. /**
  13432. * Toggle full screen mode
  13433. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13434. */
  13435. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13436. if (this.isFullscreen) {
  13437. BABYLON.Tools.ExitFullscreen();
  13438. }
  13439. else {
  13440. this._pointerLockRequested = requestPointerLock;
  13441. if (this._renderingCanvas) {
  13442. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13443. }
  13444. }
  13445. };
  13446. /**
  13447. * Clear the current render buffer or the current render target (if any is set up)
  13448. * @param color defines the color to use
  13449. * @param backBuffer defines if the back buffer must be cleared
  13450. * @param depth defines if the depth buffer must be cleared
  13451. * @param stencil defines if the stencil buffer must be cleared
  13452. */
  13453. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13454. if (stencil === void 0) { stencil = false; }
  13455. this.applyStates();
  13456. var mode = 0;
  13457. if (backBuffer && color) {
  13458. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13459. mode |= this._gl.COLOR_BUFFER_BIT;
  13460. }
  13461. if (depth) {
  13462. this._gl.clearDepth(1.0);
  13463. mode |= this._gl.DEPTH_BUFFER_BIT;
  13464. }
  13465. if (stencil) {
  13466. this._gl.clearStencil(0);
  13467. mode |= this._gl.STENCIL_BUFFER_BIT;
  13468. }
  13469. this._gl.clear(mode);
  13470. };
  13471. /**
  13472. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13473. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13474. * @param y defines the y-coordinate of the corner of the clear rectangle
  13475. * @param width defines the width of the clear rectangle
  13476. * @param height defines the height of the clear rectangle
  13477. * @param clearColor defines the clear color
  13478. */
  13479. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13480. var gl = this._gl;
  13481. // Save state
  13482. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13483. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13484. // Change state
  13485. gl.enable(gl.SCISSOR_TEST);
  13486. gl.scissor(x, y, width, height);
  13487. // Clear
  13488. this.clear(clearColor, true, true, true);
  13489. // Restore state
  13490. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13491. if (curScissor === true) {
  13492. gl.enable(gl.SCISSOR_TEST);
  13493. }
  13494. else {
  13495. gl.disable(gl.SCISSOR_TEST);
  13496. }
  13497. };
  13498. /** @hidden */
  13499. Engine.prototype._viewport = function (x, y, width, height) {
  13500. if (x !== this._viewportCached.x ||
  13501. y !== this._viewportCached.y ||
  13502. width !== this._viewportCached.z ||
  13503. height !== this._viewportCached.w) {
  13504. this._viewportCached.x = x;
  13505. this._viewportCached.y = y;
  13506. this._viewportCached.z = width;
  13507. this._viewportCached.w = height;
  13508. this._gl.viewport(x, y, width, height);
  13509. }
  13510. };
  13511. /**
  13512. * Set the WebGL's viewport
  13513. * @param viewport defines the viewport element to be used
  13514. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13515. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13516. */
  13517. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13518. var width = requiredWidth || this.getRenderWidth();
  13519. var height = requiredHeight || this.getRenderHeight();
  13520. var x = viewport.x || 0;
  13521. var y = viewport.y || 0;
  13522. this._cachedViewport = viewport;
  13523. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13524. };
  13525. /**
  13526. * Directly set the WebGL Viewport
  13527. * @param x defines the x coordinate of the viewport (in screen space)
  13528. * @param y defines the y coordinate of the viewport (in screen space)
  13529. * @param width defines the width of the viewport (in screen space)
  13530. * @param height defines the height of the viewport (in screen space)
  13531. * @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
  13532. */
  13533. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13534. var currentViewport = this._cachedViewport;
  13535. this._cachedViewport = null;
  13536. this._viewport(x, y, width, height);
  13537. return currentViewport;
  13538. };
  13539. /**
  13540. * Begin a new frame
  13541. */
  13542. Engine.prototype.beginFrame = function () {
  13543. this.onBeginFrameObservable.notifyObservers(this);
  13544. this._measureFps();
  13545. };
  13546. /**
  13547. * Enf the current frame
  13548. */
  13549. Engine.prototype.endFrame = function () {
  13550. // Force a flush in case we are using a bad OS.
  13551. if (this._badOS) {
  13552. this.flushFramebuffer();
  13553. }
  13554. // Submit frame to the vr device, if enabled
  13555. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13556. // TODO: We should only submit the frame if we read frameData successfully.
  13557. this._vrDisplay.submitFrame();
  13558. }
  13559. this.onEndFrameObservable.notifyObservers(this);
  13560. };
  13561. /**
  13562. * Resize the view according to the canvas' size
  13563. */
  13564. Engine.prototype.resize = function () {
  13565. // We're not resizing the size of the canvas while in VR mode & presenting
  13566. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13567. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13568. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13569. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13570. }
  13571. };
  13572. /**
  13573. * Force a specific size of the canvas
  13574. * @param width defines the new canvas' width
  13575. * @param height defines the new canvas' height
  13576. */
  13577. Engine.prototype.setSize = function (width, height) {
  13578. if (!this._renderingCanvas) {
  13579. return;
  13580. }
  13581. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13582. return;
  13583. }
  13584. this._renderingCanvas.width = width;
  13585. this._renderingCanvas.height = height;
  13586. for (var index = 0; index < this.scenes.length; index++) {
  13587. var scene = this.scenes[index];
  13588. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13589. var cam = scene.cameras[camIndex];
  13590. cam._currentRenderId = 0;
  13591. }
  13592. }
  13593. if (this.onResizeObservable.hasObservers) {
  13594. this.onResizeObservable.notifyObservers(this);
  13595. }
  13596. };
  13597. // WebVR functions
  13598. /**
  13599. * Gets a boolean indicating if a webVR device was detected
  13600. * @returns true if a webVR device was detected
  13601. */
  13602. Engine.prototype.isVRDevicePresent = function () {
  13603. return !!this._vrDisplay;
  13604. };
  13605. /**
  13606. * Gets the current webVR device
  13607. * @returns the current webVR device (or null)
  13608. */
  13609. Engine.prototype.getVRDevice = function () {
  13610. return this._vrDisplay;
  13611. };
  13612. /**
  13613. * Initializes a webVR display and starts listening to display change events
  13614. * The onVRDisplayChangedObservable will be notified upon these changes
  13615. * @returns The onVRDisplayChangedObservable
  13616. */
  13617. Engine.prototype.initWebVR = function () {
  13618. this.initWebVRAsync();
  13619. return this.onVRDisplayChangedObservable;
  13620. };
  13621. /**
  13622. * Initializes a webVR display and starts listening to display change events
  13623. * The onVRDisplayChangedObservable will be notified upon these changes
  13624. * @returns A promise containing a VRDisplay and if vr is supported
  13625. */
  13626. Engine.prototype.initWebVRAsync = function () {
  13627. var _this = this;
  13628. var notifyObservers = function () {
  13629. var eventArgs = {
  13630. vrDisplay: _this._vrDisplay,
  13631. vrSupported: _this._vrSupported
  13632. };
  13633. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13634. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13635. };
  13636. if (!this._onVrDisplayConnect) {
  13637. this._onVrDisplayConnect = function (event) {
  13638. _this._vrDisplay = event.display;
  13639. notifyObservers();
  13640. };
  13641. this._onVrDisplayDisconnect = function () {
  13642. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13643. _this._vrDisplay = undefined;
  13644. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13645. notifyObservers();
  13646. };
  13647. this._onVrDisplayPresentChange = function () {
  13648. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13649. };
  13650. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13651. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13652. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13653. }
  13654. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13655. this._webVRInitPromise.then(notifyObservers);
  13656. return this._webVRInitPromise;
  13657. };
  13658. /**
  13659. * Call this function to switch to webVR mode
  13660. * Will do nothing if webVR is not supported or if there is no webVR device
  13661. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13662. */
  13663. Engine.prototype.enableVR = function () {
  13664. var _this = this;
  13665. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13666. var onResolved = function () {
  13667. _this.onVRRequestPresentComplete.notifyObservers(true);
  13668. _this._onVRFullScreenTriggered();
  13669. };
  13670. var onRejected = function () {
  13671. _this.onVRRequestPresentComplete.notifyObservers(false);
  13672. };
  13673. this.onVRRequestPresentStart.notifyObservers(this);
  13674. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13675. }
  13676. };
  13677. /**
  13678. * Call this function to leave webVR mode
  13679. * Will do nothing if webVR is not supported or if there is no webVR device
  13680. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13681. */
  13682. Engine.prototype.disableVR = function () {
  13683. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13684. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13685. }
  13686. };
  13687. Engine.prototype._getVRDisplaysAsync = function () {
  13688. var _this = this;
  13689. return new Promise(function (res, rej) {
  13690. if (navigator.getVRDisplays) {
  13691. navigator.getVRDisplays().then(function (devices) {
  13692. _this._vrSupported = true;
  13693. // note that devices may actually be an empty array. This is fine;
  13694. // we expect this._vrDisplay to be undefined in this case.
  13695. _this._vrDisplay = devices[0];
  13696. res({
  13697. vrDisplay: _this._vrDisplay,
  13698. vrSupported: _this._vrSupported
  13699. });
  13700. });
  13701. }
  13702. else {
  13703. _this._vrDisplay = undefined;
  13704. _this._vrSupported = false;
  13705. res({
  13706. vrDisplay: _this._vrDisplay,
  13707. vrSupported: _this._vrSupported
  13708. });
  13709. }
  13710. });
  13711. };
  13712. /**
  13713. * Binds the frame buffer to the specified texture.
  13714. * @param texture The texture to render to or null for the default canvas
  13715. * @param faceIndex The face of the texture to render to in case of cube texture
  13716. * @param requiredWidth The width of the target to render to
  13717. * @param requiredHeight The height of the target to render to
  13718. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13719. * @param depthStencilTexture The depth stencil texture to use to render
  13720. * @param lodLevel defines le lod level to bind to the frame buffer
  13721. */
  13722. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13723. if (lodLevel === void 0) { lodLevel = 0; }
  13724. if (this._currentRenderTarget) {
  13725. this.unBindFramebuffer(this._currentRenderTarget);
  13726. }
  13727. this._currentRenderTarget = texture;
  13728. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13729. var gl = this._gl;
  13730. if (texture.isCube) {
  13731. if (faceIndex === undefined) {
  13732. faceIndex = 0;
  13733. }
  13734. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13735. if (depthStencilTexture) {
  13736. if (depthStencilTexture._generateStencilBuffer) {
  13737. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13738. }
  13739. else {
  13740. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13741. }
  13742. }
  13743. }
  13744. if (this._cachedViewport && !forceFullscreenViewport) {
  13745. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13746. }
  13747. else {
  13748. if (!requiredWidth) {
  13749. requiredWidth = texture.width;
  13750. if (lodLevel) {
  13751. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13752. }
  13753. }
  13754. if (!requiredHeight) {
  13755. requiredHeight = texture.height;
  13756. if (lodLevel) {
  13757. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13758. }
  13759. }
  13760. this._viewport(0, 0, requiredWidth, requiredHeight);
  13761. }
  13762. this.wipeCaches();
  13763. };
  13764. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13765. if (this._currentFramebuffer !== framebuffer) {
  13766. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13767. this._currentFramebuffer = framebuffer;
  13768. }
  13769. };
  13770. /**
  13771. * Unbind the current render target texture from the webGL context
  13772. * @param texture defines the render target texture to unbind
  13773. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13774. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13775. */
  13776. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13777. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13778. this._currentRenderTarget = null;
  13779. // If MSAA, we need to bitblt back to main texture
  13780. var gl = this._gl;
  13781. if (texture._MSAAFramebuffer) {
  13782. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13783. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13784. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13785. }
  13786. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13787. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13788. gl.generateMipmap(gl.TEXTURE_2D);
  13789. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13790. }
  13791. if (onBeforeUnbind) {
  13792. if (texture._MSAAFramebuffer) {
  13793. // Bind the correct framebuffer
  13794. this.bindUnboundFramebuffer(texture._framebuffer);
  13795. }
  13796. onBeforeUnbind();
  13797. }
  13798. this.bindUnboundFramebuffer(null);
  13799. };
  13800. /**
  13801. * Unbind a list of render target textures from the webGL context
  13802. * This is used only when drawBuffer extension or webGL2 are active
  13803. * @param textures defines the render target textures to unbind
  13804. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13805. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13806. */
  13807. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13808. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13809. this._currentRenderTarget = null;
  13810. // If MSAA, we need to bitblt back to main texture
  13811. var gl = this._gl;
  13812. if (textures[0]._MSAAFramebuffer) {
  13813. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13814. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13815. var attachments = textures[0]._attachments;
  13816. if (!attachments) {
  13817. attachments = new Array(textures.length);
  13818. textures[0]._attachments = attachments;
  13819. }
  13820. for (var i = 0; i < textures.length; i++) {
  13821. var texture = textures[i];
  13822. for (var j = 0; j < attachments.length; j++) {
  13823. attachments[j] = gl.NONE;
  13824. }
  13825. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13826. gl.readBuffer(attachments[i]);
  13827. gl.drawBuffers(attachments);
  13828. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13829. }
  13830. for (var i = 0; i < attachments.length; i++) {
  13831. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13832. }
  13833. gl.drawBuffers(attachments);
  13834. }
  13835. for (var i = 0; i < textures.length; i++) {
  13836. var texture = textures[i];
  13837. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13838. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13839. gl.generateMipmap(gl.TEXTURE_2D);
  13840. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13841. }
  13842. }
  13843. if (onBeforeUnbind) {
  13844. if (textures[0]._MSAAFramebuffer) {
  13845. // Bind the correct framebuffer
  13846. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13847. }
  13848. onBeforeUnbind();
  13849. }
  13850. this.bindUnboundFramebuffer(null);
  13851. };
  13852. /**
  13853. * Force the mipmap generation for the given render target texture
  13854. * @param texture defines the render target texture to use
  13855. */
  13856. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13857. if (texture.generateMipMaps) {
  13858. var gl = this._gl;
  13859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13860. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13861. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13862. }
  13863. };
  13864. /**
  13865. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13866. */
  13867. Engine.prototype.flushFramebuffer = function () {
  13868. this._gl.flush();
  13869. };
  13870. /**
  13871. * Unbind the current render target and bind the default framebuffer
  13872. */
  13873. Engine.prototype.restoreDefaultFramebuffer = function () {
  13874. if (this._currentRenderTarget) {
  13875. this.unBindFramebuffer(this._currentRenderTarget);
  13876. }
  13877. else {
  13878. this.bindUnboundFramebuffer(null);
  13879. }
  13880. if (this._cachedViewport) {
  13881. this.setViewport(this._cachedViewport);
  13882. }
  13883. this.wipeCaches();
  13884. };
  13885. // UBOs
  13886. /**
  13887. * Create an uniform buffer
  13888. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13889. * @param elements defines the content of the uniform buffer
  13890. * @returns the webGL uniform buffer
  13891. */
  13892. Engine.prototype.createUniformBuffer = function (elements) {
  13893. var ubo = this._gl.createBuffer();
  13894. if (!ubo) {
  13895. throw new Error("Unable to create uniform buffer");
  13896. }
  13897. this.bindUniformBuffer(ubo);
  13898. if (elements instanceof Float32Array) {
  13899. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13900. }
  13901. else {
  13902. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13903. }
  13904. this.bindUniformBuffer(null);
  13905. ubo.references = 1;
  13906. return ubo;
  13907. };
  13908. /**
  13909. * Create a dynamic uniform buffer
  13910. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13911. * @param elements defines the content of the uniform buffer
  13912. * @returns the webGL uniform buffer
  13913. */
  13914. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13915. var ubo = this._gl.createBuffer();
  13916. if (!ubo) {
  13917. throw new Error("Unable to create dynamic uniform buffer");
  13918. }
  13919. this.bindUniformBuffer(ubo);
  13920. if (elements instanceof Float32Array) {
  13921. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13922. }
  13923. else {
  13924. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13925. }
  13926. this.bindUniformBuffer(null);
  13927. ubo.references = 1;
  13928. return ubo;
  13929. };
  13930. /**
  13931. * Update an existing uniform buffer
  13932. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13933. * @param uniformBuffer defines the target uniform buffer
  13934. * @param elements defines the content to update
  13935. * @param offset defines the offset in the uniform buffer where update should start
  13936. * @param count defines the size of the data to update
  13937. */
  13938. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13939. this.bindUniformBuffer(uniformBuffer);
  13940. if (offset === undefined) {
  13941. offset = 0;
  13942. }
  13943. if (count === undefined) {
  13944. if (elements instanceof Float32Array) {
  13945. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13946. }
  13947. else {
  13948. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13949. }
  13950. }
  13951. else {
  13952. if (elements instanceof Float32Array) {
  13953. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13954. }
  13955. else {
  13956. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13957. }
  13958. }
  13959. this.bindUniformBuffer(null);
  13960. };
  13961. // VBOs
  13962. Engine.prototype._resetVertexBufferBinding = function () {
  13963. this.bindArrayBuffer(null);
  13964. this._cachedVertexBuffers = null;
  13965. };
  13966. /**
  13967. * Creates a vertex buffer
  13968. * @param data the data for the vertex buffer
  13969. * @returns the new WebGL static buffer
  13970. */
  13971. Engine.prototype.createVertexBuffer = function (data) {
  13972. var vbo = this._gl.createBuffer();
  13973. if (!vbo) {
  13974. throw new Error("Unable to create vertex buffer");
  13975. }
  13976. this.bindArrayBuffer(vbo);
  13977. if (data instanceof Array) {
  13978. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13979. }
  13980. else {
  13981. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13982. }
  13983. this._resetVertexBufferBinding();
  13984. vbo.references = 1;
  13985. return vbo;
  13986. };
  13987. /**
  13988. * Creates a dynamic vertex buffer
  13989. * @param data the data for the dynamic vertex buffer
  13990. * @returns the new WebGL dynamic buffer
  13991. */
  13992. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13993. var vbo = this._gl.createBuffer();
  13994. if (!vbo) {
  13995. throw new Error("Unable to create dynamic vertex buffer");
  13996. }
  13997. this.bindArrayBuffer(vbo);
  13998. if (data instanceof Array) {
  13999. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  14000. }
  14001. else {
  14002. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  14003. }
  14004. this._resetVertexBufferBinding();
  14005. vbo.references = 1;
  14006. return vbo;
  14007. };
  14008. /**
  14009. * Update a dynamic index buffer
  14010. * @param indexBuffer defines the target index buffer
  14011. * @param indices defines the data to update
  14012. * @param offset defines the offset in the target index buffer where update should start
  14013. */
  14014. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  14015. if (offset === void 0) { offset = 0; }
  14016. // Force cache update
  14017. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  14018. this.bindIndexBuffer(indexBuffer);
  14019. var arrayBuffer;
  14020. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  14021. arrayBuffer = indices;
  14022. }
  14023. else {
  14024. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14025. }
  14026. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  14027. this._resetIndexBufferBinding();
  14028. };
  14029. /**
  14030. * Updates a dynamic vertex buffer.
  14031. * @param vertexBuffer the vertex buffer to update
  14032. * @param data the data used to update the vertex buffer
  14033. * @param byteOffset the byte offset of the data
  14034. * @param byteLength the byte length of the data
  14035. */
  14036. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14037. this.bindArrayBuffer(vertexBuffer);
  14038. if (byteOffset === undefined) {
  14039. byteOffset = 0;
  14040. }
  14041. if (byteLength === undefined) {
  14042. if (data instanceof Array) {
  14043. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14044. }
  14045. else {
  14046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14047. }
  14048. }
  14049. else {
  14050. if (data instanceof Array) {
  14051. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14052. }
  14053. else {
  14054. if (data instanceof ArrayBuffer) {
  14055. data = new Uint8Array(data, byteOffset, byteLength);
  14056. }
  14057. else {
  14058. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14059. }
  14060. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14061. }
  14062. }
  14063. this._resetVertexBufferBinding();
  14064. };
  14065. Engine.prototype._resetIndexBufferBinding = function () {
  14066. this.bindIndexBuffer(null);
  14067. this._cachedIndexBuffer = null;
  14068. };
  14069. /**
  14070. * Creates a new index buffer
  14071. * @param indices defines the content of the index buffer
  14072. * @param updatable defines if the index buffer must be updatable
  14073. * @returns a new webGL buffer
  14074. */
  14075. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14076. var vbo = this._gl.createBuffer();
  14077. if (!vbo) {
  14078. throw new Error("Unable to create index buffer");
  14079. }
  14080. this.bindIndexBuffer(vbo);
  14081. // Check for 32 bits indices
  14082. var arrayBuffer;
  14083. var need32Bits = false;
  14084. if (indices instanceof Uint16Array) {
  14085. arrayBuffer = indices;
  14086. }
  14087. else {
  14088. //check 32 bit support
  14089. if (this._caps.uintIndices) {
  14090. if (indices instanceof Uint32Array) {
  14091. arrayBuffer = indices;
  14092. need32Bits = true;
  14093. }
  14094. else {
  14095. //number[] or Int32Array, check if 32 bit is necessary
  14096. for (var index = 0; index < indices.length; index++) {
  14097. if (indices[index] > 65535) {
  14098. need32Bits = true;
  14099. break;
  14100. }
  14101. }
  14102. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14103. }
  14104. }
  14105. else {
  14106. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14107. arrayBuffer = new Uint16Array(indices);
  14108. }
  14109. }
  14110. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14111. this._resetIndexBufferBinding();
  14112. vbo.references = 1;
  14113. vbo.is32Bits = need32Bits;
  14114. return vbo;
  14115. };
  14116. /**
  14117. * Bind a webGL buffer to the webGL context
  14118. * @param buffer defines the buffer to bind
  14119. */
  14120. Engine.prototype.bindArrayBuffer = function (buffer) {
  14121. if (!this._vaoRecordInProgress) {
  14122. this._unbindVertexArrayObject();
  14123. }
  14124. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14125. };
  14126. /**
  14127. * Bind an uniform buffer to the current webGL context
  14128. * @param buffer defines the buffer to bind
  14129. */
  14130. Engine.prototype.bindUniformBuffer = function (buffer) {
  14131. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14132. };
  14133. /**
  14134. * Bind a buffer to the current webGL context at a given location
  14135. * @param buffer defines the buffer to bind
  14136. * @param location defines the index where to bind the buffer
  14137. */
  14138. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14139. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14140. };
  14141. /**
  14142. * Bind a specific block at a given index in a specific shader program
  14143. * @param shaderProgram defines the shader program
  14144. * @param blockName defines the block name
  14145. * @param index defines the index where to bind the block
  14146. */
  14147. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14148. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14149. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14150. };
  14151. Engine.prototype.bindIndexBuffer = function (buffer) {
  14152. if (!this._vaoRecordInProgress) {
  14153. this._unbindVertexArrayObject();
  14154. }
  14155. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14156. };
  14157. Engine.prototype.bindBuffer = function (buffer, target) {
  14158. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14159. this._gl.bindBuffer(target, buffer);
  14160. this._currentBoundBuffer[target] = buffer;
  14161. }
  14162. };
  14163. /**
  14164. * update the bound buffer with the given data
  14165. * @param data defines the data to update
  14166. */
  14167. Engine.prototype.updateArrayBuffer = function (data) {
  14168. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14169. };
  14170. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14171. var pointer = this._currentBufferPointers[indx];
  14172. var changed = false;
  14173. if (!pointer.active) {
  14174. changed = true;
  14175. pointer.active = true;
  14176. pointer.index = indx;
  14177. pointer.size = size;
  14178. pointer.type = type;
  14179. pointer.normalized = normalized;
  14180. pointer.stride = stride;
  14181. pointer.offset = offset;
  14182. pointer.buffer = buffer;
  14183. }
  14184. else {
  14185. if (pointer.buffer !== buffer) {
  14186. pointer.buffer = buffer;
  14187. changed = true;
  14188. }
  14189. if (pointer.size !== size) {
  14190. pointer.size = size;
  14191. changed = true;
  14192. }
  14193. if (pointer.type !== type) {
  14194. pointer.type = type;
  14195. changed = true;
  14196. }
  14197. if (pointer.normalized !== normalized) {
  14198. pointer.normalized = normalized;
  14199. changed = true;
  14200. }
  14201. if (pointer.stride !== stride) {
  14202. pointer.stride = stride;
  14203. changed = true;
  14204. }
  14205. if (pointer.offset !== offset) {
  14206. pointer.offset = offset;
  14207. changed = true;
  14208. }
  14209. }
  14210. if (changed || this._vaoRecordInProgress) {
  14211. this.bindArrayBuffer(buffer);
  14212. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14213. }
  14214. };
  14215. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14216. if (indexBuffer == null) {
  14217. return;
  14218. }
  14219. if (this._cachedIndexBuffer !== indexBuffer) {
  14220. this._cachedIndexBuffer = indexBuffer;
  14221. this.bindIndexBuffer(indexBuffer);
  14222. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14223. }
  14224. };
  14225. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14226. var attributes = effect.getAttributesNames();
  14227. if (!this._vaoRecordInProgress) {
  14228. this._unbindVertexArrayObject();
  14229. }
  14230. this.unbindAllAttributes();
  14231. for (var index = 0; index < attributes.length; index++) {
  14232. var order = effect.getAttributeLocation(index);
  14233. if (order >= 0) {
  14234. var vertexBuffer = vertexBuffers[attributes[index]];
  14235. if (!vertexBuffer) {
  14236. continue;
  14237. }
  14238. this._gl.enableVertexAttribArray(order);
  14239. if (!this._vaoRecordInProgress) {
  14240. this._vertexAttribArraysEnabled[order] = true;
  14241. }
  14242. var buffer = vertexBuffer.getBuffer();
  14243. if (buffer) {
  14244. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14245. if (vertexBuffer.getIsInstanced()) {
  14246. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14247. if (!this._vaoRecordInProgress) {
  14248. this._currentInstanceLocations.push(order);
  14249. this._currentInstanceBuffers.push(buffer);
  14250. }
  14251. }
  14252. }
  14253. }
  14254. }
  14255. };
  14256. /**
  14257. * Records a vertex array object
  14258. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14259. * @param vertexBuffers defines the list of vertex buffers to store
  14260. * @param indexBuffer defines the index buffer to store
  14261. * @param effect defines the effect to store
  14262. * @returns the new vertex array object
  14263. */
  14264. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14265. var vao = this._gl.createVertexArray();
  14266. this._vaoRecordInProgress = true;
  14267. this._gl.bindVertexArray(vao);
  14268. this._mustWipeVertexAttributes = true;
  14269. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14270. this.bindIndexBuffer(indexBuffer);
  14271. this._vaoRecordInProgress = false;
  14272. this._gl.bindVertexArray(null);
  14273. return vao;
  14274. };
  14275. /**
  14276. * Bind a specific vertex array object
  14277. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14278. * @param vertexArrayObject defines the vertex array object to bind
  14279. * @param indexBuffer defines the index buffer to bind
  14280. */
  14281. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14282. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14283. this._cachedVertexArrayObject = vertexArrayObject;
  14284. this._gl.bindVertexArray(vertexArrayObject);
  14285. this._cachedVertexBuffers = null;
  14286. this._cachedIndexBuffer = null;
  14287. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14288. this._mustWipeVertexAttributes = true;
  14289. }
  14290. };
  14291. /**
  14292. * Bind webGl buffers directly to the webGL context
  14293. * @param vertexBuffer defines the vertex buffer to bind
  14294. * @param indexBuffer defines the index buffer to bind
  14295. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14296. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14297. * @param effect defines the effect associated with the vertex buffer
  14298. */
  14299. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14300. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14301. this._cachedVertexBuffers = vertexBuffer;
  14302. this._cachedEffectForVertexBuffers = effect;
  14303. var attributesCount = effect.getAttributesCount();
  14304. this._unbindVertexArrayObject();
  14305. this.unbindAllAttributes();
  14306. var offset = 0;
  14307. for (var index = 0; index < attributesCount; index++) {
  14308. if (index < vertexDeclaration.length) {
  14309. var order = effect.getAttributeLocation(index);
  14310. if (order >= 0) {
  14311. this._gl.enableVertexAttribArray(order);
  14312. this._vertexAttribArraysEnabled[order] = true;
  14313. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14314. }
  14315. offset += vertexDeclaration[index] * 4;
  14316. }
  14317. }
  14318. }
  14319. this._bindIndexBufferWithCache(indexBuffer);
  14320. };
  14321. Engine.prototype._unbindVertexArrayObject = function () {
  14322. if (!this._cachedVertexArrayObject) {
  14323. return;
  14324. }
  14325. this._cachedVertexArrayObject = null;
  14326. this._gl.bindVertexArray(null);
  14327. };
  14328. /**
  14329. * Bind a list of vertex buffers to the webGL context
  14330. * @param vertexBuffers defines the list of vertex buffers to bind
  14331. * @param indexBuffer defines the index buffer to bind
  14332. * @param effect defines the effect associated with the vertex buffers
  14333. */
  14334. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14335. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14336. this._cachedVertexBuffers = vertexBuffers;
  14337. this._cachedEffectForVertexBuffers = effect;
  14338. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14339. }
  14340. this._bindIndexBufferWithCache(indexBuffer);
  14341. };
  14342. /**
  14343. * Unbind all instance attributes
  14344. */
  14345. Engine.prototype.unbindInstanceAttributes = function () {
  14346. var boundBuffer;
  14347. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14348. var instancesBuffer = this._currentInstanceBuffers[i];
  14349. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14350. boundBuffer = instancesBuffer;
  14351. this.bindArrayBuffer(instancesBuffer);
  14352. }
  14353. var offsetLocation = this._currentInstanceLocations[i];
  14354. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14355. }
  14356. this._currentInstanceBuffers.length = 0;
  14357. this._currentInstanceLocations.length = 0;
  14358. };
  14359. /**
  14360. * Release and free the memory of a vertex array object
  14361. * @param vao defines the vertex array object to delete
  14362. */
  14363. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14364. this._gl.deleteVertexArray(vao);
  14365. };
  14366. /** @hidden */
  14367. Engine.prototype._releaseBuffer = function (buffer) {
  14368. buffer.references--;
  14369. if (buffer.references === 0) {
  14370. this._gl.deleteBuffer(buffer);
  14371. return true;
  14372. }
  14373. return false;
  14374. };
  14375. /**
  14376. * Creates a webGL buffer to use with instanciation
  14377. * @param capacity defines the size of the buffer
  14378. * @returns the webGL buffer
  14379. */
  14380. Engine.prototype.createInstancesBuffer = function (capacity) {
  14381. var buffer = this._gl.createBuffer();
  14382. if (!buffer) {
  14383. throw new Error("Unable to create instance buffer");
  14384. }
  14385. buffer.capacity = capacity;
  14386. this.bindArrayBuffer(buffer);
  14387. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14388. return buffer;
  14389. };
  14390. /**
  14391. * Delete a webGL buffer used with instanciation
  14392. * @param buffer defines the webGL buffer to delete
  14393. */
  14394. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14395. this._gl.deleteBuffer(buffer);
  14396. };
  14397. /**
  14398. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14399. * @param instancesBuffer defines the webGL buffer to update and bind
  14400. * @param data defines the data to store in the buffer
  14401. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14402. */
  14403. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14404. this.bindArrayBuffer(instancesBuffer);
  14405. if (data) {
  14406. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14407. }
  14408. if (offsetLocations[0].index !== undefined) {
  14409. var stride = 0;
  14410. for (var i = 0; i < offsetLocations.length; i++) {
  14411. var ai = offsetLocations[i];
  14412. stride += ai.attributeSize * 4;
  14413. }
  14414. for (var i = 0; i < offsetLocations.length; i++) {
  14415. var ai = offsetLocations[i];
  14416. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14417. this._gl.enableVertexAttribArray(ai.index);
  14418. this._vertexAttribArraysEnabled[ai.index] = true;
  14419. }
  14420. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14421. this._gl.vertexAttribDivisor(ai.index, 1);
  14422. this._currentInstanceLocations.push(ai.index);
  14423. this._currentInstanceBuffers.push(instancesBuffer);
  14424. }
  14425. }
  14426. else {
  14427. for (var index = 0; index < 4; index++) {
  14428. var offsetLocation = offsetLocations[index];
  14429. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14430. this._gl.enableVertexAttribArray(offsetLocation);
  14431. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14432. }
  14433. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14434. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14435. this._currentInstanceLocations.push(offsetLocation);
  14436. this._currentInstanceBuffers.push(instancesBuffer);
  14437. }
  14438. }
  14439. };
  14440. /**
  14441. * Apply all cached states (depth, culling, stencil and alpha)
  14442. */
  14443. Engine.prototype.applyStates = function () {
  14444. this._depthCullingState.apply(this._gl);
  14445. this._stencilState.apply(this._gl);
  14446. this._alphaState.apply(this._gl);
  14447. };
  14448. /**
  14449. * Send a draw order
  14450. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14451. * @param indexStart defines the starting index
  14452. * @param indexCount defines the number of index to draw
  14453. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14454. */
  14455. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14456. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14457. };
  14458. /**
  14459. * Draw a list of points
  14460. * @param verticesStart defines the index of first vertex to draw
  14461. * @param verticesCount defines the count of vertices to draw
  14462. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14463. */
  14464. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14465. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14466. };
  14467. /**
  14468. * Draw a list of unindexed primitives
  14469. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14470. * @param verticesStart defines the index of first vertex to draw
  14471. * @param verticesCount defines the count of vertices to draw
  14472. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14473. */
  14474. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14475. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14476. };
  14477. /**
  14478. * Draw a list of indexed primitives
  14479. * @param fillMode defines the primitive to use
  14480. * @param indexStart defines the starting index
  14481. * @param indexCount defines the number of index to draw
  14482. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14483. */
  14484. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14485. // Apply states
  14486. this.applyStates();
  14487. this._drawCalls.addCount(1, false);
  14488. // Render
  14489. var drawMode = this._drawMode(fillMode);
  14490. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14491. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14492. if (instancesCount) {
  14493. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14494. }
  14495. else {
  14496. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14497. }
  14498. };
  14499. /**
  14500. * Draw a list of unindexed primitives
  14501. * @param fillMode defines the primitive to use
  14502. * @param verticesStart defines the index of first vertex to draw
  14503. * @param verticesCount defines the count of vertices to draw
  14504. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14505. */
  14506. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14507. // Apply states
  14508. this.applyStates();
  14509. this._drawCalls.addCount(1, false);
  14510. var drawMode = this._drawMode(fillMode);
  14511. if (instancesCount) {
  14512. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14513. }
  14514. else {
  14515. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14516. }
  14517. };
  14518. Engine.prototype._drawMode = function (fillMode) {
  14519. switch (fillMode) {
  14520. // Triangle views
  14521. case BABYLON.Material.TriangleFillMode:
  14522. return this._gl.TRIANGLES;
  14523. case BABYLON.Material.PointFillMode:
  14524. return this._gl.POINTS;
  14525. case BABYLON.Material.WireFrameFillMode:
  14526. return this._gl.LINES;
  14527. // Draw modes
  14528. case BABYLON.Material.PointListDrawMode:
  14529. return this._gl.POINTS;
  14530. case BABYLON.Material.LineListDrawMode:
  14531. return this._gl.LINES;
  14532. case BABYLON.Material.LineLoopDrawMode:
  14533. return this._gl.LINE_LOOP;
  14534. case BABYLON.Material.LineStripDrawMode:
  14535. return this._gl.LINE_STRIP;
  14536. case BABYLON.Material.TriangleStripDrawMode:
  14537. return this._gl.TRIANGLE_STRIP;
  14538. case BABYLON.Material.TriangleFanDrawMode:
  14539. return this._gl.TRIANGLE_FAN;
  14540. default:
  14541. return this._gl.TRIANGLES;
  14542. }
  14543. };
  14544. // Shaders
  14545. /** @hidden */
  14546. Engine.prototype._releaseEffect = function (effect) {
  14547. if (this._compiledEffects[effect._key]) {
  14548. delete this._compiledEffects[effect._key];
  14549. this._deleteProgram(effect.getProgram());
  14550. }
  14551. };
  14552. /** @hidden */
  14553. Engine.prototype._deleteProgram = function (program) {
  14554. if (program) {
  14555. program.__SPECTOR_rebuildProgram = null;
  14556. if (program.transformFeedback) {
  14557. this.deleteTransformFeedback(program.transformFeedback);
  14558. program.transformFeedback = null;
  14559. }
  14560. this._gl.deleteProgram(program);
  14561. }
  14562. };
  14563. /**
  14564. * Create a new effect (used to store vertex/fragment shaders)
  14565. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14566. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14567. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14568. * @param samplers defines an array of string used to represent textures
  14569. * @param defines defines the string containing the defines to use to compile the shaders
  14570. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14571. * @param onCompiled defines a function to call when the effect creation is successful
  14572. * @param onError defines a function to call when the effect creation has failed
  14573. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14574. * @returns the new Effect
  14575. */
  14576. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14577. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14578. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14579. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14580. if (this._compiledEffects[name]) {
  14581. var compiledEffect = this._compiledEffects[name];
  14582. if (onCompiled && compiledEffect.isReady()) {
  14583. onCompiled(compiledEffect);
  14584. }
  14585. return compiledEffect;
  14586. }
  14587. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14588. effect._key = name;
  14589. this._compiledEffects[name] = effect;
  14590. return effect;
  14591. };
  14592. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14593. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14594. };
  14595. Engine.prototype._compileRawShader = function (source, type) {
  14596. var gl = this._gl;
  14597. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14598. if (!shader) {
  14599. throw new Error("Something went wrong while compile the shader.");
  14600. }
  14601. gl.shaderSource(shader, source);
  14602. gl.compileShader(shader);
  14603. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14604. var log = gl.getShaderInfoLog(shader);
  14605. if (log) {
  14606. throw new Error(log);
  14607. }
  14608. }
  14609. return shader;
  14610. };
  14611. /**
  14612. * Directly creates a webGL program
  14613. * @param vertexCode defines the vertex shader code to use
  14614. * @param fragmentCode defines the fragment shader code to use
  14615. * @param context defines the webGL context to use (if not set, the current one will be used)
  14616. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14617. * @returns the new webGL program
  14618. */
  14619. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14620. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14621. context = context || this._gl;
  14622. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14623. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14624. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14625. };
  14626. /**
  14627. * Creates a webGL program
  14628. * @param vertexCode defines the vertex shader code to use
  14629. * @param fragmentCode defines the fragment shader code to use
  14630. * @param defines defines the string containing the defines to use to compile the shaders
  14631. * @param context defines the webGL context to use (if not set, the current one will be used)
  14632. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14633. * @returns the new webGL program
  14634. */
  14635. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14636. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14637. context = context || this._gl;
  14638. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14639. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14640. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14641. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14642. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14643. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14644. return program;
  14645. };
  14646. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14647. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14648. var shaderProgram = context.createProgram();
  14649. if (!shaderProgram) {
  14650. throw new Error("Unable to create program");
  14651. }
  14652. context.attachShader(shaderProgram, vertexShader);
  14653. context.attachShader(shaderProgram, fragmentShader);
  14654. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14655. var transformFeedback = this.createTransformFeedback();
  14656. this.bindTransformFeedback(transformFeedback);
  14657. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14658. shaderProgram.transformFeedback = transformFeedback;
  14659. }
  14660. context.linkProgram(shaderProgram);
  14661. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14662. this.bindTransformFeedback(null);
  14663. }
  14664. shaderProgram.context = context;
  14665. shaderProgram.vertexShader = vertexShader;
  14666. shaderProgram.fragmentShader = fragmentShader;
  14667. if (!this._caps.parallelShaderCompile) {
  14668. this._finalizeProgram(shaderProgram);
  14669. }
  14670. else {
  14671. shaderProgram.isParallelCompiled = true;
  14672. }
  14673. return shaderProgram;
  14674. };
  14675. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14676. var context = shaderProgram.context;
  14677. var vertexShader = shaderProgram.vertexShader;
  14678. var fragmentShader = shaderProgram.fragmentShader;
  14679. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14680. if (!linked) {
  14681. var error = context.getProgramInfoLog(shaderProgram);
  14682. if (error) {
  14683. throw new Error(error);
  14684. }
  14685. }
  14686. if (this.validateShaderPrograms) {
  14687. context.validateProgram(shaderProgram);
  14688. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14689. if (!validated) {
  14690. var error = context.getProgramInfoLog(shaderProgram);
  14691. if (error) {
  14692. throw new Error(error);
  14693. }
  14694. }
  14695. }
  14696. context.deleteShader(vertexShader);
  14697. context.deleteShader(fragmentShader);
  14698. shaderProgram.context = undefined;
  14699. shaderProgram.vertexShader = undefined;
  14700. shaderProgram.fragmentShader = undefined;
  14701. if (shaderProgram.onCompiled) {
  14702. shaderProgram.onCompiled();
  14703. shaderProgram.onCompiled = undefined;
  14704. }
  14705. };
  14706. /** @hidden */
  14707. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14708. if (!shaderProgram.isParallelCompiled) {
  14709. return true;
  14710. }
  14711. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14712. this._finalizeProgram(shaderProgram);
  14713. return true;
  14714. }
  14715. return false;
  14716. };
  14717. /** @hidden */
  14718. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14719. if (!shaderProgram.isParallelCompiled) {
  14720. action();
  14721. return;
  14722. }
  14723. shaderProgram.onCompiled = action;
  14724. };
  14725. /**
  14726. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14727. * @param shaderProgram defines the webGL program to use
  14728. * @param uniformsNames defines the list of uniform names
  14729. * @returns an array of webGL uniform locations
  14730. */
  14731. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14732. var results = new Array();
  14733. for (var index = 0; index < uniformsNames.length; index++) {
  14734. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14735. }
  14736. return results;
  14737. };
  14738. /**
  14739. * Gets the lsit of active attributes for a given webGL program
  14740. * @param shaderProgram defines the webGL program to use
  14741. * @param attributesNames defines the list of attribute names to get
  14742. * @returns an array of indices indicating the offset of each attribute
  14743. */
  14744. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14745. var results = [];
  14746. for (var index = 0; index < attributesNames.length; index++) {
  14747. try {
  14748. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14749. }
  14750. catch (e) {
  14751. results.push(-1);
  14752. }
  14753. }
  14754. return results;
  14755. };
  14756. /**
  14757. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14758. * @param effect defines the effect to activate
  14759. */
  14760. Engine.prototype.enableEffect = function (effect) {
  14761. if (!effect || effect === this._currentEffect) {
  14762. return;
  14763. }
  14764. // Use program
  14765. this.bindSamplers(effect);
  14766. this._currentEffect = effect;
  14767. if (effect.onBind) {
  14768. effect.onBind(effect);
  14769. }
  14770. if (effect._onBindObservable) {
  14771. effect._onBindObservable.notifyObservers(effect);
  14772. }
  14773. };
  14774. /**
  14775. * Set the value of an uniform to an array of int32
  14776. * @param uniform defines the webGL uniform location where to store the value
  14777. * @param array defines the array of int32 to store
  14778. */
  14779. Engine.prototype.setIntArray = function (uniform, array) {
  14780. if (!uniform) {
  14781. return;
  14782. }
  14783. this._gl.uniform1iv(uniform, array);
  14784. };
  14785. /**
  14786. * Set the value of an uniform to an array of int32 (stored as vec2)
  14787. * @param uniform defines the webGL uniform location where to store the value
  14788. * @param array defines the array of int32 to store
  14789. */
  14790. Engine.prototype.setIntArray2 = function (uniform, array) {
  14791. if (!uniform || array.length % 2 !== 0) {
  14792. return;
  14793. }
  14794. this._gl.uniform2iv(uniform, array);
  14795. };
  14796. /**
  14797. * Set the value of an uniform to an array of int32 (stored as vec3)
  14798. * @param uniform defines the webGL uniform location where to store the value
  14799. * @param array defines the array of int32 to store
  14800. */
  14801. Engine.prototype.setIntArray3 = function (uniform, array) {
  14802. if (!uniform || array.length % 3 !== 0) {
  14803. return;
  14804. }
  14805. this._gl.uniform3iv(uniform, array);
  14806. };
  14807. /**
  14808. * Set the value of an uniform to an array of int32 (stored as vec4)
  14809. * @param uniform defines the webGL uniform location where to store the value
  14810. * @param array defines the array of int32 to store
  14811. */
  14812. Engine.prototype.setIntArray4 = function (uniform, array) {
  14813. if (!uniform || array.length % 4 !== 0) {
  14814. return;
  14815. }
  14816. this._gl.uniform4iv(uniform, array);
  14817. };
  14818. /**
  14819. * Set the value of an uniform to an array of float32
  14820. * @param uniform defines the webGL uniform location where to store the value
  14821. * @param array defines the array of float32 to store
  14822. */
  14823. Engine.prototype.setFloatArray = function (uniform, array) {
  14824. if (!uniform) {
  14825. return;
  14826. }
  14827. this._gl.uniform1fv(uniform, array);
  14828. };
  14829. /**
  14830. * Set the value of an uniform to an array of float32 (stored as vec2)
  14831. * @param uniform defines the webGL uniform location where to store the value
  14832. * @param array defines the array of float32 to store
  14833. */
  14834. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14835. if (!uniform || array.length % 2 !== 0) {
  14836. return;
  14837. }
  14838. this._gl.uniform2fv(uniform, array);
  14839. };
  14840. /**
  14841. * Set the value of an uniform to an array of float32 (stored as vec3)
  14842. * @param uniform defines the webGL uniform location where to store the value
  14843. * @param array defines the array of float32 to store
  14844. */
  14845. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14846. if (!uniform || array.length % 3 !== 0) {
  14847. return;
  14848. }
  14849. this._gl.uniform3fv(uniform, array);
  14850. };
  14851. /**
  14852. * Set the value of an uniform to an array of float32 (stored as vec4)
  14853. * @param uniform defines the webGL uniform location where to store the value
  14854. * @param array defines the array of float32 to store
  14855. */
  14856. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14857. if (!uniform || array.length % 4 !== 0) {
  14858. return;
  14859. }
  14860. this._gl.uniform4fv(uniform, array);
  14861. };
  14862. /**
  14863. * Set the value of an uniform to an array of number
  14864. * @param uniform defines the webGL uniform location where to store the value
  14865. * @param array defines the array of number to store
  14866. */
  14867. Engine.prototype.setArray = function (uniform, array) {
  14868. if (!uniform) {
  14869. return;
  14870. }
  14871. this._gl.uniform1fv(uniform, array);
  14872. };
  14873. /**
  14874. * Set the value of an uniform to an array of number (stored as vec2)
  14875. * @param uniform defines the webGL uniform location where to store the value
  14876. * @param array defines the array of number to store
  14877. */
  14878. Engine.prototype.setArray2 = function (uniform, array) {
  14879. if (!uniform || array.length % 2 !== 0) {
  14880. return;
  14881. }
  14882. this._gl.uniform2fv(uniform, array);
  14883. };
  14884. /**
  14885. * Set the value of an uniform to an array of number (stored as vec3)
  14886. * @param uniform defines the webGL uniform location where to store the value
  14887. * @param array defines the array of number to store
  14888. */
  14889. Engine.prototype.setArray3 = function (uniform, array) {
  14890. if (!uniform || array.length % 3 !== 0) {
  14891. return;
  14892. }
  14893. this._gl.uniform3fv(uniform, array);
  14894. };
  14895. /**
  14896. * Set the value of an uniform to an array of number (stored as vec4)
  14897. * @param uniform defines the webGL uniform location where to store the value
  14898. * @param array defines the array of number to store
  14899. */
  14900. Engine.prototype.setArray4 = function (uniform, array) {
  14901. if (!uniform || array.length % 4 !== 0) {
  14902. return;
  14903. }
  14904. this._gl.uniform4fv(uniform, array);
  14905. };
  14906. /**
  14907. * Set the value of an uniform to an array of float32 (stored as matrices)
  14908. * @param uniform defines the webGL uniform location where to store the value
  14909. * @param matrices defines the array of float32 to store
  14910. */
  14911. Engine.prototype.setMatrices = function (uniform, matrices) {
  14912. if (!uniform) {
  14913. return;
  14914. }
  14915. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14916. };
  14917. /**
  14918. * Set the value of an uniform to a matrix
  14919. * @param uniform defines the webGL uniform location where to store the value
  14920. * @param matrix defines the matrix to store
  14921. */
  14922. Engine.prototype.setMatrix = function (uniform, matrix) {
  14923. if (!uniform) {
  14924. return;
  14925. }
  14926. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14927. };
  14928. /**
  14929. * Set the value of an uniform to a matrix (3x3)
  14930. * @param uniform defines the webGL uniform location where to store the value
  14931. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14932. */
  14933. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14934. if (!uniform) {
  14935. return;
  14936. }
  14937. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14938. };
  14939. /**
  14940. * Set the value of an uniform to a matrix (2x2)
  14941. * @param uniform defines the webGL uniform location where to store the value
  14942. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14943. */
  14944. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14945. if (!uniform) {
  14946. return;
  14947. }
  14948. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14949. };
  14950. /**
  14951. * Set the value of an uniform to a number (int)
  14952. * @param uniform defines the webGL uniform location where to store the value
  14953. * @param value defines the int number to store
  14954. */
  14955. Engine.prototype.setInt = function (uniform, value) {
  14956. if (!uniform) {
  14957. return;
  14958. }
  14959. this._gl.uniform1i(uniform, value);
  14960. };
  14961. /**
  14962. * Set the value of an uniform to a number (float)
  14963. * @param uniform defines the webGL uniform location where to store the value
  14964. * @param value defines the float number to store
  14965. */
  14966. Engine.prototype.setFloat = function (uniform, value) {
  14967. if (!uniform) {
  14968. return;
  14969. }
  14970. this._gl.uniform1f(uniform, value);
  14971. };
  14972. /**
  14973. * Set the value of an uniform to a vec2
  14974. * @param uniform defines the webGL uniform location where to store the value
  14975. * @param x defines the 1st component of the value
  14976. * @param y defines the 2nd component of the value
  14977. */
  14978. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14979. if (!uniform) {
  14980. return;
  14981. }
  14982. this._gl.uniform2f(uniform, x, y);
  14983. };
  14984. /**
  14985. * Set the value of an uniform to a vec3
  14986. * @param uniform defines the webGL uniform location where to store the value
  14987. * @param x defines the 1st component of the value
  14988. * @param y defines the 2nd component of the value
  14989. * @param z defines the 3rd component of the value
  14990. */
  14991. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14992. if (!uniform) {
  14993. return;
  14994. }
  14995. this._gl.uniform3f(uniform, x, y, z);
  14996. };
  14997. /**
  14998. * Set the value of an uniform to a boolean
  14999. * @param uniform defines the webGL uniform location where to store the value
  15000. * @param bool defines the boolean to store
  15001. */
  15002. Engine.prototype.setBool = function (uniform, bool) {
  15003. if (!uniform) {
  15004. return;
  15005. }
  15006. this._gl.uniform1i(uniform, bool);
  15007. };
  15008. /**
  15009. * Set the value of an uniform to a vec4
  15010. * @param uniform defines the webGL uniform location where to store the value
  15011. * @param x defines the 1st component of the value
  15012. * @param y defines the 2nd component of the value
  15013. * @param z defines the 3rd component of the value
  15014. * @param w defines the 4th component of the value
  15015. */
  15016. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  15017. if (!uniform) {
  15018. return;
  15019. }
  15020. this._gl.uniform4f(uniform, x, y, z, w);
  15021. };
  15022. /**
  15023. * Set the value of an uniform to a Color3
  15024. * @param uniform defines the webGL uniform location where to store the value
  15025. * @param color3 defines the color to store
  15026. */
  15027. Engine.prototype.setColor3 = function (uniform, color3) {
  15028. if (!uniform) {
  15029. return;
  15030. }
  15031. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15032. };
  15033. /**
  15034. * Set the value of an uniform to a Color3 and an alpha value
  15035. * @param uniform defines the webGL uniform location where to store the value
  15036. * @param color3 defines the color to store
  15037. * @param alpha defines the alpha component to store
  15038. */
  15039. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15040. if (!uniform) {
  15041. return;
  15042. }
  15043. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15044. };
  15045. /**
  15046. * Sets a Color4 on a uniform variable
  15047. * @param uniform defines the uniform location
  15048. * @param color4 defines the value to be set
  15049. */
  15050. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15051. if (!uniform) {
  15052. return;
  15053. }
  15054. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15055. };
  15056. // States
  15057. /**
  15058. * Set various states to the webGL context
  15059. * @param culling defines backface culling state
  15060. * @param zOffset defines the value to apply to zOffset (0 by default)
  15061. * @param force defines if states must be applied even if cache is up to date
  15062. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15063. */
  15064. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15065. if (zOffset === void 0) { zOffset = 0; }
  15066. if (reverseSide === void 0) { reverseSide = false; }
  15067. // Culling
  15068. if (this._depthCullingState.cull !== culling || force) {
  15069. this._depthCullingState.cull = culling;
  15070. }
  15071. // Cull face
  15072. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15073. if (this._depthCullingState.cullFace !== cullFace || force) {
  15074. this._depthCullingState.cullFace = cullFace;
  15075. }
  15076. // Z offset
  15077. this.setZOffset(zOffset);
  15078. // Front face
  15079. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15080. if (this._depthCullingState.frontFace !== frontFace || force) {
  15081. this._depthCullingState.frontFace = frontFace;
  15082. }
  15083. };
  15084. /**
  15085. * Set the z offset to apply to current rendering
  15086. * @param value defines the offset to apply
  15087. */
  15088. Engine.prototype.setZOffset = function (value) {
  15089. this._depthCullingState.zOffset = value;
  15090. };
  15091. /**
  15092. * Gets the current value of the zOffset
  15093. * @returns the current zOffset state
  15094. */
  15095. Engine.prototype.getZOffset = function () {
  15096. return this._depthCullingState.zOffset;
  15097. };
  15098. /**
  15099. * Enable or disable depth buffering
  15100. * @param enable defines the state to set
  15101. */
  15102. Engine.prototype.setDepthBuffer = function (enable) {
  15103. this._depthCullingState.depthTest = enable;
  15104. };
  15105. /**
  15106. * Gets a boolean indicating if depth writing is enabled
  15107. * @returns the current depth writing state
  15108. */
  15109. Engine.prototype.getDepthWrite = function () {
  15110. return this._depthCullingState.depthMask;
  15111. };
  15112. /**
  15113. * Enable or disable depth writing
  15114. * @param enable defines the state to set
  15115. */
  15116. Engine.prototype.setDepthWrite = function (enable) {
  15117. this._depthCullingState.depthMask = enable;
  15118. };
  15119. /**
  15120. * Enable or disable color writing
  15121. * @param enable defines the state to set
  15122. */
  15123. Engine.prototype.setColorWrite = function (enable) {
  15124. this._gl.colorMask(enable, enable, enable, enable);
  15125. this._colorWrite = enable;
  15126. };
  15127. /**
  15128. * Gets a boolean indicating if color writing is enabled
  15129. * @returns the current color writing state
  15130. */
  15131. Engine.prototype.getColorWrite = function () {
  15132. return this._colorWrite;
  15133. };
  15134. /**
  15135. * Sets alpha constants used by some alpha blending modes
  15136. * @param r defines the red component
  15137. * @param g defines the green component
  15138. * @param b defines the blue component
  15139. * @param a defines the alpha component
  15140. */
  15141. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15142. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15143. };
  15144. /**
  15145. * Sets the current alpha mode
  15146. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15147. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15148. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15149. */
  15150. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15151. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15152. if (this._alphaMode === mode) {
  15153. return;
  15154. }
  15155. switch (mode) {
  15156. case Engine.ALPHA_DISABLE:
  15157. this._alphaState.alphaBlend = false;
  15158. break;
  15159. case Engine.ALPHA_PREMULTIPLIED:
  15160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15161. this._alphaState.alphaBlend = true;
  15162. break;
  15163. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15165. this._alphaState.alphaBlend = true;
  15166. break;
  15167. case Engine.ALPHA_COMBINE:
  15168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15169. this._alphaState.alphaBlend = true;
  15170. break;
  15171. case Engine.ALPHA_ONEONE:
  15172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15173. this._alphaState.alphaBlend = true;
  15174. break;
  15175. case Engine.ALPHA_ADD:
  15176. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15177. this._alphaState.alphaBlend = true;
  15178. break;
  15179. case Engine.ALPHA_SUBTRACT:
  15180. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15181. this._alphaState.alphaBlend = true;
  15182. break;
  15183. case Engine.ALPHA_MULTIPLY:
  15184. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15185. this._alphaState.alphaBlend = true;
  15186. break;
  15187. case Engine.ALPHA_MAXIMIZED:
  15188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15189. this._alphaState.alphaBlend = true;
  15190. break;
  15191. case Engine.ALPHA_INTERPOLATE:
  15192. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15193. this._alphaState.alphaBlend = true;
  15194. break;
  15195. case Engine.ALPHA_SCREENMODE:
  15196. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15197. this._alphaState.alphaBlend = true;
  15198. break;
  15199. }
  15200. if (!noDepthWriteChange) {
  15201. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15202. }
  15203. this._alphaMode = mode;
  15204. };
  15205. /**
  15206. * Gets the current alpha mode
  15207. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15208. * @returns the current alpha mode
  15209. */
  15210. Engine.prototype.getAlphaMode = function () {
  15211. return this._alphaMode;
  15212. };
  15213. // Textures
  15214. /**
  15215. * Clears the list of texture accessible through engine.
  15216. * This can help preventing texture load conflict due to name collision.
  15217. */
  15218. Engine.prototype.clearInternalTexturesCache = function () {
  15219. this._internalTexturesCache = [];
  15220. };
  15221. /**
  15222. * Force the entire cache to be cleared
  15223. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15224. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15225. */
  15226. Engine.prototype.wipeCaches = function (bruteForce) {
  15227. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15228. return;
  15229. }
  15230. this._currentEffect = null;
  15231. this._viewportCached.x = 0;
  15232. this._viewportCached.y = 0;
  15233. this._viewportCached.z = 0;
  15234. this._viewportCached.w = 0;
  15235. if (bruteForce) {
  15236. this.resetTextureCache();
  15237. this._currentProgram = null;
  15238. this._stencilState.reset();
  15239. this._depthCullingState.reset();
  15240. this.setDepthFunctionToLessOrEqual();
  15241. this._alphaState.reset();
  15242. this._unpackFlipYCached = null;
  15243. }
  15244. this._resetVertexBufferBinding();
  15245. this._cachedIndexBuffer = null;
  15246. this._cachedEffectForVertexBuffers = null;
  15247. this._unbindVertexArrayObject();
  15248. this.bindIndexBuffer(null);
  15249. };
  15250. /**
  15251. * Set the compressed texture format to use, based on the formats you have, and the formats
  15252. * supported by the hardware / browser.
  15253. *
  15254. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15255. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15256. * to API arguments needed to compressed textures. This puts the burden on the container
  15257. * generator to house the arcane code for determining these for current & future formats.
  15258. *
  15259. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15260. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15261. *
  15262. * Note: The result of this call is not taken into account when a texture is base64.
  15263. *
  15264. * @param formatsAvailable defines the list of those format families you have created
  15265. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15266. *
  15267. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15268. * @returns The extension selected.
  15269. */
  15270. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15271. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15272. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15273. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15274. return this._textureFormatInUse = this._texturesSupported[i];
  15275. }
  15276. }
  15277. }
  15278. // actively set format to nothing, to allow this to be called more than once
  15279. // and possibly fail the 2nd time
  15280. this._textureFormatInUse = null;
  15281. return null;
  15282. };
  15283. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15284. var gl = this._gl;
  15285. var magFilter = gl.NEAREST;
  15286. var minFilter = gl.NEAREST;
  15287. switch (samplingMode) {
  15288. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15289. magFilter = gl.LINEAR;
  15290. if (generateMipMaps) {
  15291. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15292. }
  15293. else {
  15294. minFilter = gl.LINEAR;
  15295. }
  15296. break;
  15297. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15298. magFilter = gl.LINEAR;
  15299. if (generateMipMaps) {
  15300. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15301. }
  15302. else {
  15303. minFilter = gl.LINEAR;
  15304. }
  15305. break;
  15306. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15307. magFilter = gl.NEAREST;
  15308. if (generateMipMaps) {
  15309. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15310. }
  15311. else {
  15312. minFilter = gl.NEAREST;
  15313. }
  15314. break;
  15315. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15316. magFilter = gl.NEAREST;
  15317. if (generateMipMaps) {
  15318. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15319. }
  15320. else {
  15321. minFilter = gl.NEAREST;
  15322. }
  15323. break;
  15324. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15325. magFilter = gl.NEAREST;
  15326. if (generateMipMaps) {
  15327. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15328. }
  15329. else {
  15330. minFilter = gl.LINEAR;
  15331. }
  15332. break;
  15333. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15334. magFilter = gl.NEAREST;
  15335. if (generateMipMaps) {
  15336. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15337. }
  15338. else {
  15339. minFilter = gl.LINEAR;
  15340. }
  15341. break;
  15342. case Engine.TEXTURE_NEAREST_LINEAR:
  15343. magFilter = gl.NEAREST;
  15344. minFilter = gl.LINEAR;
  15345. break;
  15346. case Engine.TEXTURE_NEAREST_NEAREST:
  15347. magFilter = gl.NEAREST;
  15348. minFilter = gl.NEAREST;
  15349. break;
  15350. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15351. magFilter = gl.LINEAR;
  15352. if (generateMipMaps) {
  15353. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15354. }
  15355. else {
  15356. minFilter = gl.NEAREST;
  15357. }
  15358. break;
  15359. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15360. magFilter = gl.LINEAR;
  15361. if (generateMipMaps) {
  15362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15363. }
  15364. else {
  15365. minFilter = gl.NEAREST;
  15366. }
  15367. break;
  15368. case Engine.TEXTURE_LINEAR_LINEAR:
  15369. magFilter = gl.LINEAR;
  15370. minFilter = gl.LINEAR;
  15371. break;
  15372. case Engine.TEXTURE_LINEAR_NEAREST:
  15373. magFilter = gl.LINEAR;
  15374. minFilter = gl.NEAREST;
  15375. break;
  15376. }
  15377. return {
  15378. min: minFilter,
  15379. mag: magFilter
  15380. };
  15381. };
  15382. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15383. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15384. var img;
  15385. var onload = function () {
  15386. loadedImages[index] = img;
  15387. loadedImages._internalCount++;
  15388. if (scene) {
  15389. scene._removePendingData(img);
  15390. }
  15391. if (loadedImages._internalCount === 6) {
  15392. onfinish(loadedImages);
  15393. }
  15394. };
  15395. var onerror = function (message, exception) {
  15396. if (scene) {
  15397. scene._removePendingData(img);
  15398. }
  15399. if (onErrorCallBack) {
  15400. onErrorCallBack(message, exception);
  15401. }
  15402. };
  15403. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15404. if (scene) {
  15405. scene._addPendingData(img);
  15406. }
  15407. };
  15408. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15409. if (onError === void 0) { onError = null; }
  15410. var loadedImages = [];
  15411. loadedImages._internalCount = 0;
  15412. for (var index = 0; index < 6; index++) {
  15413. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15414. }
  15415. };
  15416. /** @hidden */
  15417. Engine.prototype._createTexture = function () {
  15418. var texture = this._gl.createTexture();
  15419. if (!texture) {
  15420. throw new Error("Unable to create texture");
  15421. }
  15422. return texture;
  15423. };
  15424. /**
  15425. * Usually called from BABYLON.Texture.ts.
  15426. * Passed information to create a WebGLTexture
  15427. * @param urlArg defines a value which contains one of the following:
  15428. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15429. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15430. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15431. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15432. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15433. * @param scene needed for loading to the correct scene
  15434. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15435. * @param onLoad optional callback to be called upon successful completion
  15436. * @param onError optional callback to be called upon failure
  15437. * @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
  15438. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15439. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15440. * @param forcedExtension defines the extension to use to pick the right loader
  15441. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15442. */
  15443. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15444. var _this = this;
  15445. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15446. if (onLoad === void 0) { onLoad = null; }
  15447. if (onError === void 0) { onError = null; }
  15448. if (buffer === void 0) { buffer = null; }
  15449. if (fallback === void 0) { fallback = null; }
  15450. if (format === void 0) { format = null; }
  15451. if (forcedExtension === void 0) { forcedExtension = null; }
  15452. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15453. var fromData = url.substr(0, 5) === "data:";
  15454. var fromBlob = url.substr(0, 5) === "blob:";
  15455. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15456. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15457. // establish the file extension, if possible
  15458. var lastDot = url.lastIndexOf('.');
  15459. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15460. var loader = null;
  15461. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15462. var availableLoader = _a[_i];
  15463. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15464. loader = availableLoader;
  15465. break;
  15466. }
  15467. }
  15468. if (loader) {
  15469. url = loader.transformUrl(url, this._textureFormatInUse);
  15470. }
  15471. if (scene) {
  15472. scene._addPendingData(texture);
  15473. }
  15474. texture.url = url;
  15475. texture.generateMipMaps = !noMipmap;
  15476. texture.samplingMode = samplingMode;
  15477. texture.invertY = invertY;
  15478. if (!this._doNotHandleContextLost) {
  15479. // Keep a link to the buffer only if we plan to handle context lost
  15480. texture._buffer = buffer;
  15481. }
  15482. var onLoadObserver = null;
  15483. if (onLoad && !fallback) {
  15484. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15485. }
  15486. if (!fallback) {
  15487. this._internalTexturesCache.push(texture);
  15488. }
  15489. var onInternalError = function (message, exception) {
  15490. if (scene) {
  15491. scene._removePendingData(texture);
  15492. }
  15493. var customFallback = false;
  15494. if (loader) {
  15495. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15496. if (fallbackUrl) {
  15497. // Add Back
  15498. customFallback = true;
  15499. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15500. }
  15501. }
  15502. if (!customFallback) {
  15503. if (onLoadObserver) {
  15504. texture.onLoadedObservable.remove(onLoadObserver);
  15505. }
  15506. if (BABYLON.Tools.UseFallbackTexture) {
  15507. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15508. }
  15509. }
  15510. if (onError) {
  15511. onError(message || "Unknown error", exception);
  15512. }
  15513. };
  15514. // processing for non-image formats
  15515. if (loader) {
  15516. var callback = function (data) {
  15517. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15518. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15519. done();
  15520. return false;
  15521. }, samplingMode);
  15522. });
  15523. };
  15524. if (!buffer) {
  15525. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15526. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15527. });
  15528. }
  15529. else {
  15530. callback(buffer);
  15531. }
  15532. }
  15533. else {
  15534. var onload = function (img) {
  15535. if (fromBlob && !_this._doNotHandleContextLost) {
  15536. // We need to store the image if we need to rebuild the texture
  15537. // in case of a webgl context lost
  15538. texture._buffer = img;
  15539. }
  15540. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15541. var gl = _this._gl;
  15542. var isPot = (img.width === potWidth && img.height === potHeight);
  15543. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15544. if (isPot) {
  15545. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15546. return false;
  15547. }
  15548. var maxTextureSize = _this._caps.maxTextureSize;
  15549. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15550. _this._prepareWorkingCanvas();
  15551. if (!_this._workingCanvas || !_this._workingContext) {
  15552. return false;
  15553. }
  15554. _this._workingCanvas.width = potWidth;
  15555. _this._workingCanvas.height = potHeight;
  15556. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15557. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15558. texture.width = potWidth;
  15559. texture.height = potHeight;
  15560. return false;
  15561. }
  15562. else {
  15563. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15564. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15565. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15566. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15571. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15572. _this._releaseTexture(source_1);
  15573. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15574. continuationCallback();
  15575. });
  15576. }
  15577. return true;
  15578. }, samplingMode);
  15579. };
  15580. if (!fromData || isBase64) {
  15581. if (buffer instanceof HTMLImageElement) {
  15582. onload(buffer);
  15583. }
  15584. else {
  15585. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15586. }
  15587. }
  15588. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15589. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15590. }
  15591. else {
  15592. onload(buffer);
  15593. }
  15594. }
  15595. return texture;
  15596. };
  15597. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15598. var _this = this;
  15599. var rtt = this.createRenderTargetTexture({
  15600. width: destination.width,
  15601. height: destination.height,
  15602. }, {
  15603. generateMipMaps: false,
  15604. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15605. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15606. generateDepthBuffer: false,
  15607. generateStencilBuffer: false
  15608. });
  15609. if (!this._rescalePostProcess) {
  15610. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15611. }
  15612. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15613. _this._rescalePostProcess.onApply = function (effect) {
  15614. effect._bindTexture("textureSampler", source);
  15615. };
  15616. var hostingScene = scene;
  15617. if (!hostingScene) {
  15618. hostingScene = _this.scenes[_this.scenes.length - 1];
  15619. }
  15620. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15621. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15622. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15623. _this.unBindFramebuffer(rtt);
  15624. _this._releaseTexture(rtt);
  15625. if (onComplete) {
  15626. onComplete();
  15627. }
  15628. });
  15629. };
  15630. /**
  15631. * Update a raw texture
  15632. * @param texture defines the texture to update
  15633. * @param data defines the data to store in the texture
  15634. * @param format defines the format of the data
  15635. * @param invertY defines if data must be stored with Y axis inverted
  15636. * @param compression defines the compression used (null by default)
  15637. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15638. */
  15639. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15640. if (compression === void 0) { compression = null; }
  15641. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15642. if (!texture) {
  15643. return;
  15644. }
  15645. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15646. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15647. // babylon's internalFormat but gl's texImage2D format
  15648. var internalFormat = this._getInternalFormat(format);
  15649. var textureType = this._getWebGLTextureType(type);
  15650. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15651. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15652. if (!this._doNotHandleContextLost) {
  15653. texture._bufferView = data;
  15654. texture.format = format;
  15655. texture.type = type;
  15656. texture.invertY = invertY;
  15657. texture._compression = compression;
  15658. }
  15659. if (texture.width % 4 !== 0) {
  15660. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15661. }
  15662. if (compression && data) {
  15663. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15664. }
  15665. else {
  15666. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15667. }
  15668. if (texture.generateMipMaps) {
  15669. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15670. }
  15671. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15672. // this.resetTextureCache();
  15673. texture.isReady = true;
  15674. };
  15675. /**
  15676. * Creates a raw texture
  15677. * @param data defines the data to store in the texture
  15678. * @param width defines the width of the texture
  15679. * @param height defines the height of the texture
  15680. * @param format defines the format of the data
  15681. * @param generateMipMaps defines if the engine should generate the mip levels
  15682. * @param invertY defines if data must be stored with Y axis inverted
  15683. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15684. * @param compression defines the compression used (null by default)
  15685. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15686. * @returns the raw texture inside an InternalTexture
  15687. */
  15688. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15689. if (compression === void 0) { compression = null; }
  15690. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15691. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15692. texture.baseWidth = width;
  15693. texture.baseHeight = height;
  15694. texture.width = width;
  15695. texture.height = height;
  15696. texture.format = format;
  15697. texture.generateMipMaps = generateMipMaps;
  15698. texture.samplingMode = samplingMode;
  15699. texture.invertY = invertY;
  15700. texture._compression = compression;
  15701. texture.type = type;
  15702. if (!this._doNotHandleContextLost) {
  15703. texture._bufferView = data;
  15704. }
  15705. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15706. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15707. // Filters
  15708. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15711. if (generateMipMaps) {
  15712. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15713. }
  15714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15715. this._internalTexturesCache.push(texture);
  15716. return texture;
  15717. };
  15718. /** @hidden */
  15719. Engine.prototype._unpackFlipY = function (value) {
  15720. if (this._unpackFlipYCached !== value) {
  15721. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15722. if (this.enableUnpackFlipYCached) {
  15723. this._unpackFlipYCached = value;
  15724. }
  15725. }
  15726. };
  15727. /** @hidden */
  15728. Engine.prototype._getUnpackAlignement = function () {
  15729. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15730. };
  15731. /**
  15732. * Creates a dynamic texture
  15733. * @param width defines the width of the texture
  15734. * @param height defines the height of the texture
  15735. * @param generateMipMaps defines if the engine should generate the mip levels
  15736. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15737. * @returns the dynamic texture inside an InternalTexture
  15738. */
  15739. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15740. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15741. texture.baseWidth = width;
  15742. texture.baseHeight = height;
  15743. if (generateMipMaps) {
  15744. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15745. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15746. }
  15747. // this.resetTextureCache();
  15748. texture.width = width;
  15749. texture.height = height;
  15750. texture.isReady = false;
  15751. texture.generateMipMaps = generateMipMaps;
  15752. texture.samplingMode = samplingMode;
  15753. this.updateTextureSamplingMode(samplingMode, texture);
  15754. this._internalTexturesCache.push(texture);
  15755. return texture;
  15756. };
  15757. /**
  15758. * Update the sampling mode of a given texture
  15759. * @param samplingMode defines the required sampling mode
  15760. * @param texture defines the texture to update
  15761. */
  15762. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15763. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15764. if (texture.isCube) {
  15765. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15766. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15767. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15768. }
  15769. else if (texture.is3D) {
  15770. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15771. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15772. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15773. }
  15774. else {
  15775. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15776. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15777. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15778. }
  15779. texture.samplingMode = samplingMode;
  15780. };
  15781. /**
  15782. * Update the content of a dynamic texture
  15783. * @param texture defines the texture to update
  15784. * @param canvas defines the canvas containing the source
  15785. * @param invertY defines if data must be stored with Y axis inverted
  15786. * @param premulAlpha defines if alpha is stored as premultiplied
  15787. * @param format defines the format of the data
  15788. */
  15789. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15790. if (premulAlpha === void 0) { premulAlpha = false; }
  15791. if (!texture) {
  15792. return;
  15793. }
  15794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15795. this._unpackFlipY(invertY);
  15796. if (premulAlpha) {
  15797. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15798. }
  15799. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15800. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15801. if (texture.generateMipMaps) {
  15802. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15803. }
  15804. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15805. if (premulAlpha) {
  15806. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15807. }
  15808. texture.isReady = true;
  15809. };
  15810. /**
  15811. * Update a video texture
  15812. * @param texture defines the texture to update
  15813. * @param video defines the video element to use
  15814. * @param invertY defines if data must be stored with Y axis inverted
  15815. */
  15816. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15817. if (!texture || texture._isDisabled) {
  15818. return;
  15819. }
  15820. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15821. this._unpackFlipY(!invertY); // Video are upside down by default
  15822. try {
  15823. // Testing video texture support
  15824. if (this._videoTextureSupported === undefined) {
  15825. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15826. if (this._gl.getError() !== 0) {
  15827. this._videoTextureSupported = false;
  15828. }
  15829. else {
  15830. this._videoTextureSupported = true;
  15831. }
  15832. }
  15833. // Copy video through the current working canvas if video texture is not supported
  15834. if (!this._videoTextureSupported) {
  15835. if (!texture._workingCanvas) {
  15836. texture._workingCanvas = document.createElement("canvas");
  15837. var context = texture._workingCanvas.getContext("2d");
  15838. if (!context) {
  15839. throw new Error("Unable to get 2d context");
  15840. }
  15841. texture._workingContext = context;
  15842. texture._workingCanvas.width = texture.width;
  15843. texture._workingCanvas.height = texture.height;
  15844. }
  15845. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15846. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15847. }
  15848. else {
  15849. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15850. }
  15851. if (texture.generateMipMaps) {
  15852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15853. }
  15854. if (!wasPreviouslyBound) {
  15855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15856. }
  15857. // this.resetTextureCache();
  15858. texture.isReady = true;
  15859. }
  15860. catch (ex) {
  15861. // Something unexpected
  15862. // Let's disable the texture
  15863. texture._isDisabled = true;
  15864. }
  15865. };
  15866. /**
  15867. * Updates a depth texture Comparison Mode and Function.
  15868. * If the comparison Function is equal to 0, the mode will be set to none.
  15869. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15870. * @param texture The texture to set the comparison function for
  15871. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15872. */
  15873. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15874. if (this.webGLVersion === 1) {
  15875. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15876. return;
  15877. }
  15878. var gl = this._gl;
  15879. if (texture.isCube) {
  15880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15881. if (comparisonFunction === 0) {
  15882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15884. }
  15885. else {
  15886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15888. }
  15889. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15890. }
  15891. else {
  15892. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15893. if (comparisonFunction === 0) {
  15894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15896. }
  15897. else {
  15898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15900. }
  15901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15902. }
  15903. texture._comparisonFunction = comparisonFunction;
  15904. };
  15905. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15906. var width = size.width || size;
  15907. var height = size.height || size;
  15908. internalTexture.baseWidth = width;
  15909. internalTexture.baseHeight = height;
  15910. internalTexture.width = width;
  15911. internalTexture.height = height;
  15912. internalTexture.isReady = true;
  15913. internalTexture.samples = 1;
  15914. internalTexture.generateMipMaps = false;
  15915. internalTexture._generateDepthBuffer = true;
  15916. internalTexture._generateStencilBuffer = generateStencil;
  15917. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15918. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15919. internalTexture._comparisonFunction = comparisonFunction;
  15920. var gl = this._gl;
  15921. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15922. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15923. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15924. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15925. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15926. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15927. if (comparisonFunction === 0) {
  15928. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15929. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15930. }
  15931. else {
  15932. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15933. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15934. }
  15935. };
  15936. /**
  15937. * Creates a depth stencil texture.
  15938. * This is only available in WebGL 2 or with the depth texture extension available.
  15939. * @param size The size of face edge in the texture.
  15940. * @param options The options defining the texture.
  15941. * @returns The texture
  15942. */
  15943. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15944. if (options.isCube) {
  15945. var width = size.width || size;
  15946. return this._createDepthStencilCubeTexture(width, options);
  15947. }
  15948. else {
  15949. return this._createDepthStencilTexture(size, options);
  15950. }
  15951. };
  15952. /**
  15953. * Creates a depth stencil texture.
  15954. * This is only available in WebGL 2 or with the depth texture extension available.
  15955. * @param size The size of face edge in the texture.
  15956. * @param options The options defining the texture.
  15957. * @returns The texture
  15958. */
  15959. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15960. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15961. if (!this._caps.depthTextureExtension) {
  15962. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15963. return internalTexture;
  15964. }
  15965. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15966. var gl = this._gl;
  15967. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15968. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15969. if (this.webGLVersion > 1) {
  15970. if (internalOptions.generateStencil) {
  15971. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15972. }
  15973. else {
  15974. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15975. }
  15976. }
  15977. else {
  15978. if (internalOptions.generateStencil) {
  15979. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15980. }
  15981. else {
  15982. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15983. }
  15984. }
  15985. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15986. return internalTexture;
  15987. };
  15988. /**
  15989. * Creates a depth stencil cube texture.
  15990. * This is only available in WebGL 2.
  15991. * @param size The size of face edge in the cube texture.
  15992. * @param options The options defining the cube texture.
  15993. * @returns The cube texture
  15994. */
  15995. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15996. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15997. internalTexture.isCube = true;
  15998. if (this.webGLVersion === 1) {
  15999. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  16000. return internalTexture;
  16001. }
  16002. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16003. var gl = this._gl;
  16004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  16005. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16006. // Create the depth/stencil buffer
  16007. for (var face = 0; face < 6; face++) {
  16008. if (internalOptions.generateStencil) {
  16009. 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);
  16010. }
  16011. else {
  16012. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16013. }
  16014. }
  16015. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16016. return internalTexture;
  16017. };
  16018. /**
  16019. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  16020. * @param renderTarget The render target to set the frame buffer for
  16021. */
  16022. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  16023. // Create the framebuffer
  16024. var internalTexture = renderTarget.getInternalTexture();
  16025. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  16026. return;
  16027. }
  16028. var gl = this._gl;
  16029. var depthStencilTexture = renderTarget.depthStencilTexture;
  16030. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16031. if (depthStencilTexture.isCube) {
  16032. if (depthStencilTexture._generateStencilBuffer) {
  16033. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16034. }
  16035. else {
  16036. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16037. }
  16038. }
  16039. else {
  16040. if (depthStencilTexture._generateStencilBuffer) {
  16041. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16042. }
  16043. else {
  16044. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16045. }
  16046. }
  16047. this.bindUnboundFramebuffer(null);
  16048. };
  16049. /**
  16050. * Creates a new render target texture
  16051. * @param size defines the size of the texture
  16052. * @param options defines the options used to create the texture
  16053. * @returns a new render target texture stored in an InternalTexture
  16054. */
  16055. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16056. var fullOptions = new RenderTargetCreationOptions();
  16057. if (options !== undefined && typeof options === "object") {
  16058. fullOptions.generateMipMaps = options.generateMipMaps;
  16059. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16060. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16061. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16062. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16063. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16064. }
  16065. else {
  16066. fullOptions.generateMipMaps = options;
  16067. fullOptions.generateDepthBuffer = true;
  16068. fullOptions.generateStencilBuffer = false;
  16069. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16070. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16071. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16072. }
  16073. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16074. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16075. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16076. }
  16077. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16078. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16079. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16080. }
  16081. var gl = this._gl;
  16082. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16083. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16084. var width = size.width || size;
  16085. var height = size.height || size;
  16086. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16087. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16088. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16089. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16090. }
  16091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16095. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16096. // Create the framebuffer
  16097. var currentFrameBuffer = this._currentFramebuffer;
  16098. var framebuffer = gl.createFramebuffer();
  16099. this.bindUnboundFramebuffer(framebuffer);
  16100. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16101. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16102. if (fullOptions.generateMipMaps) {
  16103. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16104. }
  16105. // Unbind
  16106. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16107. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16108. this.bindUnboundFramebuffer(currentFrameBuffer);
  16109. texture._framebuffer = framebuffer;
  16110. texture.baseWidth = width;
  16111. texture.baseHeight = height;
  16112. texture.width = width;
  16113. texture.height = height;
  16114. texture.isReady = true;
  16115. texture.samples = 1;
  16116. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16117. texture.samplingMode = fullOptions.samplingMode;
  16118. texture.type = fullOptions.type;
  16119. texture.format = fullOptions.format;
  16120. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16121. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16122. // this.resetTextureCache();
  16123. this._internalTexturesCache.push(texture);
  16124. return texture;
  16125. };
  16126. /**
  16127. * Create a multi render target texture
  16128. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16129. * @param size defines the size of the texture
  16130. * @param options defines the creation options
  16131. * @returns the cube texture as an InternalTexture
  16132. */
  16133. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16134. var generateMipMaps = false;
  16135. var generateDepthBuffer = true;
  16136. var generateStencilBuffer = false;
  16137. var generateDepthTexture = false;
  16138. var textureCount = 1;
  16139. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16140. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16141. var types = new Array();
  16142. var samplingModes = new Array();
  16143. if (options !== undefined) {
  16144. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16145. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16146. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16147. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16148. textureCount = options.textureCount || 1;
  16149. if (options.types) {
  16150. types = options.types;
  16151. }
  16152. if (options.samplingModes) {
  16153. samplingModes = options.samplingModes;
  16154. }
  16155. }
  16156. var gl = this._gl;
  16157. // Create the framebuffer
  16158. var framebuffer = gl.createFramebuffer();
  16159. this.bindUnboundFramebuffer(framebuffer);
  16160. var width = size.width || size;
  16161. var height = size.height || size;
  16162. var textures = [];
  16163. var attachments = [];
  16164. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16165. for (var i = 0; i < textureCount; i++) {
  16166. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16167. var type = types[i] || defaultType;
  16168. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16169. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16170. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16171. }
  16172. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16173. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16174. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16175. }
  16176. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16177. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16178. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16179. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16180. }
  16181. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16182. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16183. textures.push(texture);
  16184. attachments.push(attachment);
  16185. gl.activeTexture(gl["TEXTURE" + i]);
  16186. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16191. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16192. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16193. if (generateMipMaps) {
  16194. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16195. }
  16196. // Unbind
  16197. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16198. texture._framebuffer = framebuffer;
  16199. texture._depthStencilBuffer = depthStencilBuffer;
  16200. texture.baseWidth = width;
  16201. texture.baseHeight = height;
  16202. texture.width = width;
  16203. texture.height = height;
  16204. texture.isReady = true;
  16205. texture.samples = 1;
  16206. texture.generateMipMaps = generateMipMaps;
  16207. texture.samplingMode = samplingMode;
  16208. texture.type = type;
  16209. texture._generateDepthBuffer = generateDepthBuffer;
  16210. texture._generateStencilBuffer = generateStencilBuffer;
  16211. texture._attachments = attachments;
  16212. this._internalTexturesCache.push(texture);
  16213. }
  16214. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16215. // Depth texture
  16216. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16217. gl.activeTexture(gl.TEXTURE0);
  16218. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16221. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16222. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16223. 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);
  16224. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16225. depthTexture._framebuffer = framebuffer;
  16226. depthTexture.baseWidth = width;
  16227. depthTexture.baseHeight = height;
  16228. depthTexture.width = width;
  16229. depthTexture.height = height;
  16230. depthTexture.isReady = true;
  16231. depthTexture.samples = 1;
  16232. depthTexture.generateMipMaps = generateMipMaps;
  16233. depthTexture.samplingMode = gl.NEAREST;
  16234. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16235. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16236. textures.push(depthTexture);
  16237. this._internalTexturesCache.push(depthTexture);
  16238. }
  16239. gl.drawBuffers(attachments);
  16240. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16241. this.bindUnboundFramebuffer(null);
  16242. this.resetTextureCache();
  16243. return textures;
  16244. };
  16245. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16246. if (samples === void 0) { samples = 1; }
  16247. var depthStencilBuffer = null;
  16248. var gl = this._gl;
  16249. // Create the depth/stencil buffer
  16250. if (generateStencilBuffer) {
  16251. depthStencilBuffer = gl.createRenderbuffer();
  16252. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16253. if (samples > 1) {
  16254. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16255. }
  16256. else {
  16257. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16258. }
  16259. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16260. }
  16261. else if (generateDepthBuffer) {
  16262. depthStencilBuffer = gl.createRenderbuffer();
  16263. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16264. if (samples > 1) {
  16265. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16266. }
  16267. else {
  16268. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16269. }
  16270. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16271. }
  16272. return depthStencilBuffer;
  16273. };
  16274. /**
  16275. * Updates the sample count of a render target texture
  16276. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16277. * @param texture defines the texture to update
  16278. * @param samples defines the sample count to set
  16279. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16280. */
  16281. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16282. if (this.webGLVersion < 2 || !texture) {
  16283. return 1;
  16284. }
  16285. if (texture.samples === samples) {
  16286. return samples;
  16287. }
  16288. var gl = this._gl;
  16289. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16290. // Dispose previous render buffers
  16291. if (texture._depthStencilBuffer) {
  16292. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16293. texture._depthStencilBuffer = null;
  16294. }
  16295. if (texture._MSAAFramebuffer) {
  16296. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16297. texture._MSAAFramebuffer = null;
  16298. }
  16299. if (texture._MSAARenderBuffer) {
  16300. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16301. texture._MSAARenderBuffer = null;
  16302. }
  16303. if (samples > 1) {
  16304. var framebuffer = gl.createFramebuffer();
  16305. if (!framebuffer) {
  16306. throw new Error("Unable to create multi sampled framebuffer");
  16307. }
  16308. texture._MSAAFramebuffer = framebuffer;
  16309. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16310. var colorRenderbuffer = gl.createRenderbuffer();
  16311. if (!colorRenderbuffer) {
  16312. throw new Error("Unable to create multi sampled framebuffer");
  16313. }
  16314. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16315. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16316. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16317. texture._MSAARenderBuffer = colorRenderbuffer;
  16318. }
  16319. else {
  16320. this.bindUnboundFramebuffer(texture._framebuffer);
  16321. }
  16322. texture.samples = samples;
  16323. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16324. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16325. this.bindUnboundFramebuffer(null);
  16326. return samples;
  16327. };
  16328. /**
  16329. * Update the sample count for a given multiple render target texture
  16330. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16331. * @param textures defines the textures to update
  16332. * @param samples defines the sample count to set
  16333. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16334. */
  16335. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16336. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16337. return 1;
  16338. }
  16339. if (textures[0].samples === samples) {
  16340. return samples;
  16341. }
  16342. var gl = this._gl;
  16343. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16344. // Dispose previous render buffers
  16345. if (textures[0]._depthStencilBuffer) {
  16346. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16347. textures[0]._depthStencilBuffer = null;
  16348. }
  16349. if (textures[0]._MSAAFramebuffer) {
  16350. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16351. textures[0]._MSAAFramebuffer = null;
  16352. }
  16353. for (var i = 0; i < textures.length; i++) {
  16354. if (textures[i]._MSAARenderBuffer) {
  16355. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16356. textures[i]._MSAARenderBuffer = null;
  16357. }
  16358. }
  16359. if (samples > 1) {
  16360. var framebuffer = gl.createFramebuffer();
  16361. if (!framebuffer) {
  16362. throw new Error("Unable to create multi sampled framebuffer");
  16363. }
  16364. this.bindUnboundFramebuffer(framebuffer);
  16365. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16366. var attachments = [];
  16367. for (var i = 0; i < textures.length; i++) {
  16368. var texture = textures[i];
  16369. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16370. var colorRenderbuffer = gl.createRenderbuffer();
  16371. if (!colorRenderbuffer) {
  16372. throw new Error("Unable to create multi sampled framebuffer");
  16373. }
  16374. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16375. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16376. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16377. texture._MSAAFramebuffer = framebuffer;
  16378. texture._MSAARenderBuffer = colorRenderbuffer;
  16379. texture.samples = samples;
  16380. texture._depthStencilBuffer = depthStencilBuffer;
  16381. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16382. attachments.push(attachment);
  16383. }
  16384. gl.drawBuffers(attachments);
  16385. }
  16386. else {
  16387. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16388. }
  16389. this.bindUnboundFramebuffer(null);
  16390. return samples;
  16391. };
  16392. /** @hidden */
  16393. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16394. if (faceIndex === void 0) { faceIndex = 0; }
  16395. if (lod === void 0) { lod = 0; }
  16396. var gl = this._gl;
  16397. var target = gl.TEXTURE_2D;
  16398. if (texture.isCube) {
  16399. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16400. }
  16401. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16402. };
  16403. /** @hidden */
  16404. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16405. if (faceIndex === void 0) { faceIndex = 0; }
  16406. if (lod === void 0) { lod = 0; }
  16407. var gl = this._gl;
  16408. var textureType = this._getWebGLTextureType(texture.type);
  16409. var format = this._getInternalFormat(texture.format);
  16410. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16411. this._unpackFlipY(texture.invertY);
  16412. var target = gl.TEXTURE_2D;
  16413. if (texture.isCube) {
  16414. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16415. }
  16416. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16417. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16418. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16419. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16420. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16421. };
  16422. /** @hidden */
  16423. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16424. if (faceIndex === void 0) { faceIndex = 0; }
  16425. if (lod === void 0) { lod = 0; }
  16426. var gl = this._gl;
  16427. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16428. this._bindTextureDirectly(bindTarget, texture, true);
  16429. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16430. this._bindTextureDirectly(bindTarget, null, true);
  16431. };
  16432. /** @hidden */
  16433. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16434. if (faceIndex === void 0) { faceIndex = 0; }
  16435. if (lod === void 0) { lod = 0; }
  16436. var gl = this._gl;
  16437. var textureType = this._getWebGLTextureType(texture.type);
  16438. var format = this._getInternalFormat(texture.format);
  16439. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16440. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16441. this._bindTextureDirectly(bindTarget, texture, true);
  16442. this._unpackFlipY(texture.invertY);
  16443. var target = gl.TEXTURE_2D;
  16444. if (texture.isCube) {
  16445. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16446. }
  16447. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16448. this._bindTextureDirectly(bindTarget, null, true);
  16449. };
  16450. /**
  16451. * Creates a new render target cube texture
  16452. * @param size defines the size of the texture
  16453. * @param options defines the options used to create the texture
  16454. * @returns a new render target cube texture stored in an InternalTexture
  16455. */
  16456. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16457. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16458. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16459. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16460. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16461. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16462. }
  16463. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16464. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16465. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16466. }
  16467. var gl = this._gl;
  16468. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16469. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16470. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16471. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16472. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16473. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16474. }
  16475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16479. for (var face = 0; face < 6; face++) {
  16480. 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);
  16481. }
  16482. // Create the framebuffer
  16483. var framebuffer = gl.createFramebuffer();
  16484. this.bindUnboundFramebuffer(framebuffer);
  16485. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16486. // MipMaps
  16487. if (fullOptions.generateMipMaps) {
  16488. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16489. }
  16490. // Unbind
  16491. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16492. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16493. this.bindUnboundFramebuffer(null);
  16494. texture._framebuffer = framebuffer;
  16495. texture.width = size;
  16496. texture.height = size;
  16497. texture.isReady = true;
  16498. texture.isCube = true;
  16499. texture.samples = 1;
  16500. texture.generateMipMaps = fullOptions.generateMipMaps;
  16501. texture.samplingMode = fullOptions.samplingMode;
  16502. texture.type = fullOptions.type;
  16503. texture.format = fullOptions.format;
  16504. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16505. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16506. this._internalTexturesCache.push(texture);
  16507. return texture;
  16508. };
  16509. /**
  16510. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16511. * @param rootUrl defines the url where the file to load is located
  16512. * @param scene defines the current scene
  16513. * @param lodScale defines scale to apply to the mip map selection
  16514. * @param lodOffset defines offset to apply to the mip map selection
  16515. * @param onLoad defines an optional callback raised when the texture is loaded
  16516. * @param onError defines an optional callback raised if there is an issue to load the texture
  16517. * @param format defines the format of the data
  16518. * @param forcedExtension defines the extension to use to pick the right loader
  16519. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16520. * @returns the cube texture as an InternalTexture
  16521. */
  16522. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16523. var _this = this;
  16524. if (onLoad === void 0) { onLoad = null; }
  16525. if (onError === void 0) { onError = null; }
  16526. if (forcedExtension === void 0) { forcedExtension = null; }
  16527. if (createPolynomials === void 0) { createPolynomials = true; }
  16528. var callback = function (loadData) {
  16529. if (!loadData) {
  16530. if (onLoad) {
  16531. onLoad(null);
  16532. }
  16533. return;
  16534. }
  16535. var texture = loadData.texture;
  16536. if (!createPolynomials) {
  16537. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16538. }
  16539. else if (loadData.info.sphericalPolynomial) {
  16540. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16541. }
  16542. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16543. if (_this._caps.textureLOD) {
  16544. // Do not add extra process if texture lod is supported.
  16545. if (onLoad) {
  16546. onLoad(texture);
  16547. }
  16548. return;
  16549. }
  16550. var mipSlices = 3;
  16551. var gl = _this._gl;
  16552. var width = loadData.width;
  16553. if (!width) {
  16554. return;
  16555. }
  16556. var textures = [];
  16557. for (var i = 0; i < mipSlices; i++) {
  16558. //compute LOD from even spacing in smoothness (matching shader calculation)
  16559. var smoothness = i / (mipSlices - 1);
  16560. var roughness = 1 - smoothness;
  16561. var minLODIndex = lodOffset; // roughness = 0
  16562. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16563. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16564. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16565. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16566. glTextureFromLod.type = texture.type;
  16567. glTextureFromLod.format = texture.format;
  16568. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16569. glTextureFromLod.height = glTextureFromLod.width;
  16570. glTextureFromLod.isCube = true;
  16571. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16576. if (loadData.isDDS) {
  16577. var info = loadData.info;
  16578. var data = loadData.data;
  16579. _this._unpackFlipY(info.isCompressed);
  16580. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16581. }
  16582. else {
  16583. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16584. }
  16585. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16586. // Wrap in a base texture for easy binding.
  16587. var lodTexture = new BABYLON.BaseTexture(scene);
  16588. lodTexture.isCube = true;
  16589. lodTexture._texture = glTextureFromLod;
  16590. glTextureFromLod.isReady = true;
  16591. textures.push(lodTexture);
  16592. }
  16593. texture._lodTextureHigh = textures[2];
  16594. texture._lodTextureMid = textures[1];
  16595. texture._lodTextureLow = textures[0];
  16596. if (onLoad) {
  16597. onLoad(texture);
  16598. }
  16599. };
  16600. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16601. };
  16602. /**
  16603. * Creates a cube texture
  16604. * @param rootUrl defines the url where the files to load is located
  16605. * @param scene defines the current scene
  16606. * @param files defines the list of files to load (1 per face)
  16607. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16608. * @param onLoad defines an optional callback raised when the texture is loaded
  16609. * @param onError defines an optional callback raised if there is an issue to load the texture
  16610. * @param format defines the format of the data
  16611. * @param forcedExtension defines the extension to use to pick the right loader
  16612. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16613. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16614. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16615. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16616. * @returns the cube texture as an InternalTexture
  16617. */
  16618. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16619. var _this = this;
  16620. if (onLoad === void 0) { onLoad = null; }
  16621. if (onError === void 0) { onError = null; }
  16622. if (forcedExtension === void 0) { forcedExtension = null; }
  16623. if (createPolynomials === void 0) { createPolynomials = false; }
  16624. if (lodScale === void 0) { lodScale = 0; }
  16625. if (lodOffset === void 0) { lodOffset = 0; }
  16626. if (fallback === void 0) { fallback = null; }
  16627. var gl = this._gl;
  16628. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16629. texture.isCube = true;
  16630. texture.url = rootUrl;
  16631. texture.generateMipMaps = !noMipmap;
  16632. texture._lodGenerationScale = lodScale;
  16633. texture._lodGenerationOffset = lodOffset;
  16634. if (!this._doNotHandleContextLost) {
  16635. texture._extension = forcedExtension;
  16636. texture._files = files;
  16637. }
  16638. var lastDot = rootUrl.lastIndexOf('.');
  16639. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16640. var loader = null;
  16641. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16642. var availableLoader = _a[_i];
  16643. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16644. loader = availableLoader;
  16645. break;
  16646. }
  16647. }
  16648. var onInternalError = function (request, exception) {
  16649. if (loader) {
  16650. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16651. if (fallbackUrl) {
  16652. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16653. }
  16654. }
  16655. if (onError && request) {
  16656. onError(request.status + " " + request.statusText, exception);
  16657. }
  16658. };
  16659. if (loader) {
  16660. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16661. var onloaddata = function (data) {
  16662. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16663. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16664. };
  16665. if (files && files.length === 6) {
  16666. if (loader.supportCascades) {
  16667. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16668. }
  16669. else if (onError) {
  16670. onError("Textures type does not support cascades.");
  16671. }
  16672. }
  16673. else {
  16674. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16675. }
  16676. }
  16677. else {
  16678. if (!files) {
  16679. throw new Error("Cannot load cubemap because files were not defined");
  16680. }
  16681. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16682. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16683. var height = width;
  16684. _this._prepareWorkingCanvas();
  16685. if (!_this._workingCanvas || !_this._workingContext) {
  16686. return;
  16687. }
  16688. _this._workingCanvas.width = width;
  16689. _this._workingCanvas.height = height;
  16690. var faces = [
  16691. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16692. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16693. ];
  16694. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16695. _this._unpackFlipY(false);
  16696. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16697. for (var index = 0; index < faces.length; index++) {
  16698. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16699. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16700. }
  16701. if (!noMipmap) {
  16702. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16703. }
  16704. _this._setCubeMapTextureParams(!noMipmap);
  16705. texture.width = width;
  16706. texture.height = height;
  16707. texture.isReady = true;
  16708. if (format) {
  16709. texture.format = format;
  16710. }
  16711. texture.onLoadedObservable.notifyObservers(texture);
  16712. texture.onLoadedObservable.clear();
  16713. if (onLoad) {
  16714. onLoad();
  16715. }
  16716. }, files, onError);
  16717. }
  16718. this._internalTexturesCache.push(texture);
  16719. return texture;
  16720. };
  16721. /**
  16722. * @hidden
  16723. */
  16724. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16725. var gl = this._gl;
  16726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16730. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16731. // this.resetTextureCache();
  16732. };
  16733. /**
  16734. * Update a raw cube texture
  16735. * @param texture defines the texture to udpdate
  16736. * @param data defines the data to store
  16737. * @param format defines the data format
  16738. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16739. * @param invertY defines if data must be stored with Y axis inverted
  16740. * @param compression defines the compression used (null by default)
  16741. * @param level defines which level of the texture to update
  16742. */
  16743. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16744. if (compression === void 0) { compression = null; }
  16745. if (level === void 0) { level = 0; }
  16746. texture._bufferViewArray = data;
  16747. texture.format = format;
  16748. texture.type = type;
  16749. texture.invertY = invertY;
  16750. texture._compression = compression;
  16751. var gl = this._gl;
  16752. var textureType = this._getWebGLTextureType(type);
  16753. var internalFormat = this._getInternalFormat(format);
  16754. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16755. var needConversion = false;
  16756. if (internalFormat === gl.RGB) {
  16757. internalFormat = gl.RGBA;
  16758. needConversion = true;
  16759. }
  16760. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16761. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16762. if (texture.width % 4 !== 0) {
  16763. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16764. }
  16765. // Data are known to be in +X +Y +Z -X -Y -Z
  16766. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16767. var faceData = data[faceIndex];
  16768. if (compression) {
  16769. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16770. }
  16771. else {
  16772. if (needConversion) {
  16773. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16774. }
  16775. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16776. }
  16777. }
  16778. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16779. if (isPot && texture.generateMipMaps && level === 0) {
  16780. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16781. }
  16782. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16783. // this.resetTextureCache();
  16784. texture.isReady = true;
  16785. };
  16786. /**
  16787. * Creates a new raw cube texture
  16788. * @param data defines the array of data to use to create each face
  16789. * @param size defines the size of the textures
  16790. * @param format defines the format of the data
  16791. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16792. * @param generateMipMaps defines if the engine should generate the mip levels
  16793. * @param invertY defines if data must be stored with Y axis inverted
  16794. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16795. * @param compression defines the compression used (null by default)
  16796. * @returns the cube texture as an InternalTexture
  16797. */
  16798. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16799. if (compression === void 0) { compression = null; }
  16800. var gl = this._gl;
  16801. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16802. texture.isCube = true;
  16803. texture.format = format;
  16804. texture.type = type;
  16805. if (!this._doNotHandleContextLost) {
  16806. texture._bufferViewArray = data;
  16807. }
  16808. var textureType = this._getWebGLTextureType(type);
  16809. var internalFormat = this._getInternalFormat(format);
  16810. if (internalFormat === gl.RGB) {
  16811. internalFormat = gl.RGBA;
  16812. }
  16813. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16814. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16815. generateMipMaps = false;
  16816. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16817. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16818. }
  16819. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16820. generateMipMaps = false;
  16821. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16822. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16823. }
  16824. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16825. generateMipMaps = false;
  16826. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16827. }
  16828. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16829. generateMipMaps = false;
  16830. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16831. }
  16832. var width = size;
  16833. var height = width;
  16834. texture.width = width;
  16835. texture.height = height;
  16836. // Double check on POT to generate Mips.
  16837. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16838. if (!isPot) {
  16839. generateMipMaps = false;
  16840. }
  16841. // Upload data if needed. The texture won't be ready until then.
  16842. if (data) {
  16843. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16844. }
  16845. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16846. // Filters
  16847. if (data && generateMipMaps) {
  16848. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16849. }
  16850. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16855. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16856. texture.generateMipMaps = generateMipMaps;
  16857. return texture;
  16858. };
  16859. /**
  16860. * Creates a new raw cube texture from a specified url
  16861. * @param url defines the url where the data is located
  16862. * @param scene defines the current scene
  16863. * @param size defines the size of the textures
  16864. * @param format defines the format of the data
  16865. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16866. * @param noMipmap defines if the engine should avoid generating the mip levels
  16867. * @param callback defines a callback used to extract texture data from loaded data
  16868. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16869. * @param onLoad defines a callback called when texture is loaded
  16870. * @param onError defines a callback called if there is an error
  16871. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16872. * @param invertY defines if data must be stored with Y axis inverted
  16873. * @returns the cube texture as an InternalTexture
  16874. */
  16875. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16876. var _this = this;
  16877. if (onLoad === void 0) { onLoad = null; }
  16878. if (onError === void 0) { onError = null; }
  16879. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16880. if (invertY === void 0) { invertY = false; }
  16881. var gl = this._gl;
  16882. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16883. scene._addPendingData(texture);
  16884. texture.url = url;
  16885. this._internalTexturesCache.push(texture);
  16886. var onerror = function (request, exception) {
  16887. scene._removePendingData(texture);
  16888. if (onError && request) {
  16889. onError(request.status + " " + request.statusText, exception);
  16890. }
  16891. };
  16892. var internalCallback = function (data) {
  16893. var width = texture.width;
  16894. var faceDataArrays = callback(data);
  16895. if (!faceDataArrays) {
  16896. return;
  16897. }
  16898. if (mipmapGenerator) {
  16899. var textureType = _this._getWebGLTextureType(type);
  16900. var internalFormat = _this._getInternalFormat(format);
  16901. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16902. var needConversion = false;
  16903. if (internalFormat === gl.RGB) {
  16904. internalFormat = gl.RGBA;
  16905. needConversion = true;
  16906. }
  16907. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16908. _this._unpackFlipY(false);
  16909. var mipData = mipmapGenerator(faceDataArrays);
  16910. for (var level = 0; level < mipData.length; level++) {
  16911. var mipSize = width >> level;
  16912. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16913. var mipFaceData = mipData[level][faceIndex];
  16914. if (needConversion) {
  16915. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16916. }
  16917. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16918. }
  16919. }
  16920. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16921. }
  16922. else {
  16923. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16924. }
  16925. texture.isReady = true;
  16926. // this.resetTextureCache();
  16927. scene._removePendingData(texture);
  16928. if (onLoad) {
  16929. onLoad();
  16930. }
  16931. };
  16932. this._loadFile(url, function (data) {
  16933. internalCallback(data);
  16934. }, undefined, scene.offlineProvider, true, onerror);
  16935. return texture;
  16936. };
  16937. /**
  16938. * Update a raw 3D texture
  16939. * @param texture defines the texture to update
  16940. * @param data defines the data to store
  16941. * @param format defines the data format
  16942. * @param invertY defines if data must be stored with Y axis inverted
  16943. * @param compression defines the used compression (can be null)
  16944. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16945. */
  16946. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16947. if (compression === void 0) { compression = null; }
  16948. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16949. var internalType = this._getWebGLTextureType(textureType);
  16950. var internalFormat = this._getInternalFormat(format);
  16951. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16952. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16953. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16954. if (!this._doNotHandleContextLost) {
  16955. texture._bufferView = data;
  16956. texture.format = format;
  16957. texture.invertY = invertY;
  16958. texture._compression = compression;
  16959. }
  16960. if (texture.width % 4 !== 0) {
  16961. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16962. }
  16963. if (compression && data) {
  16964. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16965. }
  16966. else {
  16967. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16968. }
  16969. if (texture.generateMipMaps) {
  16970. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16971. }
  16972. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16973. // this.resetTextureCache();
  16974. texture.isReady = true;
  16975. };
  16976. /**
  16977. * Creates a new raw 3D texture
  16978. * @param data defines the data used to create the texture
  16979. * @param width defines the width of the texture
  16980. * @param height defines the height of the texture
  16981. * @param depth defines the depth of the texture
  16982. * @param format defines the format of the texture
  16983. * @param generateMipMaps defines if the engine must generate mip levels
  16984. * @param invertY defines if data must be stored with Y axis inverted
  16985. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16986. * @param compression defines the compressed used (can be null)
  16987. * @param textureType defines the compressed used (can be null)
  16988. * @returns a new raw 3D texture (stored in an InternalTexture)
  16989. */
  16990. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16991. if (compression === void 0) { compression = null; }
  16992. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16993. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16994. texture.baseWidth = width;
  16995. texture.baseHeight = height;
  16996. texture.baseDepth = depth;
  16997. texture.width = width;
  16998. texture.height = height;
  16999. texture.depth = depth;
  17000. texture.format = format;
  17001. texture.type = textureType;
  17002. texture.generateMipMaps = generateMipMaps;
  17003. texture.samplingMode = samplingMode;
  17004. texture.is3D = true;
  17005. if (!this._doNotHandleContextLost) {
  17006. texture._bufferView = data;
  17007. }
  17008. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  17009. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17010. // Filters
  17011. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17012. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  17013. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  17014. if (generateMipMaps) {
  17015. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17016. }
  17017. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17018. this._internalTexturesCache.push(texture);
  17019. return texture;
  17020. };
  17021. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  17022. var gl = this._gl;
  17023. if (!gl) {
  17024. return;
  17025. }
  17026. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  17027. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  17028. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17029. if (!noMipmap && !isCompressed) {
  17030. gl.generateMipmap(gl.TEXTURE_2D);
  17031. }
  17032. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17033. // this.resetTextureCache();
  17034. if (scene) {
  17035. scene._removePendingData(texture);
  17036. }
  17037. texture.onLoadedObservable.notifyObservers(texture);
  17038. texture.onLoadedObservable.clear();
  17039. };
  17040. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17041. var _this = this;
  17042. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17043. var maxTextureSize = this.getCaps().maxTextureSize;
  17044. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17045. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17046. var gl = this._gl;
  17047. if (!gl) {
  17048. return;
  17049. }
  17050. if (!texture._webGLTexture) {
  17051. // this.resetTextureCache();
  17052. if (scene) {
  17053. scene._removePendingData(texture);
  17054. }
  17055. return;
  17056. }
  17057. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17058. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17059. texture.baseWidth = width;
  17060. texture.baseHeight = height;
  17061. texture.width = potWidth;
  17062. texture.height = potHeight;
  17063. texture.isReady = true;
  17064. if (processFunction(potWidth, potHeight, function () {
  17065. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17066. })) {
  17067. // Returning as texture needs extra async steps
  17068. return;
  17069. }
  17070. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17071. };
  17072. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17073. // Create new RGBA data container.
  17074. var rgbaData;
  17075. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17076. rgbaData = new Float32Array(width * height * 4);
  17077. }
  17078. else {
  17079. rgbaData = new Uint32Array(width * height * 4);
  17080. }
  17081. // Convert each pixel.
  17082. for (var x = 0; x < width; x++) {
  17083. for (var y = 0; y < height; y++) {
  17084. var index = (y * width + x) * 3;
  17085. var newIndex = (y * width + x) * 4;
  17086. // Map Old Value to new value.
  17087. rgbaData[newIndex + 0] = rgbData[index + 0];
  17088. rgbaData[newIndex + 1] = rgbData[index + 1];
  17089. rgbaData[newIndex + 2] = rgbData[index + 2];
  17090. // Add fully opaque alpha channel.
  17091. rgbaData[newIndex + 3] = 1;
  17092. }
  17093. }
  17094. return rgbaData;
  17095. };
  17096. /** @hidden */
  17097. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17098. var gl = this._gl;
  17099. if (texture._framebuffer) {
  17100. gl.deleteFramebuffer(texture._framebuffer);
  17101. texture._framebuffer = null;
  17102. }
  17103. if (texture._depthStencilBuffer) {
  17104. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17105. texture._depthStencilBuffer = null;
  17106. }
  17107. if (texture._MSAAFramebuffer) {
  17108. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17109. texture._MSAAFramebuffer = null;
  17110. }
  17111. if (texture._MSAARenderBuffer) {
  17112. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17113. texture._MSAARenderBuffer = null;
  17114. }
  17115. };
  17116. /** @hidden */
  17117. Engine.prototype._releaseTexture = function (texture) {
  17118. var gl = this._gl;
  17119. this._releaseFramebufferObjects(texture);
  17120. gl.deleteTexture(texture._webGLTexture);
  17121. // Unbind channels
  17122. this.unbindAllTextures();
  17123. var index = this._internalTexturesCache.indexOf(texture);
  17124. if (index !== -1) {
  17125. this._internalTexturesCache.splice(index, 1);
  17126. }
  17127. // Integrated fixed lod samplers.
  17128. if (texture._lodTextureHigh) {
  17129. texture._lodTextureHigh.dispose();
  17130. }
  17131. if (texture._lodTextureMid) {
  17132. texture._lodTextureMid.dispose();
  17133. }
  17134. if (texture._lodTextureLow) {
  17135. texture._lodTextureLow.dispose();
  17136. }
  17137. // Set output texture of post process to null if the texture has been released/disposed
  17138. this.scenes.forEach(function (scene) {
  17139. scene.postProcesses.forEach(function (postProcess) {
  17140. if (postProcess._outputTexture == texture) {
  17141. postProcess._outputTexture = null;
  17142. }
  17143. });
  17144. scene.cameras.forEach(function (camera) {
  17145. camera._postProcesses.forEach(function (postProcess) {
  17146. if (postProcess) {
  17147. if (postProcess._outputTexture == texture) {
  17148. postProcess._outputTexture = null;
  17149. }
  17150. }
  17151. });
  17152. });
  17153. });
  17154. };
  17155. Engine.prototype.setProgram = function (program) {
  17156. if (this._currentProgram !== program) {
  17157. this._gl.useProgram(program);
  17158. this._currentProgram = program;
  17159. }
  17160. };
  17161. /**
  17162. * Binds an effect to the webGL context
  17163. * @param effect defines the effect to bind
  17164. */
  17165. Engine.prototype.bindSamplers = function (effect) {
  17166. this.setProgram(effect.getProgram());
  17167. var samplers = effect.getSamplers();
  17168. for (var index = 0; index < samplers.length; index++) {
  17169. var uniform = effect.getUniform(samplers[index]);
  17170. if (uniform) {
  17171. this._boundUniforms[index] = uniform;
  17172. }
  17173. }
  17174. this._currentEffect = null;
  17175. };
  17176. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17177. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17178. return;
  17179. }
  17180. // Remove
  17181. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17182. // Bind last to it
  17183. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17184. // Bind to dummy
  17185. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17186. };
  17187. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17188. if (!internalTexture) {
  17189. return -1;
  17190. }
  17191. internalTexture._initialSlot = channel;
  17192. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17193. if (channel !== internalTexture._designatedSlot) {
  17194. this._textureCollisions.addCount(1, false);
  17195. }
  17196. }
  17197. else {
  17198. if (channel !== internalTexture._designatedSlot) {
  17199. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17200. return internalTexture._designatedSlot;
  17201. }
  17202. else {
  17203. // No slot for this texture, let's pick a new one (if we find a free slot)
  17204. if (this._nextFreeTextureSlots.length) {
  17205. return this._nextFreeTextureSlots[0];
  17206. }
  17207. // We need to recycle the oldest bound texture, sorry.
  17208. this._textureCollisions.addCount(1, false);
  17209. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17210. }
  17211. }
  17212. }
  17213. return channel;
  17214. };
  17215. Engine.prototype._linkTrackers = function (previous, next) {
  17216. previous.next = next;
  17217. next.previous = previous;
  17218. };
  17219. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17220. var currentSlot = internalTexture._designatedSlot;
  17221. if (currentSlot === -1) {
  17222. return -1;
  17223. }
  17224. internalTexture._designatedSlot = -1;
  17225. if (this.disableTextureBindingOptimization) {
  17226. return -1;
  17227. }
  17228. // Remove from bound list
  17229. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17230. // Free the slot
  17231. this._boundTexturesCache[currentSlot] = null;
  17232. this._nextFreeTextureSlots.push(currentSlot);
  17233. return currentSlot;
  17234. };
  17235. Engine.prototype._activateCurrentTexture = function () {
  17236. if (this._currentTextureChannel !== this._activeChannel) {
  17237. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17238. this._currentTextureChannel = this._activeChannel;
  17239. }
  17240. };
  17241. /** @hidden */
  17242. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17243. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17244. if (force === void 0) { force = false; }
  17245. var wasPreviouslyBound = false;
  17246. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17247. this._activeChannel = texture._designatedSlot;
  17248. }
  17249. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17250. var isTextureForRendering = texture && texture._initialSlot > -1;
  17251. if (currentTextureBound !== texture || force) {
  17252. if (currentTextureBound) {
  17253. this._removeDesignatedSlot(currentTextureBound);
  17254. }
  17255. this._activateCurrentTexture();
  17256. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17257. this._boundTexturesCache[this._activeChannel] = texture;
  17258. if (texture) {
  17259. if (!this.disableTextureBindingOptimization) {
  17260. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17261. if (slotIndex > -1) {
  17262. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17263. }
  17264. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17265. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17266. }
  17267. texture._designatedSlot = this._activeChannel;
  17268. }
  17269. }
  17270. else if (forTextureDataUpdate) {
  17271. wasPreviouslyBound = true;
  17272. this._activateCurrentTexture();
  17273. }
  17274. if (isTextureForRendering && !forTextureDataUpdate) {
  17275. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17276. }
  17277. return wasPreviouslyBound;
  17278. };
  17279. /** @hidden */
  17280. Engine.prototype._bindTexture = function (channel, texture) {
  17281. if (channel < 0) {
  17282. return;
  17283. }
  17284. if (texture) {
  17285. channel = this._getCorrectTextureChannel(channel, texture);
  17286. }
  17287. this._activeChannel = channel;
  17288. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17289. };
  17290. /**
  17291. * Sets a texture to the webGL context from a postprocess
  17292. * @param channel defines the channel to use
  17293. * @param postProcess defines the source postprocess
  17294. */
  17295. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17296. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17297. };
  17298. /**
  17299. * Binds the output of the passed in post process to the texture channel specified
  17300. * @param channel The channel the texture should be bound to
  17301. * @param postProcess The post process which's output should be bound
  17302. */
  17303. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17304. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17305. };
  17306. /**
  17307. * Unbind all textures from the webGL context
  17308. */
  17309. Engine.prototype.unbindAllTextures = function () {
  17310. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17311. this._activeChannel = channel;
  17312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17313. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17314. if (this.webGLVersion > 1) {
  17315. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17316. }
  17317. }
  17318. };
  17319. /**
  17320. * Sets a texture to the according uniform.
  17321. * @param channel The texture channel
  17322. * @param uniform The uniform to set
  17323. * @param texture The texture to apply
  17324. */
  17325. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17326. if (channel < 0) {
  17327. return;
  17328. }
  17329. if (uniform) {
  17330. this._boundUniforms[channel] = uniform;
  17331. }
  17332. this._setTexture(channel, texture);
  17333. };
  17334. /**
  17335. * Sets a depth stencil texture from a render target to the according uniform.
  17336. * @param channel The texture channel
  17337. * @param uniform The uniform to set
  17338. * @param texture The render target texture containing the depth stencil texture to apply
  17339. */
  17340. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17341. if (channel < 0) {
  17342. return;
  17343. }
  17344. if (uniform) {
  17345. this._boundUniforms[channel] = uniform;
  17346. }
  17347. if (!texture || !texture.depthStencilTexture) {
  17348. this._setTexture(channel, null);
  17349. }
  17350. else {
  17351. this._setTexture(channel, texture, false, true);
  17352. }
  17353. };
  17354. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17355. var uniform = this._boundUniforms[sourceSlot];
  17356. if (uniform._currentState === destination) {
  17357. return;
  17358. }
  17359. this._gl.uniform1i(uniform, destination);
  17360. uniform._currentState = destination;
  17361. };
  17362. Engine.prototype._getTextureWrapMode = function (mode) {
  17363. switch (mode) {
  17364. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17365. return this._gl.REPEAT;
  17366. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17367. return this._gl.CLAMP_TO_EDGE;
  17368. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17369. return this._gl.MIRRORED_REPEAT;
  17370. }
  17371. return this._gl.REPEAT;
  17372. };
  17373. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17374. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17375. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17376. // Not ready?
  17377. if (!texture) {
  17378. if (this._boundTexturesCache[channel] != null) {
  17379. this._activeChannel = channel;
  17380. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17381. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17382. if (this.webGLVersion > 1) {
  17383. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17384. }
  17385. }
  17386. return false;
  17387. }
  17388. // Video
  17389. if (texture.video) {
  17390. this._activeChannel = channel;
  17391. texture.update();
  17392. }
  17393. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17394. texture.delayLoad();
  17395. return false;
  17396. }
  17397. var internalTexture;
  17398. if (depthStencilTexture) {
  17399. internalTexture = texture.depthStencilTexture;
  17400. }
  17401. else if (texture.isReady()) {
  17402. internalTexture = texture.getInternalTexture();
  17403. }
  17404. else if (texture.isCube) {
  17405. internalTexture = this.emptyCubeTexture;
  17406. }
  17407. else if (texture.is3D) {
  17408. internalTexture = this.emptyTexture3D;
  17409. }
  17410. else {
  17411. internalTexture = this.emptyTexture;
  17412. }
  17413. if (!isPartOfTextureArray) {
  17414. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17415. }
  17416. var needToBind = true;
  17417. if (this._boundTexturesCache[channel] === internalTexture) {
  17418. this._moveBoundTextureOnTop(internalTexture);
  17419. if (!isPartOfTextureArray) {
  17420. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17421. }
  17422. needToBind = false;
  17423. }
  17424. this._activeChannel = channel;
  17425. if (internalTexture && internalTexture.is3D) {
  17426. if (needToBind) {
  17427. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17428. }
  17429. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17430. internalTexture._cachedWrapU = texture.wrapU;
  17431. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17432. }
  17433. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17434. internalTexture._cachedWrapV = texture.wrapV;
  17435. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17436. }
  17437. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17438. internalTexture._cachedWrapR = texture.wrapR;
  17439. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17440. }
  17441. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17442. }
  17443. else if (internalTexture && internalTexture.isCube) {
  17444. if (needToBind) {
  17445. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17446. }
  17447. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17448. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17449. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17450. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17451. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17452. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17453. }
  17454. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17455. }
  17456. else {
  17457. if (needToBind) {
  17458. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17459. }
  17460. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17461. internalTexture._cachedWrapU = texture.wrapU;
  17462. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17463. }
  17464. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17465. internalTexture._cachedWrapV = texture.wrapV;
  17466. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17467. }
  17468. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17469. }
  17470. return true;
  17471. };
  17472. /**
  17473. * Sets an array of texture to the webGL context
  17474. * @param channel defines the channel where the texture array must be set
  17475. * @param uniform defines the associated uniform location
  17476. * @param textures defines the array of textures to bind
  17477. */
  17478. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17479. if (channel < 0 || !uniform) {
  17480. return;
  17481. }
  17482. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17483. this._textureUnits = new Int32Array(textures.length);
  17484. }
  17485. for (var i = 0; i < textures.length; i++) {
  17486. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17487. }
  17488. this._gl.uniform1iv(uniform, this._textureUnits);
  17489. for (var index = 0; index < textures.length; index++) {
  17490. this._setTexture(this._textureUnits[index], textures[index], true);
  17491. }
  17492. };
  17493. /** @hidden */
  17494. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17495. var internalTexture = texture.getInternalTexture();
  17496. if (!internalTexture) {
  17497. return;
  17498. }
  17499. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17500. var value = texture.anisotropicFilteringLevel;
  17501. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17502. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17503. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17504. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17505. }
  17506. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17507. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17508. internalTexture._cachedAnisotropicFilteringLevel = value;
  17509. }
  17510. };
  17511. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17512. this._bindTextureDirectly(target, texture, true, true);
  17513. this._gl.texParameterf(target, parameter, value);
  17514. };
  17515. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17516. if (texture) {
  17517. this._bindTextureDirectly(target, texture, true, true);
  17518. }
  17519. this._gl.texParameteri(target, parameter, value);
  17520. };
  17521. /**
  17522. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17523. * @param x defines the x coordinate of the rectangle where pixels must be read
  17524. * @param y defines the y coordinate of the rectangle where pixels must be read
  17525. * @param width defines the width of the rectangle where pixels must be read
  17526. * @param height defines the height of the rectangle where pixels must be read
  17527. * @returns a Uint8Array containing RGBA colors
  17528. */
  17529. Engine.prototype.readPixels = function (x, y, width, height) {
  17530. var data = new Uint8Array(height * width * 4);
  17531. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17532. return data;
  17533. };
  17534. /**
  17535. * Add an externaly attached data from its key.
  17536. * This method call will fail and return false, if such key already exists.
  17537. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17538. * @param key the unique key that identifies the data
  17539. * @param data the data object to associate to the key for this Engine instance
  17540. * @return true if no such key were already present and the data was added successfully, false otherwise
  17541. */
  17542. Engine.prototype.addExternalData = function (key, data) {
  17543. if (!this._externalData) {
  17544. this._externalData = new BABYLON.StringDictionary();
  17545. }
  17546. return this._externalData.add(key, data);
  17547. };
  17548. /**
  17549. * Get an externaly attached data from its key
  17550. * @param key the unique key that identifies the data
  17551. * @return the associated data, if present (can be null), or undefined if not present
  17552. */
  17553. Engine.prototype.getExternalData = function (key) {
  17554. if (!this._externalData) {
  17555. this._externalData = new BABYLON.StringDictionary();
  17556. }
  17557. return this._externalData.get(key);
  17558. };
  17559. /**
  17560. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17561. * @param key the unique key that identifies the data
  17562. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17563. * @return the associated data, can be null if the factory returned null.
  17564. */
  17565. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17566. if (!this._externalData) {
  17567. this._externalData = new BABYLON.StringDictionary();
  17568. }
  17569. return this._externalData.getOrAddWithFactory(key, factory);
  17570. };
  17571. /**
  17572. * Remove an externaly attached data from the Engine instance
  17573. * @param key the unique key that identifies the data
  17574. * @return true if the data was successfully removed, false if it doesn't exist
  17575. */
  17576. Engine.prototype.removeExternalData = function (key) {
  17577. if (!this._externalData) {
  17578. this._externalData = new BABYLON.StringDictionary();
  17579. }
  17580. return this._externalData.remove(key);
  17581. };
  17582. /**
  17583. * Unbind all vertex attributes from the webGL context
  17584. */
  17585. Engine.prototype.unbindAllAttributes = function () {
  17586. if (this._mustWipeVertexAttributes) {
  17587. this._mustWipeVertexAttributes = false;
  17588. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17589. this._gl.disableVertexAttribArray(i);
  17590. this._vertexAttribArraysEnabled[i] = false;
  17591. this._currentBufferPointers[i].active = false;
  17592. }
  17593. return;
  17594. }
  17595. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17596. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17597. continue;
  17598. }
  17599. this._gl.disableVertexAttribArray(i);
  17600. this._vertexAttribArraysEnabled[i] = false;
  17601. this._currentBufferPointers[i].active = false;
  17602. }
  17603. };
  17604. /**
  17605. * 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
  17606. */
  17607. Engine.prototype.releaseEffects = function () {
  17608. for (var name in this._compiledEffects) {
  17609. this._deleteProgram(this._compiledEffects[name]._program);
  17610. }
  17611. this._compiledEffects = {};
  17612. };
  17613. /**
  17614. * Dispose and release all associated resources
  17615. */
  17616. Engine.prototype.dispose = function () {
  17617. this.hideLoadingUI();
  17618. this.stopRenderLoop();
  17619. // Release postProcesses
  17620. while (this.postProcesses.length) {
  17621. this.postProcesses[0].dispose();
  17622. }
  17623. // Empty texture
  17624. if (this._emptyTexture) {
  17625. this._releaseTexture(this._emptyTexture);
  17626. this._emptyTexture = null;
  17627. }
  17628. if (this._emptyCubeTexture) {
  17629. this._releaseTexture(this._emptyCubeTexture);
  17630. this._emptyCubeTexture = null;
  17631. }
  17632. // Rescale PP
  17633. if (this._rescalePostProcess) {
  17634. this._rescalePostProcess.dispose();
  17635. }
  17636. // Release scenes
  17637. while (this.scenes.length) {
  17638. this.scenes[0].dispose();
  17639. }
  17640. // Release audio engine
  17641. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17642. Engine.audioEngine.dispose();
  17643. }
  17644. // Release effects
  17645. this.releaseEffects();
  17646. // Unbind
  17647. this.unbindAllAttributes();
  17648. this._boundUniforms = [];
  17649. if (this._dummyFramebuffer) {
  17650. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17651. }
  17652. //WebVR
  17653. this.disableVR();
  17654. // Events
  17655. if (BABYLON.Tools.IsWindowObjectExist()) {
  17656. window.removeEventListener("blur", this._onBlur);
  17657. window.removeEventListener("focus", this._onFocus);
  17658. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17659. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17660. if (this._renderingCanvas) {
  17661. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17662. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17663. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17664. if (!this._doNotHandleContextLost) {
  17665. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17666. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17667. }
  17668. }
  17669. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17670. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17671. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17672. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17673. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17674. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17675. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17676. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17677. if (this._onVrDisplayConnect) {
  17678. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17679. if (this._onVrDisplayDisconnect) {
  17680. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17681. }
  17682. if (this._onVrDisplayPresentChange) {
  17683. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17684. }
  17685. this._onVrDisplayConnect = null;
  17686. this._onVrDisplayDisconnect = null;
  17687. }
  17688. }
  17689. // Remove from Instances
  17690. var index = Engine.Instances.indexOf(this);
  17691. if (index >= 0) {
  17692. Engine.Instances.splice(index, 1);
  17693. }
  17694. this._workingCanvas = null;
  17695. this._workingContext = null;
  17696. this._currentBufferPointers = [];
  17697. this._renderingCanvas = null;
  17698. this._currentProgram = null;
  17699. this._bindedRenderFunction = null;
  17700. this.onResizeObservable.clear();
  17701. this.onCanvasBlurObservable.clear();
  17702. this.onCanvasFocusObservable.clear();
  17703. this.onCanvasPointerOutObservable.clear();
  17704. this.onBeginFrameObservable.clear();
  17705. this.onEndFrameObservable.clear();
  17706. BABYLON.Effect.ResetCache();
  17707. // Abort active requests
  17708. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17709. var request = _a[_i];
  17710. request.abort();
  17711. }
  17712. };
  17713. // Loading screen
  17714. /**
  17715. * Display the loading screen
  17716. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17717. */
  17718. Engine.prototype.displayLoadingUI = function () {
  17719. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17720. return;
  17721. }
  17722. var loadingScreen = this.loadingScreen;
  17723. if (loadingScreen) {
  17724. loadingScreen.displayLoadingUI();
  17725. }
  17726. };
  17727. /**
  17728. * Hide the loading screen
  17729. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17730. */
  17731. Engine.prototype.hideLoadingUI = function () {
  17732. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17733. return;
  17734. }
  17735. var loadingScreen = this.loadingScreen;
  17736. if (loadingScreen) {
  17737. loadingScreen.hideLoadingUI();
  17738. }
  17739. };
  17740. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17741. /**
  17742. * Gets the current loading screen object
  17743. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17744. */
  17745. get: function () {
  17746. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17747. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17748. }
  17749. return this._loadingScreen;
  17750. },
  17751. /**
  17752. * Sets the current loading screen object
  17753. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17754. */
  17755. set: function (loadingScreen) {
  17756. this._loadingScreen = loadingScreen;
  17757. },
  17758. enumerable: true,
  17759. configurable: true
  17760. });
  17761. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17762. /**
  17763. * Sets the current loading screen text
  17764. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17765. */
  17766. set: function (text) {
  17767. this.loadingScreen.loadingUIText = text;
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17773. /**
  17774. * Sets the current loading screen background color
  17775. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17776. */
  17777. set: function (color) {
  17778. this.loadingScreen.loadingUIBackgroundColor = color;
  17779. },
  17780. enumerable: true,
  17781. configurable: true
  17782. });
  17783. /**
  17784. * Attach a new callback raised when context lost event is fired
  17785. * @param callback defines the callback to call
  17786. */
  17787. Engine.prototype.attachContextLostEvent = function (callback) {
  17788. if (this._renderingCanvas) {
  17789. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17790. }
  17791. };
  17792. /**
  17793. * Attach a new callback raised when context restored event is fired
  17794. * @param callback defines the callback to call
  17795. */
  17796. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17797. if (this._renderingCanvas) {
  17798. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17799. }
  17800. };
  17801. /**
  17802. * Gets the source code of the vertex shader associated with a specific webGL program
  17803. * @param program defines the program to use
  17804. * @returns a string containing the source code of the vertex shader associated with the program
  17805. */
  17806. Engine.prototype.getVertexShaderSource = function (program) {
  17807. var shaders = this._gl.getAttachedShaders(program);
  17808. if (!shaders) {
  17809. return null;
  17810. }
  17811. return this._gl.getShaderSource(shaders[0]);
  17812. };
  17813. /**
  17814. * Gets the source code of the fragment shader associated with a specific webGL program
  17815. * @param program defines the program to use
  17816. * @returns a string containing the source code of the fragment shader associated with the program
  17817. */
  17818. Engine.prototype.getFragmentShaderSource = function (program) {
  17819. var shaders = this._gl.getAttachedShaders(program);
  17820. if (!shaders) {
  17821. return null;
  17822. }
  17823. return this._gl.getShaderSource(shaders[1]);
  17824. };
  17825. /**
  17826. * Get the current error code of the webGL context
  17827. * @returns the error code
  17828. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17829. */
  17830. Engine.prototype.getError = function () {
  17831. return this._gl.getError();
  17832. };
  17833. // FPS
  17834. /**
  17835. * Gets the current framerate
  17836. * @returns a number representing the framerate
  17837. */
  17838. Engine.prototype.getFps = function () {
  17839. return this._fps;
  17840. };
  17841. /**
  17842. * Gets the time spent between current and previous frame
  17843. * @returns a number representing the delta time in ms
  17844. */
  17845. Engine.prototype.getDeltaTime = function () {
  17846. return this._deltaTime;
  17847. };
  17848. Engine.prototype._measureFps = function () {
  17849. this._performanceMonitor.sampleFrame();
  17850. this._fps = this._performanceMonitor.averageFPS;
  17851. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17852. };
  17853. /** @hidden */
  17854. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17855. if (faceIndex === void 0) { faceIndex = -1; }
  17856. if (level === void 0) { level = 0; }
  17857. if (buffer === void 0) { buffer = null; }
  17858. var gl = this._gl;
  17859. if (!this._dummyFramebuffer) {
  17860. var dummy = gl.createFramebuffer();
  17861. if (!dummy) {
  17862. throw new Error("Unable to create dummy framebuffer");
  17863. }
  17864. this._dummyFramebuffer = dummy;
  17865. }
  17866. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17867. if (faceIndex > -1) {
  17868. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17869. }
  17870. else {
  17871. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17872. }
  17873. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17874. switch (readType) {
  17875. case gl.UNSIGNED_BYTE:
  17876. if (!buffer) {
  17877. buffer = new Uint8Array(4 * width * height);
  17878. }
  17879. readType = gl.UNSIGNED_BYTE;
  17880. break;
  17881. default:
  17882. if (!buffer) {
  17883. buffer = new Float32Array(4 * width * height);
  17884. }
  17885. readType = gl.FLOAT;
  17886. break;
  17887. }
  17888. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17889. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17890. return buffer;
  17891. };
  17892. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17893. if (this._webGLVersion > 1) {
  17894. return this._caps.colorBufferFloat;
  17895. }
  17896. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17897. };
  17898. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17899. if (this._webGLVersion > 1) {
  17900. return this._caps.colorBufferFloat;
  17901. }
  17902. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17903. };
  17904. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17905. Engine.prototype._canRenderToFramebuffer = function (type) {
  17906. var gl = this._gl;
  17907. //clear existing errors
  17908. while (gl.getError() !== gl.NO_ERROR) { }
  17909. var successful = true;
  17910. var texture = gl.createTexture();
  17911. gl.bindTexture(gl.TEXTURE_2D, texture);
  17912. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17915. var fb = gl.createFramebuffer();
  17916. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17917. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17918. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17919. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17920. successful = successful && (gl.getError() === gl.NO_ERROR);
  17921. //try render by clearing frame buffer's color buffer
  17922. if (successful) {
  17923. gl.clear(gl.COLOR_BUFFER_BIT);
  17924. successful = successful && (gl.getError() === gl.NO_ERROR);
  17925. }
  17926. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17927. if (successful) {
  17928. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17929. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17930. var readFormat = gl.RGBA;
  17931. var readType = gl.UNSIGNED_BYTE;
  17932. var buffer = new Uint8Array(4);
  17933. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17934. successful = successful && (gl.getError() === gl.NO_ERROR);
  17935. }
  17936. //clean up
  17937. gl.deleteTexture(texture);
  17938. gl.deleteFramebuffer(fb);
  17939. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17940. //clear accumulated errors
  17941. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17942. return successful;
  17943. };
  17944. /** @hidden */
  17945. Engine.prototype._getWebGLTextureType = function (type) {
  17946. if (this._webGLVersion === 1) {
  17947. switch (type) {
  17948. case Engine.TEXTURETYPE_FLOAT:
  17949. return this._gl.FLOAT;
  17950. case Engine.TEXTURETYPE_HALF_FLOAT:
  17951. return this._gl.HALF_FLOAT_OES;
  17952. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17953. return this._gl.UNSIGNED_BYTE;
  17954. }
  17955. return this._gl.UNSIGNED_BYTE;
  17956. }
  17957. switch (type) {
  17958. case Engine.TEXTURETYPE_BYTE:
  17959. return this._gl.BYTE;
  17960. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17961. return this._gl.UNSIGNED_BYTE;
  17962. case Engine.TEXTURETYPE_SHORT:
  17963. return this._gl.SHORT;
  17964. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17965. return this._gl.UNSIGNED_SHORT;
  17966. case Engine.TEXTURETYPE_INT:
  17967. return this._gl.INT;
  17968. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17969. return this._gl.UNSIGNED_INT;
  17970. case Engine.TEXTURETYPE_FLOAT:
  17971. return this._gl.FLOAT;
  17972. case Engine.TEXTURETYPE_HALF_FLOAT:
  17973. return this._gl.HALF_FLOAT;
  17974. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17975. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17976. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17977. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17978. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17979. return this._gl.UNSIGNED_SHORT_5_6_5;
  17980. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17981. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17982. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17983. return this._gl.UNSIGNED_INT_24_8;
  17984. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17985. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17986. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17987. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17988. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17989. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17990. }
  17991. return this._gl.UNSIGNED_BYTE;
  17992. };
  17993. Engine.prototype._getInternalFormat = function (format) {
  17994. var internalFormat = this._gl.RGBA;
  17995. switch (format) {
  17996. case Engine.TEXTUREFORMAT_ALPHA:
  17997. internalFormat = this._gl.ALPHA;
  17998. break;
  17999. case Engine.TEXTUREFORMAT_LUMINANCE:
  18000. internalFormat = this._gl.LUMINANCE;
  18001. break;
  18002. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18003. internalFormat = this._gl.LUMINANCE_ALPHA;
  18004. break;
  18005. case Engine.TEXTUREFORMAT_RED:
  18006. internalFormat = this._gl.RED;
  18007. break;
  18008. case Engine.TEXTUREFORMAT_RG:
  18009. internalFormat = this._gl.RG;
  18010. break;
  18011. case Engine.TEXTUREFORMAT_RGB:
  18012. internalFormat = this._gl.RGB;
  18013. break;
  18014. case Engine.TEXTUREFORMAT_RGBA:
  18015. internalFormat = this._gl.RGBA;
  18016. break;
  18017. }
  18018. if (this._webGLVersion > 1) {
  18019. switch (format) {
  18020. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18021. internalFormat = this._gl.RED_INTEGER;
  18022. break;
  18023. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18024. internalFormat = this._gl.RG_INTEGER;
  18025. break;
  18026. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18027. internalFormat = this._gl.RGB_INTEGER;
  18028. break;
  18029. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18030. internalFormat = this._gl.RGBA_INTEGER;
  18031. break;
  18032. }
  18033. }
  18034. return internalFormat;
  18035. };
  18036. /** @hidden */
  18037. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18038. if (this._webGLVersion === 1) {
  18039. if (format !== undefined) {
  18040. switch (format) {
  18041. case Engine.TEXTUREFORMAT_ALPHA:
  18042. return this._gl.ALPHA;
  18043. case Engine.TEXTUREFORMAT_LUMINANCE:
  18044. return this._gl.LUMINANCE;
  18045. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18046. return this._gl.LUMINANCE_ALPHA;
  18047. }
  18048. }
  18049. return this._gl.RGBA;
  18050. }
  18051. switch (type) {
  18052. case Engine.TEXTURETYPE_BYTE:
  18053. switch (format) {
  18054. case Engine.TEXTUREFORMAT_RED:
  18055. return this._gl.R8_SNORM;
  18056. case Engine.TEXTUREFORMAT_RG:
  18057. return this._gl.RG8_SNORM;
  18058. case Engine.TEXTUREFORMAT_RGB:
  18059. return this._gl.RGB8_SNORM;
  18060. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18061. return this._gl.R8I;
  18062. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18063. return this._gl.RG8I;
  18064. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18065. return this._gl.RGB8I;
  18066. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18067. return this._gl.RGBA8I;
  18068. default:
  18069. return this._gl.RGBA8_SNORM;
  18070. }
  18071. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18072. switch (format) {
  18073. case Engine.TEXTUREFORMAT_RED:
  18074. return this._gl.R8;
  18075. case Engine.TEXTUREFORMAT_RG:
  18076. return this._gl.RG8;
  18077. case Engine.TEXTUREFORMAT_RGB:
  18078. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18079. case Engine.TEXTUREFORMAT_RGBA:
  18080. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18081. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18082. return this._gl.R8UI;
  18083. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18084. return this._gl.RG8UI;
  18085. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18086. return this._gl.RGB8UI;
  18087. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18088. return this._gl.RGBA8UI;
  18089. default:
  18090. return this._gl.RGBA8;
  18091. }
  18092. case Engine.TEXTURETYPE_SHORT:
  18093. switch (format) {
  18094. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18095. return this._gl.R16I;
  18096. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18097. return this._gl.RG16I;
  18098. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18099. return this._gl.RGB16I;
  18100. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18101. return this._gl.RGBA16I;
  18102. default:
  18103. return this._gl.RGBA16I;
  18104. }
  18105. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18106. switch (format) {
  18107. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18108. return this._gl.R16UI;
  18109. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18110. return this._gl.RG16UI;
  18111. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18112. return this._gl.RGB16UI;
  18113. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18114. return this._gl.RGBA16UI;
  18115. default:
  18116. return this._gl.RGBA16UI;
  18117. }
  18118. case Engine.TEXTURETYPE_INT:
  18119. switch (format) {
  18120. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18121. return this._gl.R32I;
  18122. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18123. return this._gl.RG32I;
  18124. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18125. return this._gl.RGB32I;
  18126. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18127. return this._gl.RGBA32I;
  18128. default:
  18129. return this._gl.RGBA32I;
  18130. }
  18131. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18132. switch (format) {
  18133. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18134. return this._gl.R32UI;
  18135. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18136. return this._gl.RG32UI;
  18137. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18138. return this._gl.RGB32UI;
  18139. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18140. return this._gl.RGBA32UI;
  18141. default:
  18142. return this._gl.RGBA32UI;
  18143. }
  18144. case Engine.TEXTURETYPE_FLOAT:
  18145. switch (format) {
  18146. case Engine.TEXTUREFORMAT_RED:
  18147. return this._gl.R32F; // By default. Other possibility is R16F.
  18148. case Engine.TEXTUREFORMAT_RG:
  18149. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18150. case Engine.TEXTUREFORMAT_RGB:
  18151. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18152. case Engine.TEXTUREFORMAT_RGBA:
  18153. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18154. default:
  18155. return this._gl.RGBA32F;
  18156. }
  18157. case Engine.TEXTURETYPE_HALF_FLOAT:
  18158. switch (format) {
  18159. case Engine.TEXTUREFORMAT_RED:
  18160. return this._gl.R16F;
  18161. case Engine.TEXTUREFORMAT_RG:
  18162. return this._gl.RG16F;
  18163. case Engine.TEXTUREFORMAT_RGB:
  18164. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18165. case Engine.TEXTUREFORMAT_RGBA:
  18166. return this._gl.RGBA16F;
  18167. default:
  18168. return this._gl.RGBA16F;
  18169. }
  18170. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18171. return this._gl.RGB565;
  18172. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18173. return this._gl.R11F_G11F_B10F;
  18174. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18175. return this._gl.RGB9_E5;
  18176. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18177. return this._gl.RGBA4;
  18178. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18179. return this._gl.RGB5_A1;
  18180. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18181. switch (format) {
  18182. case Engine.TEXTUREFORMAT_RGBA:
  18183. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18184. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18185. return this._gl.RGB10_A2UI;
  18186. default:
  18187. return this._gl.RGB10_A2;
  18188. }
  18189. }
  18190. return this._gl.RGBA8;
  18191. };
  18192. /** @hidden */
  18193. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18194. if (type === Engine.TEXTURETYPE_FLOAT) {
  18195. return this._gl.RGBA32F;
  18196. }
  18197. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18198. return this._gl.RGBA16F;
  18199. }
  18200. return this._gl.RGBA8;
  18201. };
  18202. /** @hidden */
  18203. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18204. var _this = this;
  18205. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18206. this._activeRequests.push(request);
  18207. request.onCompleteObservable.add(function (request) {
  18208. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18209. });
  18210. return request;
  18211. };
  18212. /** @hidden */
  18213. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18214. var _this = this;
  18215. return new Promise(function (resolve, reject) {
  18216. _this._loadFile(url, function (data) {
  18217. resolve(data);
  18218. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18219. reject(exception);
  18220. });
  18221. });
  18222. };
  18223. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18224. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18225. var onload = function (data) {
  18226. loadedFiles[index] = data;
  18227. loadedFiles._internalCount++;
  18228. if (loadedFiles._internalCount === 6) {
  18229. onfinish(loadedFiles);
  18230. }
  18231. };
  18232. var onerror = function (request, exception) {
  18233. if (onErrorCallBack && request) {
  18234. onErrorCallBack(request.status + " " + request.statusText, exception);
  18235. }
  18236. };
  18237. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18238. };
  18239. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18240. if (onError === void 0) { onError = null; }
  18241. var loadedFiles = [];
  18242. loadedFiles._internalCount = 0;
  18243. for (var index = 0; index < 6; index++) {
  18244. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18245. }
  18246. };
  18247. // Statics
  18248. /**
  18249. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18250. * @returns true if the engine can be created
  18251. * @ignorenaming
  18252. */
  18253. Engine.isSupported = function () {
  18254. try {
  18255. var tempcanvas = document.createElement("canvas");
  18256. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18257. return gl != null && !!window.WebGLRenderingContext;
  18258. }
  18259. catch (e) {
  18260. return false;
  18261. }
  18262. };
  18263. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18264. Engine.ExceptionList = [
  18265. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18266. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18267. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18268. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18269. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18270. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18271. ];
  18272. /** Gets the list of created engines */
  18273. Engine.Instances = new Array();
  18274. /**
  18275. * Hidden
  18276. */
  18277. Engine._TextureLoaders = [];
  18278. // Const statics
  18279. /** Defines that alpha blending is disabled */
  18280. Engine.ALPHA_DISABLE = 0;
  18281. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18282. Engine.ALPHA_ADD = 1;
  18283. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18284. Engine.ALPHA_COMBINE = 2;
  18285. /** Defines that alpha blending to DEST - SRC * DEST */
  18286. Engine.ALPHA_SUBTRACT = 3;
  18287. /** Defines that alpha blending to SRC * DEST */
  18288. Engine.ALPHA_MULTIPLY = 4;
  18289. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18290. Engine.ALPHA_MAXIMIZED = 5;
  18291. /** Defines that alpha blending to SRC + DEST */
  18292. Engine.ALPHA_ONEONE = 6;
  18293. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18294. Engine.ALPHA_PREMULTIPLIED = 7;
  18295. /**
  18296. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18297. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18298. */
  18299. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18300. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18301. Engine.ALPHA_INTERPOLATE = 9;
  18302. /**
  18303. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18304. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18305. */
  18306. Engine.ALPHA_SCREENMODE = 10;
  18307. /** Defines that the ressource is not delayed*/
  18308. Engine.DELAYLOADSTATE_NONE = 0;
  18309. /** Defines that the ressource was successfully delay loaded */
  18310. Engine.DELAYLOADSTATE_LOADED = 1;
  18311. /** Defines that the ressource is currently delay loading */
  18312. Engine.DELAYLOADSTATE_LOADING = 2;
  18313. /** Defines that the ressource is delayed and has not started loading */
  18314. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18315. // Depht or Stencil test Constants.
  18316. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18317. Engine.NEVER = 0x0200;
  18318. /** 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 */
  18319. Engine.ALWAYS = 0x0207;
  18320. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18321. Engine.LESS = 0x0201;
  18322. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18323. Engine.EQUAL = 0x0202;
  18324. /** 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 */
  18325. Engine.LEQUAL = 0x0203;
  18326. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18327. Engine.GREATER = 0x0204;
  18328. /** 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 */
  18329. Engine.GEQUAL = 0x0206;
  18330. /** 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 */
  18331. Engine.NOTEQUAL = 0x0205;
  18332. // Stencil Actions Constants.
  18333. /** Passed to stencilOperation to specify that stencil value must be kept */
  18334. Engine.KEEP = 0x1E00;
  18335. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18336. Engine.REPLACE = 0x1E01;
  18337. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18338. Engine.INCR = 0x1E02;
  18339. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18340. Engine.DECR = 0x1E03;
  18341. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18342. Engine.INVERT = 0x150A;
  18343. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18344. Engine.INCR_WRAP = 0x8507;
  18345. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18346. Engine.DECR_WRAP = 0x8508;
  18347. /** Texture is not repeating outside of 0..1 UVs */
  18348. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18349. /** Texture is repeating outside of 0..1 UVs */
  18350. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18351. /** Texture is repeating and mirrored */
  18352. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18353. /** ALPHA */
  18354. Engine.TEXTUREFORMAT_ALPHA = 0;
  18355. /** LUMINANCE */
  18356. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18357. /** LUMINANCE_ALPHA */
  18358. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18359. /** RGB */
  18360. Engine.TEXTUREFORMAT_RGB = 4;
  18361. /** RGBA */
  18362. Engine.TEXTUREFORMAT_RGBA = 5;
  18363. /** RED */
  18364. Engine.TEXTUREFORMAT_RED = 6;
  18365. /** RED (2nd reference) */
  18366. Engine.TEXTUREFORMAT_R = 6;
  18367. /** RG */
  18368. Engine.TEXTUREFORMAT_RG = 7;
  18369. /** RED_INTEGER */
  18370. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18371. /** RED_INTEGER (2nd reference) */
  18372. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18373. /** RG_INTEGER */
  18374. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18375. /** RGB_INTEGER */
  18376. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18377. /** RGBA_INTEGER */
  18378. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18379. /** UNSIGNED_BYTE */
  18380. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18381. /** UNSIGNED_BYTE (2nd reference) */
  18382. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18383. /** FLOAT */
  18384. Engine.TEXTURETYPE_FLOAT = 1;
  18385. /** HALF_FLOAT */
  18386. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18387. /** BYTE */
  18388. Engine.TEXTURETYPE_BYTE = 3;
  18389. /** SHORT */
  18390. Engine.TEXTURETYPE_SHORT = 4;
  18391. /** UNSIGNED_SHORT */
  18392. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18393. /** INT */
  18394. Engine.TEXTURETYPE_INT = 6;
  18395. /** UNSIGNED_INT */
  18396. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18397. /** UNSIGNED_SHORT_4_4_4_4 */
  18398. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18399. /** UNSIGNED_SHORT_5_5_5_1 */
  18400. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18401. /** UNSIGNED_SHORT_5_6_5 */
  18402. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18403. /** UNSIGNED_INT_2_10_10_10_REV */
  18404. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18405. /** UNSIGNED_INT_24_8 */
  18406. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18407. /** UNSIGNED_INT_10F_11F_11F_REV */
  18408. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18409. /** UNSIGNED_INT_5_9_9_9_REV */
  18410. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18411. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18412. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18413. /** nearest is mag = nearest and min = nearest and mip = linear */
  18414. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18415. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18416. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18417. /** Trilinear is mag = linear and min = linear and mip = linear */
  18418. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18419. /** nearest is mag = nearest and min = nearest and mip = linear */
  18420. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18421. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18422. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18423. /** Trilinear is mag = linear and min = linear and mip = linear */
  18424. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18425. /** mag = nearest and min = nearest and mip = nearest */
  18426. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18427. /** mag = nearest and min = linear and mip = nearest */
  18428. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18429. /** mag = nearest and min = linear and mip = linear */
  18430. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18431. /** mag = nearest and min = linear and mip = none */
  18432. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18433. /** mag = nearest and min = nearest and mip = none */
  18434. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18435. /** mag = linear and min = nearest and mip = nearest */
  18436. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18437. /** mag = linear and min = nearest and mip = linear */
  18438. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18439. /** mag = linear and min = linear and mip = none */
  18440. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18441. /** mag = linear and min = nearest and mip = none */
  18442. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18443. /** Explicit coordinates mode */
  18444. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18445. /** Spherical coordinates mode */
  18446. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18447. /** Planar coordinates mode */
  18448. Engine.TEXTURE_PLANAR_MODE = 2;
  18449. /** Cubic coordinates mode */
  18450. Engine.TEXTURE_CUBIC_MODE = 3;
  18451. /** Projection coordinates mode */
  18452. Engine.TEXTURE_PROJECTION_MODE = 4;
  18453. /** Skybox coordinates mode */
  18454. Engine.TEXTURE_SKYBOX_MODE = 5;
  18455. /** Inverse Cubic coordinates mode */
  18456. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18457. /** Equirectangular coordinates mode */
  18458. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18459. /** Equirectangular Fixed coordinates mode */
  18460. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18461. /** Equirectangular Fixed Mirrored coordinates mode */
  18462. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18463. // Texture rescaling mode
  18464. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18465. Engine.SCALEMODE_FLOOR = 1;
  18466. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18467. Engine.SCALEMODE_NEAREST = 2;
  18468. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18469. Engine.SCALEMODE_CEILING = 3;
  18470. // Updatable statics so stick with vars here
  18471. /**
  18472. * Gets or sets the epsilon value used by collision engine
  18473. */
  18474. Engine.CollisionsEpsilon = 0.001;
  18475. /**
  18476. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18477. */
  18478. Engine.CodeRepository = "src/";
  18479. /**
  18480. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18481. */
  18482. Engine.ShadersRepository = "src/Shaders/";
  18483. return Engine;
  18484. }());
  18485. BABYLON.Engine = Engine;
  18486. })(BABYLON || (BABYLON = {}));
  18487. //# sourceMappingURL=babylon.engine.js.map
  18488. var BABYLON;
  18489. (function (BABYLON) {
  18490. /**
  18491. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18492. */
  18493. var Node = /** @class */ (function () {
  18494. /**
  18495. * Creates a new Node
  18496. * @param name the name and id to be given to this node
  18497. * @param scene the scene this node will be added to
  18498. */
  18499. function Node(name, scene) {
  18500. if (scene === void 0) { scene = null; }
  18501. /**
  18502. * Gets or sets a string used to store user defined state for the node
  18503. */
  18504. this.state = "";
  18505. /**
  18506. * Gets or sets an object used to store user defined information for the node
  18507. */
  18508. this.metadata = null;
  18509. /**
  18510. * Gets or sets a boolean used to define if the node must be serialized
  18511. */
  18512. this.doNotSerialize = false;
  18513. /** @hidden */
  18514. this._isDisposed = false;
  18515. /**
  18516. * Gets a list of Animations associated with the node
  18517. */
  18518. this.animations = new Array();
  18519. this._ranges = {};
  18520. this._isEnabled = true;
  18521. this._isParentEnabled = true;
  18522. this._isReady = true;
  18523. /** @hidden */
  18524. this._currentRenderId = -1;
  18525. this._parentRenderId = -1;
  18526. this._childRenderId = -1;
  18527. /** @hidden */
  18528. this._worldMatrix = BABYLON.Matrix.Identity();
  18529. /** @hidden */
  18530. this._worldMatrixDeterminant = 0;
  18531. /** @hidden */
  18532. this._sceneRootNodesIndex = -1;
  18533. this._animationPropertiesOverride = null;
  18534. /**
  18535. * An event triggered when the mesh is disposed
  18536. */
  18537. this.onDisposeObservable = new BABYLON.Observable();
  18538. // Behaviors
  18539. this._behaviors = new Array();
  18540. this.name = name;
  18541. this.id = name;
  18542. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18543. this.uniqueId = this._scene.getUniqueId();
  18544. this._initCache();
  18545. this.addToSceneRootNodes();
  18546. }
  18547. /**
  18548. * Add a new node constructor
  18549. * @param type defines the type name of the node to construct
  18550. * @param constructorFunc defines the constructor function
  18551. */
  18552. Node.AddNodeConstructor = function (type, constructorFunc) {
  18553. this._NodeConstructors[type] = constructorFunc;
  18554. };
  18555. /**
  18556. * Returns a node constructor based on type name
  18557. * @param type defines the type name
  18558. * @param name defines the new node name
  18559. * @param scene defines the hosting scene
  18560. * @param options defines optional options to transmit to constructors
  18561. * @returns the new constructor or null
  18562. */
  18563. Node.Construct = function (type, name, scene, options) {
  18564. var constructorFunc = this._NodeConstructors[type];
  18565. if (!constructorFunc) {
  18566. return null;
  18567. }
  18568. return constructorFunc(name, scene, options);
  18569. };
  18570. /**
  18571. * Gets a boolean indicating if the node has been disposed
  18572. * @returns true if the node was disposed
  18573. */
  18574. Node.prototype.isDisposed = function () {
  18575. return this._isDisposed;
  18576. };
  18577. Object.defineProperty(Node.prototype, "parent", {
  18578. get: function () {
  18579. return this._parentNode;
  18580. },
  18581. /**
  18582. * Gets or sets the parent of the node
  18583. */
  18584. set: function (parent) {
  18585. if (this._parentNode === parent) {
  18586. return;
  18587. }
  18588. var previousParentNode = this._parentNode;
  18589. // Remove self from list of children of parent
  18590. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18591. var index = this._parentNode._children.indexOf(this);
  18592. if (index !== -1) {
  18593. this._parentNode._children.splice(index, 1);
  18594. }
  18595. if (!parent) {
  18596. this.addToSceneRootNodes();
  18597. }
  18598. }
  18599. // Store new parent
  18600. this._parentNode = parent;
  18601. // Add as child to new parent
  18602. if (this._parentNode) {
  18603. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18604. this._parentNode._children = new Array();
  18605. }
  18606. this._parentNode._children.push(this);
  18607. if (!previousParentNode) {
  18608. this.removeFromSceneRootNodes();
  18609. }
  18610. }
  18611. // Enabled state
  18612. this._syncParentEnabledState();
  18613. },
  18614. enumerable: true,
  18615. configurable: true
  18616. });
  18617. Node.prototype.addToSceneRootNodes = function () {
  18618. if (this._sceneRootNodesIndex === -1) {
  18619. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18620. this._scene.rootNodes.push(this);
  18621. }
  18622. };
  18623. Node.prototype.removeFromSceneRootNodes = function () {
  18624. if (this._sceneRootNodesIndex !== -1) {
  18625. var rootNodes = this._scene.rootNodes;
  18626. var lastIdx = rootNodes.length - 1;
  18627. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18628. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18629. this._scene.rootNodes.pop();
  18630. this._sceneRootNodesIndex = -1;
  18631. }
  18632. };
  18633. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18634. /**
  18635. * Gets or sets the animation properties override
  18636. */
  18637. get: function () {
  18638. if (!this._animationPropertiesOverride) {
  18639. return this._scene.animationPropertiesOverride;
  18640. }
  18641. return this._animationPropertiesOverride;
  18642. },
  18643. set: function (value) {
  18644. this._animationPropertiesOverride = value;
  18645. },
  18646. enumerable: true,
  18647. configurable: true
  18648. });
  18649. /**
  18650. * Gets a string idenfifying the name of the class
  18651. * @returns "Node" string
  18652. */
  18653. Node.prototype.getClassName = function () {
  18654. return "Node";
  18655. };
  18656. Object.defineProperty(Node.prototype, "onDispose", {
  18657. /**
  18658. * Sets a callback that will be raised when the node will be disposed
  18659. */
  18660. set: function (callback) {
  18661. if (this._onDisposeObserver) {
  18662. this.onDisposeObservable.remove(this._onDisposeObserver);
  18663. }
  18664. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. /**
  18670. * Gets the scene of the node
  18671. * @returns a scene
  18672. */
  18673. Node.prototype.getScene = function () {
  18674. return this._scene;
  18675. };
  18676. /**
  18677. * Gets the engine of the node
  18678. * @returns a Engine
  18679. */
  18680. Node.prototype.getEngine = function () {
  18681. return this._scene.getEngine();
  18682. };
  18683. /**
  18684. * Attach a behavior to the node
  18685. * @see http://doc.babylonjs.com/features/behaviour
  18686. * @param behavior defines the behavior to attach
  18687. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18688. * @returns the current Node
  18689. */
  18690. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18691. var _this = this;
  18692. if (attachImmediately === void 0) { attachImmediately = false; }
  18693. var index = this._behaviors.indexOf(behavior);
  18694. if (index !== -1) {
  18695. return this;
  18696. }
  18697. behavior.init();
  18698. if (this._scene.isLoading && !attachImmediately) {
  18699. // We defer the attach when the scene will be loaded
  18700. this._scene.onDataLoadedObservable.addOnce(function () {
  18701. behavior.attach(_this);
  18702. });
  18703. }
  18704. else {
  18705. behavior.attach(this);
  18706. }
  18707. this._behaviors.push(behavior);
  18708. return this;
  18709. };
  18710. /**
  18711. * Remove an attached behavior
  18712. * @see http://doc.babylonjs.com/features/behaviour
  18713. * @param behavior defines the behavior to attach
  18714. * @returns the current Node
  18715. */
  18716. Node.prototype.removeBehavior = function (behavior) {
  18717. var index = this._behaviors.indexOf(behavior);
  18718. if (index === -1) {
  18719. return this;
  18720. }
  18721. this._behaviors[index].detach();
  18722. this._behaviors.splice(index, 1);
  18723. return this;
  18724. };
  18725. Object.defineProperty(Node.prototype, "behaviors", {
  18726. /**
  18727. * Gets the list of attached behaviors
  18728. * @see http://doc.babylonjs.com/features/behaviour
  18729. */
  18730. get: function () {
  18731. return this._behaviors;
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. /**
  18737. * Gets an attached behavior by name
  18738. * @param name defines the name of the behavior to look for
  18739. * @see http://doc.babylonjs.com/features/behaviour
  18740. * @returns null if behavior was not found else the requested behavior
  18741. */
  18742. Node.prototype.getBehaviorByName = function (name) {
  18743. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18744. var behavior = _a[_i];
  18745. if (behavior.name === name) {
  18746. return behavior;
  18747. }
  18748. }
  18749. return null;
  18750. };
  18751. /**
  18752. * Returns the latest update of the World matrix
  18753. * @returns a Matrix
  18754. */
  18755. Node.prototype.getWorldMatrix = function () {
  18756. if (this._currentRenderId !== this._scene.getRenderId()) {
  18757. this.computeWorldMatrix();
  18758. }
  18759. return this._worldMatrix;
  18760. };
  18761. /** @hidden */
  18762. Node.prototype._getWorldMatrixDeterminant = function () {
  18763. return this._worldMatrixDeterminant;
  18764. };
  18765. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18766. /**
  18767. * Returns directly the latest state of the mesh World matrix.
  18768. * A Matrix is returned.
  18769. */
  18770. get: function () {
  18771. return this._worldMatrix;
  18772. },
  18773. enumerable: true,
  18774. configurable: true
  18775. });
  18776. // override it in derived class if you add new variables to the cache
  18777. // and call the parent class method
  18778. /** @hidden */
  18779. Node.prototype._initCache = function () {
  18780. this._cache = {};
  18781. this._cache.parent = undefined;
  18782. };
  18783. /** @hidden */
  18784. Node.prototype.updateCache = function (force) {
  18785. if (!force && this.isSynchronized()) {
  18786. return;
  18787. }
  18788. this._cache.parent = this.parent;
  18789. this._updateCache();
  18790. };
  18791. // override it in derived class if you add new variables to the cache
  18792. // and call the parent class method if !ignoreParentClass
  18793. /** @hidden */
  18794. Node.prototype._updateCache = function (ignoreParentClass) {
  18795. };
  18796. // override it in derived class if you add new variables to the cache
  18797. /** @hidden */
  18798. Node.prototype._isSynchronized = function () {
  18799. return true;
  18800. };
  18801. /** @hidden */
  18802. Node.prototype._markSyncedWithParent = function () {
  18803. if (this._parentNode) {
  18804. this._parentRenderId = this._parentNode._childRenderId;
  18805. }
  18806. };
  18807. /** @hidden */
  18808. Node.prototype.isSynchronizedWithParent = function () {
  18809. if (!this._parentNode) {
  18810. return true;
  18811. }
  18812. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18813. return false;
  18814. }
  18815. return this._parentNode.isSynchronized();
  18816. };
  18817. /** @hidden */
  18818. Node.prototype.isSynchronized = function () {
  18819. if (this._cache.parent != this._parentNode) {
  18820. this._cache.parent = this._parentNode;
  18821. return false;
  18822. }
  18823. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18824. return false;
  18825. }
  18826. return this._isSynchronized();
  18827. };
  18828. /**
  18829. * Is this node ready to be used/rendered
  18830. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18831. * @return true if the node is ready
  18832. */
  18833. Node.prototype.isReady = function (completeCheck) {
  18834. if (completeCheck === void 0) { completeCheck = false; }
  18835. return this._isReady;
  18836. };
  18837. /**
  18838. * Is this node enabled?
  18839. * 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
  18840. * @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
  18841. * @return whether this node (and its parent) is enabled
  18842. */
  18843. Node.prototype.isEnabled = function (checkAncestors) {
  18844. if (checkAncestors === void 0) { checkAncestors = true; }
  18845. if (checkAncestors === false) {
  18846. return this._isEnabled;
  18847. }
  18848. if (!this._isEnabled) {
  18849. return false;
  18850. }
  18851. return this._isParentEnabled;
  18852. };
  18853. /** @hidden */
  18854. Node.prototype._syncParentEnabledState = function () {
  18855. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18856. if (this._children) {
  18857. this._children.forEach(function (c) {
  18858. c._syncParentEnabledState(); // Force children to update accordingly
  18859. });
  18860. }
  18861. };
  18862. /**
  18863. * Set the enabled state of this node
  18864. * @param value defines the new enabled state
  18865. */
  18866. Node.prototype.setEnabled = function (value) {
  18867. this._isEnabled = value;
  18868. this._syncParentEnabledState();
  18869. };
  18870. /**
  18871. * Is this node a descendant of the given node?
  18872. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18873. * @param ancestor defines the parent node to inspect
  18874. * @returns a boolean indicating if this node is a descendant of the given node
  18875. */
  18876. Node.prototype.isDescendantOf = function (ancestor) {
  18877. if (this.parent) {
  18878. if (this.parent === ancestor) {
  18879. return true;
  18880. }
  18881. return this.parent.isDescendantOf(ancestor);
  18882. }
  18883. return false;
  18884. };
  18885. /** @hidden */
  18886. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18887. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18888. if (!this._children) {
  18889. return;
  18890. }
  18891. for (var index = 0; index < this._children.length; index++) {
  18892. var item = this._children[index];
  18893. if (!predicate || predicate(item)) {
  18894. results.push(item);
  18895. }
  18896. if (!directDescendantsOnly) {
  18897. item._getDescendants(results, false, predicate);
  18898. }
  18899. }
  18900. };
  18901. /**
  18902. * Will return all nodes that have this node as ascendant
  18903. * @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
  18904. * @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
  18905. * @return all children nodes of all types
  18906. */
  18907. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18908. var results = new Array();
  18909. this._getDescendants(results, directDescendantsOnly, predicate);
  18910. return results;
  18911. };
  18912. /**
  18913. * Get all child-meshes of this node
  18914. * @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
  18915. * @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
  18916. * @returns an array of AbstractMesh
  18917. */
  18918. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18919. var results = [];
  18920. this._getDescendants(results, directDescendantsOnly, function (node) {
  18921. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18922. });
  18923. return results;
  18924. };
  18925. /**
  18926. * Get all child-transformNodes of this node
  18927. * @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
  18928. * @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
  18929. * @returns an array of TransformNode
  18930. */
  18931. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18932. var results = [];
  18933. this._getDescendants(results, directDescendantsOnly, function (node) {
  18934. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18935. });
  18936. return results;
  18937. };
  18938. /**
  18939. * Get all direct children of this node
  18940. * @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
  18941. * @returns an array of Node
  18942. */
  18943. Node.prototype.getChildren = function (predicate) {
  18944. return this.getDescendants(true, predicate);
  18945. };
  18946. /** @hidden */
  18947. Node.prototype._setReady = function (state) {
  18948. if (state === this._isReady) {
  18949. return;
  18950. }
  18951. if (!state) {
  18952. this._isReady = false;
  18953. return;
  18954. }
  18955. if (this.onReady) {
  18956. this.onReady(this);
  18957. }
  18958. this._isReady = true;
  18959. };
  18960. /**
  18961. * Get an animation by name
  18962. * @param name defines the name of the animation to look for
  18963. * @returns null if not found else the requested animation
  18964. */
  18965. Node.prototype.getAnimationByName = function (name) {
  18966. for (var i = 0; i < this.animations.length; i++) {
  18967. var animation = this.animations[i];
  18968. if (animation.name === name) {
  18969. return animation;
  18970. }
  18971. }
  18972. return null;
  18973. };
  18974. /**
  18975. * Creates an animation range for this node
  18976. * @param name defines the name of the range
  18977. * @param from defines the starting key
  18978. * @param to defines the end key
  18979. */
  18980. Node.prototype.createAnimationRange = function (name, from, to) {
  18981. // check name not already in use
  18982. if (!this._ranges[name]) {
  18983. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18984. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18985. if (this.animations[i]) {
  18986. this.animations[i].createRange(name, from, to);
  18987. }
  18988. }
  18989. }
  18990. };
  18991. /**
  18992. * Delete a specific animation range
  18993. * @param name defines the name of the range to delete
  18994. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18995. */
  18996. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18997. if (deleteFrames === void 0) { deleteFrames = true; }
  18998. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18999. if (this.animations[i]) {
  19000. this.animations[i].deleteRange(name, deleteFrames);
  19001. }
  19002. }
  19003. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  19004. };
  19005. /**
  19006. * Get an animation range by name
  19007. * @param name defines the name of the animation range to look for
  19008. * @returns null if not found else the requested animation range
  19009. */
  19010. Node.prototype.getAnimationRange = function (name) {
  19011. return this._ranges[name];
  19012. };
  19013. /**
  19014. * Will start the animation sequence
  19015. * @param name defines the range frames for animation sequence
  19016. * @param loop defines if the animation should loop (false by default)
  19017. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  19018. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  19019. * @returns the object created for this animation. If range does not exist, it will return null
  19020. */
  19021. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  19022. var range = this.getAnimationRange(name);
  19023. if (!range) {
  19024. return null;
  19025. }
  19026. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  19027. };
  19028. /**
  19029. * Serialize animation ranges into a JSON compatible object
  19030. * @returns serialization object
  19031. */
  19032. Node.prototype.serializeAnimationRanges = function () {
  19033. var serializationRanges = [];
  19034. for (var name in this._ranges) {
  19035. var localRange = this._ranges[name];
  19036. if (!localRange) {
  19037. continue;
  19038. }
  19039. var range = {};
  19040. range.name = name;
  19041. range.from = localRange.from;
  19042. range.to = localRange.to;
  19043. serializationRanges.push(range);
  19044. }
  19045. return serializationRanges;
  19046. };
  19047. /**
  19048. * Computes the world matrix of the node
  19049. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19050. * @returns the world matrix
  19051. */
  19052. Node.prototype.computeWorldMatrix = function (force) {
  19053. if (!this._worldMatrix) {
  19054. this._worldMatrix = BABYLON.Matrix.Identity();
  19055. }
  19056. return this._worldMatrix;
  19057. };
  19058. /**
  19059. * Releases resources associated with this node.
  19060. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19061. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19062. */
  19063. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19064. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19065. if (!doNotRecurse) {
  19066. var nodes = this.getDescendants(true);
  19067. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19068. var node = nodes_1[_i];
  19069. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19070. }
  19071. }
  19072. else {
  19073. var transformNodes = this.getChildTransformNodes(true);
  19074. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19075. var transformNode = transformNodes_1[_a];
  19076. transformNode.parent = null;
  19077. transformNode.computeWorldMatrix(true);
  19078. }
  19079. }
  19080. if (!this.parent) {
  19081. this.removeFromSceneRootNodes();
  19082. }
  19083. else {
  19084. this.parent = null;
  19085. }
  19086. // Callback
  19087. this.onDisposeObservable.notifyObservers(this);
  19088. this.onDisposeObservable.clear();
  19089. // Behaviors
  19090. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19091. var behavior = _c[_b];
  19092. behavior.detach();
  19093. }
  19094. this._behaviors = [];
  19095. this._isDisposed = true;
  19096. };
  19097. /**
  19098. * Parse animation range data from a serialization object and store them into a given node
  19099. * @param node defines where to store the animation ranges
  19100. * @param parsedNode defines the serialization object to read data from
  19101. * @param scene defines the hosting scene
  19102. */
  19103. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19104. if (parsedNode.ranges) {
  19105. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19106. var data = parsedNode.ranges[index];
  19107. node.createAnimationRange(data.name, data.from, data.to);
  19108. }
  19109. }
  19110. };
  19111. Node._NodeConstructors = {};
  19112. __decorate([
  19113. BABYLON.serialize()
  19114. ], Node.prototype, "name", void 0);
  19115. __decorate([
  19116. BABYLON.serialize()
  19117. ], Node.prototype, "id", void 0);
  19118. __decorate([
  19119. BABYLON.serialize()
  19120. ], Node.prototype, "uniqueId", void 0);
  19121. __decorate([
  19122. BABYLON.serialize()
  19123. ], Node.prototype, "state", void 0);
  19124. __decorate([
  19125. BABYLON.serialize()
  19126. ], Node.prototype, "metadata", void 0);
  19127. return Node;
  19128. }());
  19129. BABYLON.Node = Node;
  19130. })(BABYLON || (BABYLON = {}));
  19131. //# sourceMappingURL=babylon.node.js.map
  19132. var BABYLON;
  19133. (function (BABYLON) {
  19134. /**
  19135. * Class used to store bounding sphere information
  19136. */
  19137. var BoundingSphere = /** @class */ (function () {
  19138. /**
  19139. * Creates a new bounding sphere
  19140. * @param min defines the minimum vector (in local space)
  19141. * @param max defines the maximum vector (in local space)
  19142. * @param worldMatrix defines the new world matrix
  19143. */
  19144. function BoundingSphere(min, max, worldMatrix) {
  19145. /**
  19146. * Gets the center of the bounding sphere in local space
  19147. */
  19148. this.center = BABYLON.Vector3.Zero();
  19149. /**
  19150. * Gets the center of the bounding sphere in world space
  19151. */
  19152. this.centerWorld = BABYLON.Vector3.Zero();
  19153. /**
  19154. * Gets the minimum vector in local space
  19155. */
  19156. this.minimum = BABYLON.Vector3.Zero();
  19157. /**
  19158. * Gets the maximum vector in local space
  19159. */
  19160. this.maximum = BABYLON.Vector3.Zero();
  19161. this.reConstruct(min, max, worldMatrix);
  19162. }
  19163. /**
  19164. * Recreates the entire bounding sphere from scratch as if we call the constructor in place
  19165. * @param min defines the new minimum vector (in local space)
  19166. * @param max defines the new maximum vector (in local space)
  19167. * @param worldMatrix defines the new world matrix
  19168. */
  19169. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19170. this.minimum.copyFrom(min);
  19171. this.maximum.copyFrom(max);
  19172. var distance = BABYLON.Vector3.Distance(min, max);
  19173. max.addToRef(min, this.center).scaleInPlace(0.5);
  19174. this.radius = distance * 0.5;
  19175. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19176. };
  19177. /**
  19178. * Scale the current bounding sphere by applying a scale factor
  19179. * @param factor defines the scale factor to apply
  19180. * @returns the current bounding box
  19181. */
  19182. BoundingSphere.prototype.scale = function (factor) {
  19183. var newRadius = this.radius * factor;
  19184. var tmpVectors = BoundingSphere.TmpVector3;
  19185. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19186. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19187. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19188. this.reConstruct(min, max, this._worldMatrix);
  19189. return this;
  19190. };
  19191. /**
  19192. * Gets the world matrix of the bounding box
  19193. * @returns a matrix
  19194. */
  19195. BoundingSphere.prototype.getWorldMatrix = function () {
  19196. return this._worldMatrix;
  19197. };
  19198. // Methods
  19199. /** @hidden */
  19200. BoundingSphere.prototype._update = function (worldMatrix) {
  19201. if (!worldMatrix.isIdentity()) {
  19202. BABYLON.Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
  19203. var tempVector = BoundingSphere.TmpVector3[0];
  19204. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
  19205. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19206. }
  19207. else {
  19208. this.centerWorld.copyFrom(this.center);
  19209. this.radiusWorld = this.radius;
  19210. }
  19211. };
  19212. /**
  19213. * Tests if the bounding sphere is intersecting the frustum planes
  19214. * @param frustumPlanes defines the frustum planes to test
  19215. * @returns true if there is an intersection
  19216. */
  19217. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19218. for (var i = 0; i < 6; i++) {
  19219. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19220. return false;
  19221. }
  19222. }
  19223. return true;
  19224. };
  19225. /**
  19226. * Tests if a point is inside the bounding sphere
  19227. * @param point defines the point to test
  19228. * @returns true if the point is inside the bounding sphere
  19229. */
  19230. BoundingSphere.prototype.intersectsPoint = function (point) {
  19231. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19232. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19233. return false;
  19234. }
  19235. return true;
  19236. };
  19237. // Statics
  19238. /**
  19239. * Checks if two sphere intersct
  19240. * @param sphere0 sphere 0
  19241. * @param sphere1 sphere 1
  19242. * @returns true if the speres intersect
  19243. */
  19244. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19245. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19246. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19247. if (radiusSum * radiusSum < squareDistance) {
  19248. return false;
  19249. }
  19250. return true;
  19251. };
  19252. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19253. return BoundingSphere;
  19254. }());
  19255. BABYLON.BoundingSphere = BoundingSphere;
  19256. })(BABYLON || (BABYLON = {}));
  19257. //# sourceMappingURL=babylon.boundingSphere.js.map
  19258. var BABYLON;
  19259. (function (BABYLON) {
  19260. /**
  19261. * Class used to store bounding box information
  19262. */
  19263. var BoundingBox = /** @class */ (function () {
  19264. /**
  19265. * Creates a new bounding box
  19266. * @param min defines the minimum vector (in local space)
  19267. * @param max defines the maximum vector (in local space)
  19268. * @param worldMatrix defines the new world matrix
  19269. */
  19270. function BoundingBox(min, max, worldMatrix) {
  19271. /**
  19272. * Gets the 8 vectors representing the bounding box in local space
  19273. */
  19274. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19275. /**
  19276. * Gets the center of the bounding box in local space
  19277. */
  19278. this.center = BABYLON.Vector3.Zero();
  19279. /**
  19280. * Gets the center of the bounding box in world space
  19281. */
  19282. this.centerWorld = BABYLON.Vector3.Zero();
  19283. /**
  19284. * Gets the extend size in local space
  19285. */
  19286. this.extendSize = BABYLON.Vector3.Zero();
  19287. /**
  19288. * Gets the extend size in world space
  19289. */
  19290. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19291. /**
  19292. * Gets the OBB (object bounding box) directions
  19293. */
  19294. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19295. /**
  19296. * Gets the 8 vectors representing the bounding box in world space
  19297. */
  19298. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19299. /**
  19300. * Gets the minimum vector in world space
  19301. */
  19302. this.minimumWorld = BABYLON.Vector3.Zero();
  19303. /**
  19304. * Gets the maximum vector in world space
  19305. */
  19306. this.maximumWorld = BABYLON.Vector3.Zero();
  19307. /**
  19308. * Gets the minimum vector in local space
  19309. */
  19310. this.minimum = BABYLON.Vector3.Zero();
  19311. /**
  19312. * Gets the maximum vector in local space
  19313. */
  19314. this.maximum = BABYLON.Vector3.Zero();
  19315. this.reConstruct(min, max, worldMatrix);
  19316. }
  19317. // Methods
  19318. /**
  19319. * Recreates the entire bounding box from scratch as if we call the constructor in place
  19320. * @param min defines the new minimum vector (in local space)
  19321. * @param max defines the new maximum vector (in local space)
  19322. * @param worldMatrix defines the new world matrix
  19323. */
  19324. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19325. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19326. var vectors = this.vectors;
  19327. this.minimum.copyFromFloats(minX, minY, minZ);
  19328. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19329. vectors[0].copyFromFloats(minX, minY, minZ);
  19330. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19331. vectors[2].copyFromFloats(maxX, minY, minZ);
  19332. vectors[3].copyFromFloats(minX, maxY, minZ);
  19333. vectors[4].copyFromFloats(minX, minY, maxZ);
  19334. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19335. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19336. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19337. // OBB
  19338. max.addToRef(min, this.center).scaleInPlace(0.5);
  19339. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19340. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19341. };
  19342. /**
  19343. * Scale the current bounding box by applying a scale factor
  19344. * @param factor defines the scale factor to apply
  19345. * @returns the current bounding box
  19346. */
  19347. BoundingBox.prototype.scale = function (factor) {
  19348. var tmpVectors = BoundingBox.TmpVector3;
  19349. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19350. var len = diff.length();
  19351. diff.normalizeFromLength(len);
  19352. var distance = len * factor;
  19353. var newRadius = diff.scaleInPlace(distance * 0.5);
  19354. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19355. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19356. this.reConstruct(min, max, this._worldMatrix);
  19357. return this;
  19358. };
  19359. /**
  19360. * Gets the world matrix of the bounding box
  19361. * @returns a matrix
  19362. */
  19363. BoundingBox.prototype.getWorldMatrix = function () {
  19364. return this._worldMatrix;
  19365. };
  19366. /** @hidden */
  19367. BoundingBox.prototype._update = function (world) {
  19368. var minWorld = this.minimumWorld;
  19369. var maxWorld = this.maximumWorld;
  19370. var directions = this.directions;
  19371. var vectorsWorld = this.vectorsWorld;
  19372. var vectors = this.vectors;
  19373. if (!world.isIdentity()) {
  19374. minWorld.setAll(Number.MAX_VALUE);
  19375. maxWorld.setAll(-Number.MAX_VALUE);
  19376. for (var index = 0; index < 8; ++index) {
  19377. var v = vectorsWorld[index];
  19378. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19379. minWorld.minimizeInPlace(v);
  19380. maxWorld.maximizeInPlace(v);
  19381. }
  19382. // Extend
  19383. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19384. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19385. }
  19386. else {
  19387. minWorld.copyFrom(this.minimum);
  19388. maxWorld.copyFrom(this.maximum);
  19389. for (var index = 0; index < 8; ++index) {
  19390. vectorsWorld[index].copyFrom(vectors[index]);
  19391. }
  19392. // Extend
  19393. this.extendSizeWorld.copyFrom(this.extendSize);
  19394. this.centerWorld.copyFrom(this.center);
  19395. }
  19396. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19397. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19398. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19399. this._worldMatrix = world;
  19400. };
  19401. /**
  19402. * Tests if the bounding box is intersecting the frustum planes
  19403. * @param frustumPlanes defines the frustum planes to test
  19404. * @returns true if there is an intersection
  19405. */
  19406. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19407. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19408. };
  19409. /**
  19410. * Tests if the bounding box is entirely inside the frustum planes
  19411. * @param frustumPlanes defines the frustum planes to test
  19412. * @returns true if there is an inclusion
  19413. */
  19414. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19415. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19416. };
  19417. /**
  19418. * Tests if a point is inside the bounding box
  19419. * @param point defines the point to test
  19420. * @returns true if the point is inside the bounding box
  19421. */
  19422. BoundingBox.prototype.intersectsPoint = function (point) {
  19423. var min = this.minimumWorld;
  19424. var max = this.maximumWorld;
  19425. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19426. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19427. var delta = -BABYLON.Epsilon;
  19428. if (maxX - pointX < delta || delta > pointX - minX) {
  19429. return false;
  19430. }
  19431. if (maxY - pointY < delta || delta > pointY - minY) {
  19432. return false;
  19433. }
  19434. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19435. return false;
  19436. }
  19437. return true;
  19438. };
  19439. /**
  19440. * Tests if the bounding box intersects with a bounding sphere
  19441. * @param sphere defines the sphere to test
  19442. * @returns true if there is an intersection
  19443. */
  19444. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19445. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19446. };
  19447. /**
  19448. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19449. * @param min defines the min vector to use
  19450. * @param max defines the max vector to use
  19451. * @returns true if there is an intersection
  19452. */
  19453. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19454. var myMin = this.minimumWorld;
  19455. var myMax = this.maximumWorld;
  19456. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19457. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19458. if (myMaxX < minX || myMinX > maxX) {
  19459. return false;
  19460. }
  19461. if (myMaxY < minY || myMinY > maxY) {
  19462. return false;
  19463. }
  19464. if (myMaxZ < minZ || myMinZ > maxZ) {
  19465. return false;
  19466. }
  19467. return true;
  19468. };
  19469. // Statics
  19470. /**
  19471. * Tests if two bounding boxes are intersections
  19472. * @param box0 defines the first box to test
  19473. * @param box1 defines the second box to test
  19474. * @returns true if there is an intersection
  19475. */
  19476. BoundingBox.Intersects = function (box0, box1) {
  19477. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19478. };
  19479. /**
  19480. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19481. * @param minPoint defines the minimum vector of the bounding box
  19482. * @param maxPoint defines the maximum vector of the bounding box
  19483. * @param sphereCenter defines the sphere center
  19484. * @param sphereRadius defines the sphere radius
  19485. * @returns true if there is an intersection
  19486. */
  19487. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19488. var vector = BoundingBox.TmpVector3[0];
  19489. BABYLON.Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
  19490. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19491. return (num <= (sphereRadius * sphereRadius));
  19492. };
  19493. /**
  19494. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19495. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19496. * @param frustumPlanes defines the frustum planes to test
  19497. * @return true if there is an inclusion
  19498. */
  19499. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19500. for (var p = 0; p < 6; ++p) {
  19501. var frustumPlane = frustumPlanes[p];
  19502. for (var i = 0; i < 8; ++i) {
  19503. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19504. return false;
  19505. }
  19506. }
  19507. }
  19508. return true;
  19509. };
  19510. /**
  19511. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19512. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19513. * @param frustumPlanes defines the frustum planes to test
  19514. * @return true if there is an intersection
  19515. */
  19516. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19517. for (var p = 0; p < 6; ++p) {
  19518. var canReturnFalse = true;
  19519. var frustumPlane = frustumPlanes[p];
  19520. for (var i = 0; i < 8; ++i) {
  19521. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19522. canReturnFalse = false;
  19523. break;
  19524. }
  19525. }
  19526. if (canReturnFalse) {
  19527. return false;
  19528. }
  19529. }
  19530. return true;
  19531. };
  19532. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19533. return BoundingBox;
  19534. }());
  19535. BABYLON.BoundingBox = BoundingBox;
  19536. })(BABYLON || (BABYLON = {}));
  19537. //# sourceMappingURL=babylon.boundingBox.js.map
  19538. var BABYLON;
  19539. (function (BABYLON) {
  19540. var _result0 = { min: 0, max: 0 };
  19541. var _result1 = { min: 0, max: 0 };
  19542. var computeBoxExtents = function (axis, box, result) {
  19543. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19544. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19545. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19546. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19547. var r = r0 + r1 + r2;
  19548. result.min = p - r;
  19549. result.max = p + r;
  19550. };
  19551. var axisOverlap = function (axis, box0, box1) {
  19552. computeBoxExtents(axis, box0, _result0);
  19553. computeBoxExtents(axis, box1, _result1);
  19554. return !(_result0.min > _result1.max || _result1.min > _result0.max);
  19555. };
  19556. /**
  19557. * Info for a bounding data of a mesh
  19558. */
  19559. var BoundingInfo = /** @class */ (function () {
  19560. /**
  19561. * Constructs bounding info
  19562. * @param minimum min vector of the bounding box/sphere
  19563. * @param maximum max vector of the bounding box/sphere
  19564. * @param worldMatrix defines the new world matrix
  19565. */
  19566. function BoundingInfo(minimum, maximum, worldMatrix) {
  19567. this._isLocked = false;
  19568. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19569. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19570. }
  19571. /**
  19572. * Recreates the entire bounding info from scratch as if we call the constructor in place
  19573. * @param min defines the new minimum vector (in local space)
  19574. * @param max defines the new maximum vector (in local space)
  19575. * @param worldMatrix defines the new world matrix
  19576. */
  19577. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19578. this.boundingBox.reConstruct(min, max, worldMatrix);
  19579. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19580. };
  19581. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19582. /**
  19583. * min vector of the bounding box/sphere
  19584. */
  19585. get: function () {
  19586. return this.boundingBox.minimum;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19592. /**
  19593. * max vector of the bounding box/sphere
  19594. */
  19595. get: function () {
  19596. return this.boundingBox.maximum;
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19602. /**
  19603. * If the info is locked and won't be updated to avoid perf overhead
  19604. */
  19605. get: function () {
  19606. return this._isLocked;
  19607. },
  19608. set: function (value) {
  19609. this._isLocked = value;
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. // Methods
  19615. /**
  19616. * Updates the bounding sphere and box
  19617. * @param world world matrix to be used to update
  19618. */
  19619. BoundingInfo.prototype.update = function (world) {
  19620. if (this._isLocked) {
  19621. return;
  19622. }
  19623. this.boundingBox._update(world);
  19624. this.boundingSphere._update(world);
  19625. };
  19626. /**
  19627. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19628. * @param center New center of the bounding info
  19629. * @param extend New extend of the bounding info
  19630. * @returns the current bounding info
  19631. */
  19632. BoundingInfo.prototype.centerOn = function (center, extend) {
  19633. var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend);
  19634. var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend);
  19635. this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19636. this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19637. return this;
  19638. };
  19639. /**
  19640. * Scale the current bounding info by applying a scale factor
  19641. * @param factor defines the scale factor to apply
  19642. * @returns the current bounding info
  19643. */
  19644. BoundingInfo.prototype.scale = function (factor) {
  19645. this.boundingBox.scale(factor);
  19646. this.boundingSphere.scale(factor);
  19647. return this;
  19648. };
  19649. /**
  19650. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19651. * @param frustumPlanes defines the frustum to test
  19652. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19653. * @returns true if the bounding info is in the frustum planes
  19654. */
  19655. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19656. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19657. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19658. return false;
  19659. }
  19660. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19661. return true;
  19662. }
  19663. return this.boundingBox.isInFrustum(frustumPlanes);
  19664. };
  19665. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19666. /**
  19667. * Gets the world distance between the min and max points of the bounding box
  19668. */
  19669. get: function () {
  19670. var boundingBox = this.boundingBox;
  19671. var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]);
  19672. return diag.length();
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. /**
  19678. * Checks if a cullable object (mesh...) is in the camera frustum
  19679. * Unlike isInFrustum this cheks the full bounding box
  19680. * @param frustumPlanes Camera near/planes
  19681. * @returns true if the object is in frustum otherwise false
  19682. */
  19683. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19684. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19685. };
  19686. /** @hidden */
  19687. BoundingInfo.prototype._checkCollision = function (collider) {
  19688. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19689. };
  19690. /**
  19691. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19692. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19693. * @param point the point to check intersection with
  19694. * @returns if the point intersects
  19695. */
  19696. BoundingInfo.prototype.intersectsPoint = function (point) {
  19697. if (!this.boundingSphere.centerWorld) {
  19698. return false;
  19699. }
  19700. if (!this.boundingSphere.intersectsPoint(point)) {
  19701. return false;
  19702. }
  19703. if (!this.boundingBox.intersectsPoint(point)) {
  19704. return false;
  19705. }
  19706. return true;
  19707. };
  19708. /**
  19709. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19710. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19711. * @param boundingInfo the bounding info to check intersection with
  19712. * @param precise if the intersection should be done using OBB
  19713. * @returns if the bounding info intersects
  19714. */
  19715. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19716. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19717. return false;
  19718. }
  19719. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19720. return false;
  19721. }
  19722. if (!precise) {
  19723. return true;
  19724. }
  19725. var box0 = this.boundingBox;
  19726. var box1 = boundingInfo.boundingBox;
  19727. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19728. return false;
  19729. }
  19730. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19731. return false;
  19732. }
  19733. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19734. return false;
  19735. }
  19736. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19737. return false;
  19738. }
  19739. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19740. return false;
  19741. }
  19742. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19743. return false;
  19744. }
  19745. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19746. return false;
  19747. }
  19748. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19749. return false;
  19750. }
  19751. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19752. return false;
  19753. }
  19754. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19755. return false;
  19756. }
  19757. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19758. return false;
  19759. }
  19760. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19761. return false;
  19762. }
  19763. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19764. return false;
  19765. }
  19766. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19767. return false;
  19768. }
  19769. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19770. return false;
  19771. }
  19772. return true;
  19773. };
  19774. BoundingInfo.TmpVector3 = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  19775. return BoundingInfo;
  19776. }());
  19777. BABYLON.BoundingInfo = BoundingInfo;
  19778. })(BABYLON || (BABYLON = {}));
  19779. //# sourceMappingURL=babylon.boundingInfo.js.map
  19780. var BABYLON;
  19781. (function (BABYLON) {
  19782. /**
  19783. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19784. * @see https://doc.babylonjs.com/how_to/transformnode
  19785. */
  19786. var TransformNode = /** @class */ (function (_super) {
  19787. __extends(TransformNode, _super);
  19788. function TransformNode(name, scene, isPure) {
  19789. if (scene === void 0) { scene = null; }
  19790. if (isPure === void 0) { isPure = true; }
  19791. var _this = _super.call(this, name, scene) || this;
  19792. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19793. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19794. _this._up = new BABYLON.Vector3(0, 1, 0);
  19795. _this._right = new BABYLON.Vector3(1, 0, 0);
  19796. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19797. // Properties
  19798. _this._position = BABYLON.Vector3.Zero();
  19799. _this._rotation = BABYLON.Vector3.Zero();
  19800. _this._scaling = BABYLON.Vector3.One();
  19801. _this._isDirty = false;
  19802. /**
  19803. * Set the billboard mode. Default is 0.
  19804. *
  19805. * | Value | Type | Description |
  19806. * | --- | --- | --- |
  19807. * | 0 | BILLBOARDMODE_NONE | |
  19808. * | 1 | BILLBOARDMODE_X | |
  19809. * | 2 | BILLBOARDMODE_Y | |
  19810. * | 4 | BILLBOARDMODE_Z | |
  19811. * | 7 | BILLBOARDMODE_ALL | |
  19812. *
  19813. */
  19814. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19815. /**
  19816. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19817. */
  19818. _this.scalingDeterminant = 1;
  19819. /**
  19820. * Sets the distance of the object to max, often used by skybox
  19821. */
  19822. _this.infiniteDistance = false;
  19823. /**
  19824. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19825. * By default the system will update normals to compensate
  19826. */
  19827. _this.ignoreNonUniformScaling = false;
  19828. _this._localWorld = BABYLON.Matrix.Zero();
  19829. _this._absolutePosition = BABYLON.Vector3.Zero();
  19830. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19831. _this._postMultiplyPivotMatrix = false;
  19832. _this._isWorldMatrixFrozen = false;
  19833. /** @hidden */
  19834. _this._indexInSceneTransformNodesArray = -1;
  19835. /**
  19836. * An event triggered after the world matrix is updated
  19837. */
  19838. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19839. _this._nonUniformScaling = false;
  19840. if (isPure) {
  19841. _this.getScene().addTransformNode(_this);
  19842. }
  19843. return _this;
  19844. }
  19845. /**
  19846. * Gets a string identifying the name of the class
  19847. * @returns "TransformNode" string
  19848. */
  19849. TransformNode.prototype.getClassName = function () {
  19850. return "TransformNode";
  19851. };
  19852. Object.defineProperty(TransformNode.prototype, "position", {
  19853. /**
  19854. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19855. */
  19856. get: function () {
  19857. return this._position;
  19858. },
  19859. set: function (newPosition) {
  19860. this._position = newPosition;
  19861. this._isDirty = true;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(TransformNode.prototype, "rotation", {
  19867. /**
  19868. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19869. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19870. */
  19871. get: function () {
  19872. return this._rotation;
  19873. },
  19874. set: function (newRotation) {
  19875. this._rotation = newRotation;
  19876. this._isDirty = true;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(TransformNode.prototype, "scaling", {
  19882. /**
  19883. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19884. */
  19885. get: function () {
  19886. return this._scaling;
  19887. },
  19888. set: function (newScaling) {
  19889. this._scaling = newScaling;
  19890. this._isDirty = true;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19896. /**
  19897. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19898. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19899. */
  19900. get: function () {
  19901. return this._rotationQuaternion;
  19902. },
  19903. set: function (quaternion) {
  19904. this._rotationQuaternion = quaternion;
  19905. //reset the rotation vector.
  19906. if (quaternion) {
  19907. this.rotation.setAll(0.0);
  19908. }
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(TransformNode.prototype, "forward", {
  19914. /**
  19915. * The forward direction of that transform in world space.
  19916. */
  19917. get: function () {
  19918. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(TransformNode.prototype, "up", {
  19924. /**
  19925. * The up direction of that transform in world space.
  19926. */
  19927. get: function () {
  19928. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(TransformNode.prototype, "right", {
  19934. /**
  19935. * The right direction of that transform in world space.
  19936. */
  19937. get: function () {
  19938. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. /**
  19944. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19945. * @param matrix the matrix to copy the pose from
  19946. * @returns this TransformNode.
  19947. */
  19948. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19949. this._poseMatrix.copyFrom(matrix);
  19950. return this;
  19951. };
  19952. /**
  19953. * Returns the mesh Pose matrix.
  19954. * @returns the pose matrix
  19955. */
  19956. TransformNode.prototype.getPoseMatrix = function () {
  19957. return this._poseMatrix;
  19958. };
  19959. /** @hidden */
  19960. TransformNode.prototype._isSynchronized = function () {
  19961. if (this._isDirty) {
  19962. return false;
  19963. }
  19964. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19965. return false;
  19966. }
  19967. if (this._cache.pivotMatrixUpdated) {
  19968. return false;
  19969. }
  19970. if (this.infiniteDistance) {
  19971. return false;
  19972. }
  19973. if (!this._cache.position.equals(this._position)) {
  19974. return false;
  19975. }
  19976. if (this._rotationQuaternion) {
  19977. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19978. return false;
  19979. }
  19980. }
  19981. if (!this._cache.rotation.equals(this._rotation)) {
  19982. return false;
  19983. }
  19984. if (!this._cache.scaling.equals(this._scaling)) {
  19985. return false;
  19986. }
  19987. return true;
  19988. };
  19989. /** @hidden */
  19990. TransformNode.prototype._initCache = function () {
  19991. _super.prototype._initCache.call(this);
  19992. this._cache.localMatrixUpdated = false;
  19993. this._cache.position = BABYLON.Vector3.Zero();
  19994. this._cache.scaling = BABYLON.Vector3.Zero();
  19995. this._cache.rotation = BABYLON.Vector3.Zero();
  19996. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19997. this._cache.billboardMode = -1;
  19998. };
  19999. /**
  20000. * Flag the transform node as dirty (Forcing it to update everything)
  20001. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  20002. * @returns this transform node
  20003. */
  20004. TransformNode.prototype.markAsDirty = function (property) {
  20005. if (property === "rotation") {
  20006. this.rotationQuaternion = null;
  20007. }
  20008. this._currentRenderId = Number.MAX_VALUE;
  20009. this._isDirty = true;
  20010. return this;
  20011. };
  20012. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  20013. /**
  20014. * Returns the current mesh absolute position.
  20015. * Returns a Vector3.
  20016. */
  20017. get: function () {
  20018. return this._absolutePosition;
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. /**
  20024. * Sets a new matrix to apply before all other transformation
  20025. * @param matrix defines the transform matrix
  20026. * @returns the current TransformNode
  20027. */
  20028. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  20029. return this.setPivotMatrix(matrix, false);
  20030. };
  20031. /**
  20032. * Sets a new pivot matrix to the current node
  20033. * @param matrix defines the new pivot matrix to use
  20034. * @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
  20035. * @returns the current TransformNode
  20036. */
  20037. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20038. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20039. this._pivotMatrix.copyFrom(matrix);
  20040. this._cache.pivotMatrixUpdated = true;
  20041. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20042. if (this._postMultiplyPivotMatrix) {
  20043. if (!this._pivotMatrixInverse) {
  20044. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20045. }
  20046. else {
  20047. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20048. }
  20049. }
  20050. return this;
  20051. };
  20052. /**
  20053. * Returns the mesh pivot matrix.
  20054. * Default : Identity.
  20055. * @returns the matrix
  20056. */
  20057. TransformNode.prototype.getPivotMatrix = function () {
  20058. return this._pivotMatrix;
  20059. };
  20060. /**
  20061. * Prevents the World matrix to be computed any longer.
  20062. * @returns the TransformNode.
  20063. */
  20064. TransformNode.prototype.freezeWorldMatrix = function () {
  20065. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20066. this.computeWorldMatrix(true);
  20067. this._isWorldMatrixFrozen = true;
  20068. return this;
  20069. };
  20070. /**
  20071. * Allows back the World matrix computation.
  20072. * @returns the TransformNode.
  20073. */
  20074. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20075. this._isWorldMatrixFrozen = false;
  20076. this.computeWorldMatrix(true);
  20077. return this;
  20078. };
  20079. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20080. /**
  20081. * True if the World matrix has been frozen.
  20082. */
  20083. get: function () {
  20084. return this._isWorldMatrixFrozen;
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. /**
  20090. * Retuns the mesh absolute position in the World.
  20091. * @returns a Vector3.
  20092. */
  20093. TransformNode.prototype.getAbsolutePosition = function () {
  20094. this.computeWorldMatrix();
  20095. return this._absolutePosition;
  20096. };
  20097. /**
  20098. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20099. * @param absolutePosition the absolute position to set
  20100. * @returns the TransformNode.
  20101. */
  20102. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20103. if (!absolutePosition) {
  20104. return this;
  20105. }
  20106. var absolutePositionX;
  20107. var absolutePositionY;
  20108. var absolutePositionZ;
  20109. if (absolutePosition.x === undefined) {
  20110. if (arguments.length < 3) {
  20111. return this;
  20112. }
  20113. absolutePositionX = arguments[0];
  20114. absolutePositionY = arguments[1];
  20115. absolutePositionZ = arguments[2];
  20116. }
  20117. else {
  20118. absolutePositionX = absolutePosition.x;
  20119. absolutePositionY = absolutePosition.y;
  20120. absolutePositionZ = absolutePosition.z;
  20121. }
  20122. if (this.parent) {
  20123. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20124. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20126. }
  20127. else {
  20128. this.position.x = absolutePositionX;
  20129. this.position.y = absolutePositionY;
  20130. this.position.z = absolutePositionZ;
  20131. }
  20132. return this;
  20133. };
  20134. /**
  20135. * Sets the mesh position in its local space.
  20136. * @param vector3 the position to set in localspace
  20137. * @returns the TransformNode.
  20138. */
  20139. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20140. this.computeWorldMatrix();
  20141. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20142. return this;
  20143. };
  20144. /**
  20145. * Returns the mesh position in the local space from the current World matrix values.
  20146. * @returns a new Vector3.
  20147. */
  20148. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20149. this.computeWorldMatrix();
  20150. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20151. this._localWorld.invertToRef(invLocalWorldMatrix);
  20152. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20153. };
  20154. /**
  20155. * Translates the mesh along the passed Vector3 in its local space.
  20156. * @param vector3 the distance to translate in localspace
  20157. * @returns the TransformNode.
  20158. */
  20159. TransformNode.prototype.locallyTranslate = function (vector3) {
  20160. this.computeWorldMatrix(true);
  20161. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20162. return this;
  20163. };
  20164. /**
  20165. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20166. * @param targetPoint the position (must be in same space as current mesh) to look at
  20167. * @param yawCor optional yaw (y-axis) correction in radians
  20168. * @param pitchCor optional pitch (x-axis) correction in radians
  20169. * @param rollCor optional roll (z-axis) correction in radians
  20170. * @param space the choosen space of the target
  20171. * @returns the TransformNode.
  20172. */
  20173. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20174. if (yawCor === void 0) { yawCor = 0; }
  20175. if (pitchCor === void 0) { pitchCor = 0; }
  20176. if (rollCor === void 0) { rollCor = 0; }
  20177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20178. var dv = TransformNode._lookAtVectorCache;
  20179. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20180. targetPoint.subtractToRef(pos, dv);
  20181. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20182. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20183. var pitch = Math.atan2(dv.y, len);
  20184. if (this.rotationQuaternion) {
  20185. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20186. }
  20187. else {
  20188. this.rotation.x = pitch + pitchCor;
  20189. this.rotation.y = yaw + yawCor;
  20190. this.rotation.z = rollCor;
  20191. }
  20192. return this;
  20193. };
  20194. /**
  20195. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20196. * This Vector3 is expressed in the World space.
  20197. * @param localAxis axis to rotate
  20198. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20199. */
  20200. TransformNode.prototype.getDirection = function (localAxis) {
  20201. var result = BABYLON.Vector3.Zero();
  20202. this.getDirectionToRef(localAxis, result);
  20203. return result;
  20204. };
  20205. /**
  20206. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20207. * localAxis is expressed in the mesh local space.
  20208. * result is computed in the Wordl space from the mesh World matrix.
  20209. * @param localAxis axis to rotate
  20210. * @param result the resulting transformnode
  20211. * @returns this TransformNode.
  20212. */
  20213. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20214. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20215. return this;
  20216. };
  20217. /**
  20218. * Sets a new pivot point to the current node
  20219. * @param point defines the new pivot point to use
  20220. * @param space defines if the point is in world or local space (local by default)
  20221. * @returns the current TransformNode
  20222. */
  20223. TransformNode.prototype.setPivotPoint = function (point, space) {
  20224. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20225. if (this.getScene().getRenderId() == 0) {
  20226. this.computeWorldMatrix(true);
  20227. }
  20228. var wm = this.getWorldMatrix();
  20229. if (space == BABYLON.Space.WORLD) {
  20230. var tmat = BABYLON.Tmp.Matrix[0];
  20231. wm.invertToRef(tmat);
  20232. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20233. }
  20234. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20235. };
  20236. /**
  20237. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20238. * @returns the pivot point
  20239. */
  20240. TransformNode.prototype.getPivotPoint = function () {
  20241. var point = BABYLON.Vector3.Zero();
  20242. this.getPivotPointToRef(point);
  20243. return point;
  20244. };
  20245. /**
  20246. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20247. * @param result the vector3 to store the result
  20248. * @returns this TransformNode.
  20249. */
  20250. TransformNode.prototype.getPivotPointToRef = function (result) {
  20251. result.x = -this._pivotMatrix.m[12];
  20252. result.y = -this._pivotMatrix.m[13];
  20253. result.z = -this._pivotMatrix.m[14];
  20254. return this;
  20255. };
  20256. /**
  20257. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20258. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20259. */
  20260. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20261. var point = BABYLON.Vector3.Zero();
  20262. this.getAbsolutePivotPointToRef(point);
  20263. return point;
  20264. };
  20265. /**
  20266. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20267. * @param result vector3 to store the result
  20268. * @returns this TransformNode.
  20269. */
  20270. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20271. result.x = this._pivotMatrix.m[12];
  20272. result.y = this._pivotMatrix.m[13];
  20273. result.z = this._pivotMatrix.m[14];
  20274. this.getPivotPointToRef(result);
  20275. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20276. return this;
  20277. };
  20278. /**
  20279. * Defines the passed node as the parent of the current node.
  20280. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20281. * @param node the node ot set as the parent
  20282. * @returns this TransformNode.
  20283. */
  20284. TransformNode.prototype.setParent = function (node) {
  20285. if (!node && !this.parent) {
  20286. return this;
  20287. }
  20288. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20289. var position = BABYLON.Tmp.Vector3[0];
  20290. var scale = BABYLON.Tmp.Vector3[1];
  20291. if (!node) {
  20292. if (this.parent && this.parent.computeWorldMatrix) {
  20293. this.parent.computeWorldMatrix(true);
  20294. }
  20295. this.computeWorldMatrix(true);
  20296. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20297. }
  20298. else {
  20299. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20300. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20301. this.computeWorldMatrix(true);
  20302. node.computeWorldMatrix(true);
  20303. node.getWorldMatrix().invertToRef(invParentMatrix);
  20304. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20305. diffMatrix.decompose(scale, quatRotation, position);
  20306. }
  20307. if (this.rotationQuaternion) {
  20308. this.rotationQuaternion.copyFrom(quatRotation);
  20309. }
  20310. else {
  20311. quatRotation.toEulerAnglesToRef(this.rotation);
  20312. }
  20313. this.scaling.copyFrom(scale);
  20314. this.position.copyFrom(position);
  20315. this.parent = node;
  20316. return this;
  20317. };
  20318. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20319. /**
  20320. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20321. */
  20322. get: function () {
  20323. return this._nonUniformScaling;
  20324. },
  20325. enumerable: true,
  20326. configurable: true
  20327. });
  20328. /** @hidden */
  20329. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20330. if (this._nonUniformScaling === value) {
  20331. return false;
  20332. }
  20333. this._nonUniformScaling = value;
  20334. return true;
  20335. };
  20336. /**
  20337. * Attach the current TransformNode to another TransformNode associated with a bone
  20338. * @param bone Bone affecting the TransformNode
  20339. * @param affectedTransformNode TransformNode associated with the bone
  20340. * @returns this object
  20341. */
  20342. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20343. this._transformToBoneReferal = affectedTransformNode;
  20344. this.parent = bone;
  20345. if (bone.getWorldMatrix().determinant() < 0) {
  20346. this.scalingDeterminant *= -1;
  20347. }
  20348. return this;
  20349. };
  20350. /**
  20351. * Detach the transform node if its associated with a bone
  20352. * @returns this object
  20353. */
  20354. TransformNode.prototype.detachFromBone = function () {
  20355. if (!this.parent) {
  20356. return this;
  20357. }
  20358. if (this.parent.getWorldMatrix().determinant() < 0) {
  20359. this.scalingDeterminant *= -1;
  20360. }
  20361. this._transformToBoneReferal = null;
  20362. this.parent = null;
  20363. return this;
  20364. };
  20365. /**
  20366. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20367. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20368. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20369. * The passed axis is also normalized.
  20370. * @param axis the axis to rotate around
  20371. * @param amount the amount to rotate in radians
  20372. * @param space Space to rotate in (Default: local)
  20373. * @returns the TransformNode.
  20374. */
  20375. TransformNode.prototype.rotate = function (axis, amount, space) {
  20376. axis.normalize();
  20377. if (!this.rotationQuaternion) {
  20378. this.rotationQuaternion = this.rotation.toQuaternion();
  20379. this.rotation.setAll(0);
  20380. }
  20381. var rotationQuaternion;
  20382. if (!space || space === BABYLON.Space.LOCAL) {
  20383. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20384. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20385. }
  20386. else {
  20387. if (this.parent) {
  20388. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20389. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20390. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20391. }
  20392. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20393. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20394. }
  20395. return this;
  20396. };
  20397. /**
  20398. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20399. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20400. * The passed axis is also normalized. .
  20401. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20402. * @param point the point to rotate around
  20403. * @param axis the axis to rotate around
  20404. * @param amount the amount to rotate in radians
  20405. * @returns the TransformNode
  20406. */
  20407. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20408. axis.normalize();
  20409. if (!this.rotationQuaternion) {
  20410. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20411. this.rotation.setAll(0);
  20412. }
  20413. var tmpVector = BABYLON.Tmp.Vector3[0];
  20414. var finalScale = BABYLON.Tmp.Vector3[1];
  20415. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20416. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20417. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20418. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20419. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20420. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20421. point.subtractToRef(this.position, tmpVector);
  20422. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20423. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20424. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20425. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20426. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20427. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20428. this.position.addInPlace(finalTranslation);
  20429. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20430. return this;
  20431. };
  20432. /**
  20433. * Translates the mesh along the axis vector for the passed distance in the given space.
  20434. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20435. * @param axis the axis to translate in
  20436. * @param distance the distance to translate
  20437. * @param space Space to rotate in (Default: local)
  20438. * @returns the TransformNode.
  20439. */
  20440. TransformNode.prototype.translate = function (axis, distance, space) {
  20441. var displacementVector = axis.scale(distance);
  20442. if (!space || space === BABYLON.Space.LOCAL) {
  20443. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20444. this.setPositionWithLocalVector(tempV3);
  20445. }
  20446. else {
  20447. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20448. }
  20449. return this;
  20450. };
  20451. /**
  20452. * Adds a rotation step to the mesh current rotation.
  20453. * x, y, z are Euler angles expressed in radians.
  20454. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20455. * This means this rotation is made in the mesh local space only.
  20456. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20457. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20458. * ```javascript
  20459. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20460. * ```
  20461. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20462. * 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.
  20463. * @param x Rotation to add
  20464. * @param y Rotation to add
  20465. * @param z Rotation to add
  20466. * @returns the TransformNode.
  20467. */
  20468. TransformNode.prototype.addRotation = function (x, y, z) {
  20469. var rotationQuaternion;
  20470. if (this.rotationQuaternion) {
  20471. rotationQuaternion = this.rotationQuaternion;
  20472. }
  20473. else {
  20474. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20475. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20476. }
  20477. var accumulation = BABYLON.Tmp.Quaternion[0];
  20478. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20479. rotationQuaternion.multiplyInPlace(accumulation);
  20480. if (!this.rotationQuaternion) {
  20481. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20482. }
  20483. return this;
  20484. };
  20485. /**
  20486. * Computes the world matrix of the node
  20487. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20488. * @returns the world matrix
  20489. */
  20490. TransformNode.prototype.computeWorldMatrix = function (force) {
  20491. if (this._isWorldMatrixFrozen) {
  20492. return this._worldMatrix;
  20493. }
  20494. if (!force && this.isSynchronized()) {
  20495. this._currentRenderId = this.getScene().getRenderId();
  20496. return this._worldMatrix;
  20497. }
  20498. this._updateCache();
  20499. this._cache.position.copyFrom(this.position);
  20500. this._cache.scaling.copyFrom(this.scaling);
  20501. this._cache.pivotMatrixUpdated = false;
  20502. this._cache.billboardMode = this.billboardMode;
  20503. this._currentRenderId = this.getScene().getRenderId();
  20504. this._childRenderId = this.getScene().getRenderId();
  20505. this._isDirty = false;
  20506. // Scaling
  20507. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20508. // Rotation
  20509. //rotate, if quaternion is set and rotation was used
  20510. if (this.rotationQuaternion) {
  20511. var len = this.rotation.length();
  20512. if (len) {
  20513. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20514. this.rotation.copyFromFloats(0, 0, 0);
  20515. }
  20516. }
  20517. if (this.rotationQuaternion) {
  20518. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20519. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20520. }
  20521. else {
  20522. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20523. this._cache.rotation.copyFrom(this.rotation);
  20524. }
  20525. // Translation
  20526. var camera = this.getScene().activeCamera;
  20527. if (this.infiniteDistance && !this.parent && camera) {
  20528. var cameraWorldMatrix = camera.getWorldMatrix();
  20529. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20530. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20531. }
  20532. else {
  20533. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20534. }
  20535. // Composing transformations
  20536. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20537. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20538. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20539. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20540. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20541. // Need to decompose each rotation here
  20542. var currentPosition = BABYLON.Tmp.Vector3[3];
  20543. if (this.parent && this.parent.getWorldMatrix) {
  20544. if (this._transformToBoneReferal) {
  20545. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20546. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20547. }
  20548. else {
  20549. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20550. }
  20551. }
  20552. else {
  20553. currentPosition.copyFrom(this.position);
  20554. }
  20555. currentPosition.subtractInPlace(camera.globalPosition);
  20556. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20557. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20558. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20559. }
  20560. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20561. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20562. }
  20563. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20564. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20565. }
  20566. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20567. }
  20568. else {
  20569. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20570. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20571. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20572. }
  20573. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20574. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20575. }
  20576. // Post multiply inverse of pivotMatrix
  20577. if (this._postMultiplyPivotMatrix) {
  20578. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20579. }
  20580. // Local world
  20581. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20582. // Parent
  20583. if (this.parent && this.parent.getWorldMatrix) {
  20584. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20585. if (this._transformToBoneReferal) {
  20586. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20587. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20588. }
  20589. else {
  20590. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20591. }
  20592. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20593. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20594. this._worldMatrix.copyFrom(this._localWorld);
  20595. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20596. }
  20597. else {
  20598. if (this._transformToBoneReferal) {
  20599. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20600. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20601. }
  20602. else {
  20603. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20604. }
  20605. }
  20606. this._markSyncedWithParent();
  20607. }
  20608. else {
  20609. this._worldMatrix.copyFrom(this._localWorld);
  20610. }
  20611. // Normal matrix
  20612. if (!this.ignoreNonUniformScaling) {
  20613. if (this.scaling.isNonUniform) {
  20614. this._updateNonUniformScalingState(true);
  20615. }
  20616. else if (this.parent && this.parent._nonUniformScaling) {
  20617. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20618. }
  20619. else {
  20620. this._updateNonUniformScalingState(false);
  20621. }
  20622. }
  20623. else {
  20624. this._updateNonUniformScalingState(false);
  20625. }
  20626. this._afterComputeWorldMatrix();
  20627. // Absolute position
  20628. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20629. // Callbacks
  20630. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20631. if (!this._poseMatrix) {
  20632. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20633. }
  20634. // Cache the determinant
  20635. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20636. return this._worldMatrix;
  20637. };
  20638. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20639. };
  20640. /**
  20641. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20642. * @param func callback function to add
  20643. *
  20644. * @returns the TransformNode.
  20645. */
  20646. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20647. this.onAfterWorldMatrixUpdateObservable.add(func);
  20648. return this;
  20649. };
  20650. /**
  20651. * Removes a registered callback function.
  20652. * @param func callback function to remove
  20653. * @returns the TransformNode.
  20654. */
  20655. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20656. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20657. return this;
  20658. };
  20659. /**
  20660. * Clone the current transform node
  20661. * @param name Name of the new clone
  20662. * @param newParent New parent for the clone
  20663. * @param doNotCloneChildren Do not clone children hierarchy
  20664. * @returns the new transform node
  20665. */
  20666. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20667. var _this = this;
  20668. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20669. result.name = name;
  20670. result.id = name;
  20671. if (newParent) {
  20672. result.parent = newParent;
  20673. }
  20674. if (!doNotCloneChildren) {
  20675. // Children
  20676. var directDescendants = this.getDescendants(true);
  20677. for (var index = 0; index < directDescendants.length; index++) {
  20678. var child = directDescendants[index];
  20679. if (child.clone) {
  20680. child.clone(name + "." + child.name, result);
  20681. }
  20682. }
  20683. }
  20684. return result;
  20685. };
  20686. /**
  20687. * Serializes the objects information.
  20688. * @param currentSerializationObject defines the object to serialize in
  20689. * @returns the serialized object
  20690. */
  20691. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20692. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20693. serializationObject.type = this.getClassName();
  20694. // Parent
  20695. if (this.parent) {
  20696. serializationObject.parentId = this.parent.id;
  20697. }
  20698. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20699. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20700. }
  20701. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20702. serializationObject.isEnabled = this.isEnabled();
  20703. // Parent
  20704. if (this.parent) {
  20705. serializationObject.parentId = this.parent.id;
  20706. }
  20707. return serializationObject;
  20708. };
  20709. // Statics
  20710. /**
  20711. * Returns a new TransformNode object parsed from the source provided.
  20712. * @param parsedTransformNode is the source.
  20713. * @param scene the scne the object belongs to
  20714. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20715. * @returns a new TransformNode object parsed from the source provided.
  20716. */
  20717. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20718. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20719. if (BABYLON.Tags) {
  20720. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20721. }
  20722. if (parsedTransformNode.localMatrix) {
  20723. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20724. }
  20725. else if (parsedTransformNode.pivotMatrix) {
  20726. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20727. }
  20728. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20729. // Parent
  20730. if (parsedTransformNode.parentId) {
  20731. transformNode._waitingParentId = parsedTransformNode.parentId;
  20732. }
  20733. return transformNode;
  20734. };
  20735. /**
  20736. * Releases resources associated with this transform node.
  20737. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20738. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20739. */
  20740. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20741. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20742. // Animations
  20743. this.getScene().stopAnimation(this);
  20744. // Remove from scene
  20745. this.getScene().removeTransformNode(this);
  20746. this.onAfterWorldMatrixUpdateObservable.clear();
  20747. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20748. };
  20749. // Statics
  20750. /**
  20751. * Object will not rotate to face the camera
  20752. */
  20753. TransformNode.BILLBOARDMODE_NONE = 0;
  20754. /**
  20755. * Object will rotate to face the camera but only on the x axis
  20756. */
  20757. TransformNode.BILLBOARDMODE_X = 1;
  20758. /**
  20759. * Object will rotate to face the camera but only on the y axis
  20760. */
  20761. TransformNode.BILLBOARDMODE_Y = 2;
  20762. /**
  20763. * Object will rotate to face the camera but only on the z axis
  20764. */
  20765. TransformNode.BILLBOARDMODE_Z = 4;
  20766. /**
  20767. * Object will rotate to face the camera
  20768. */
  20769. TransformNode.BILLBOARDMODE_ALL = 7;
  20770. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20771. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20772. __decorate([
  20773. BABYLON.serializeAsVector3("position")
  20774. ], TransformNode.prototype, "_position", void 0);
  20775. __decorate([
  20776. BABYLON.serializeAsVector3("rotation")
  20777. ], TransformNode.prototype, "_rotation", void 0);
  20778. __decorate([
  20779. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20780. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20781. __decorate([
  20782. BABYLON.serializeAsVector3("scaling")
  20783. ], TransformNode.prototype, "_scaling", void 0);
  20784. __decorate([
  20785. BABYLON.serialize()
  20786. ], TransformNode.prototype, "billboardMode", void 0);
  20787. __decorate([
  20788. BABYLON.serialize()
  20789. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20790. __decorate([
  20791. BABYLON.serialize()
  20792. ], TransformNode.prototype, "infiniteDistance", void 0);
  20793. __decorate([
  20794. BABYLON.serialize()
  20795. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20796. return TransformNode;
  20797. }(BABYLON.Node));
  20798. BABYLON.TransformNode = TransformNode;
  20799. })(BABYLON || (BABYLON = {}));
  20800. //# sourceMappingURL=babylon.transformNode.js.map
  20801. var BABYLON;
  20802. (function (BABYLON) {
  20803. /** @hidden */
  20804. var _FacetDataStorage = /** @class */ (function () {
  20805. function _FacetDataStorage() {
  20806. this.facetNb = 0; // facet number
  20807. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20808. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20809. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20810. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20811. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20812. this.subDiv = {
  20813. max: 1,
  20814. X: 1,
  20815. Y: 1,
  20816. Z: 1
  20817. };
  20818. this.facetDepthSort = false; // is the facet depth sort to be computed
  20819. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20820. }
  20821. return _FacetDataStorage;
  20822. }());
  20823. /**
  20824. * Class used to store all common mesh properties
  20825. */
  20826. var AbstractMesh = /** @class */ (function (_super) {
  20827. __extends(AbstractMesh, _super);
  20828. // Constructor
  20829. /**
  20830. * Creates a new AbstractMesh
  20831. * @param name defines the name of the mesh
  20832. * @param scene defines the hosting scene
  20833. */
  20834. function AbstractMesh(name, scene) {
  20835. if (scene === void 0) { scene = null; }
  20836. var _this = _super.call(this, name, scene, false) || this;
  20837. _this._facetData = new _FacetDataStorage();
  20838. /** Gets ot sets the culling strategy to use to find visible meshes */
  20839. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20840. // Events
  20841. /**
  20842. * An event triggered when this mesh collides with another one
  20843. */
  20844. _this.onCollideObservable = new BABYLON.Observable();
  20845. /**
  20846. * An event triggered when the collision's position changes
  20847. */
  20848. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20849. /**
  20850. * An event triggered when material is changed
  20851. */
  20852. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20853. // Properties
  20854. /**
  20855. * Gets or sets the orientation for POV movement & rotation
  20856. */
  20857. _this.definedFacingForward = true;
  20858. _this._visibility = 1.0;
  20859. /** Gets or sets the alpha index used to sort transparent meshes
  20860. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20861. */
  20862. _this.alphaIndex = Number.MAX_VALUE;
  20863. /**
  20864. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20865. */
  20866. _this.isVisible = true;
  20867. /**
  20868. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20869. */
  20870. _this.isPickable = true;
  20871. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20872. _this.showSubMeshesBoundingBox = false;
  20873. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20874. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20875. */
  20876. _this.isBlocker = false;
  20877. /**
  20878. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20879. */
  20880. _this.enablePointerMoveEvents = false;
  20881. /**
  20882. * Specifies the rendering group id for this mesh (0 by default)
  20883. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20884. */
  20885. _this.renderingGroupId = 0;
  20886. _this._receiveShadows = false;
  20887. /** Defines color to use when rendering outline */
  20888. _this.outlineColor = BABYLON.Color3.Red();
  20889. /** Define width to use when rendering outline */
  20890. _this.outlineWidth = 0.02;
  20891. /** Defines color to use when rendering overlay */
  20892. _this.overlayColor = BABYLON.Color3.Red();
  20893. /** Defines alpha to use when rendering overlay */
  20894. _this.overlayAlpha = 0.5;
  20895. _this._hasVertexAlpha = false;
  20896. _this._useVertexColors = true;
  20897. _this._computeBonesUsingShaders = true;
  20898. _this._numBoneInfluencers = 4;
  20899. _this._applyFog = true;
  20900. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20901. _this.useOctreeForRenderingSelection = true;
  20902. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20903. _this.useOctreeForPicking = true;
  20904. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20905. _this.useOctreeForCollisions = true;
  20906. _this._layerMask = 0x0FFFFFFF;
  20907. /**
  20908. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20909. */
  20910. _this.alwaysSelectAsActiveMesh = false;
  20911. /**
  20912. * Gets or sets the current action manager
  20913. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20914. */
  20915. _this.actionManager = null;
  20916. // Collisions
  20917. _this._checkCollisions = false;
  20918. _this._collisionMask = -1;
  20919. _this._collisionGroup = -1;
  20920. /**
  20921. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20922. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20923. */
  20924. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20925. /**
  20926. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20927. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20928. */
  20929. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20930. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20931. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20932. // Edges
  20933. /**
  20934. * Defines edge width used when edgesRenderer is enabled
  20935. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20936. */
  20937. _this.edgesWidth = 1;
  20938. /**
  20939. * Defines edge color used when edgesRenderer is enabled
  20940. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20941. */
  20942. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20943. /** @hidden */
  20944. _this._renderId = 0;
  20945. /** @hidden */
  20946. _this._intersectionsInProgress = new Array();
  20947. /** @hidden */
  20948. _this._unIndexed = false;
  20949. /** @hidden */
  20950. _this._lightSources = new Array();
  20951. /**
  20952. * An event triggered when the mesh is rebuilt.
  20953. */
  20954. _this.onRebuildObservable = new BABYLON.Observable();
  20955. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20956. if (collidedMesh === void 0) { collidedMesh = null; }
  20957. //TODO move this to the collision coordinator!
  20958. if (_this.getScene().workerCollisions) {
  20959. newPosition.multiplyInPlace(_this._collider._radius);
  20960. }
  20961. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20962. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20963. _this.position.addInPlace(_this._diffPositionForCollisions);
  20964. }
  20965. if (collidedMesh) {
  20966. _this.onCollideObservable.notifyObservers(collidedMesh);
  20967. }
  20968. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20969. };
  20970. _this.getScene().addMesh(_this);
  20971. _this._resyncLightSources();
  20972. return _this;
  20973. }
  20974. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20975. /**
  20976. * No billboard
  20977. */
  20978. get: function () {
  20979. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20980. },
  20981. enumerable: true,
  20982. configurable: true
  20983. });
  20984. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20985. /** Billboard on X axis */
  20986. get: function () {
  20987. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20988. },
  20989. enumerable: true,
  20990. configurable: true
  20991. });
  20992. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20993. /** Billboard on Y axis */
  20994. get: function () {
  20995. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20996. },
  20997. enumerable: true,
  20998. configurable: true
  20999. });
  21000. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  21001. /** Billboard on Z axis */
  21002. get: function () {
  21003. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  21004. },
  21005. enumerable: true,
  21006. configurable: true
  21007. });
  21008. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  21009. /** Billboard on all axes */
  21010. get: function () {
  21011. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  21012. },
  21013. enumerable: true,
  21014. configurable: true
  21015. });
  21016. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  21017. /**
  21018. * Gets the number of facets in the mesh
  21019. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21020. */
  21021. get: function () {
  21022. return this._facetData.facetNb;
  21023. },
  21024. enumerable: true,
  21025. configurable: true
  21026. });
  21027. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  21028. /**
  21029. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  21030. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21031. */
  21032. get: function () {
  21033. return this._facetData.partitioningSubdivisions;
  21034. },
  21035. set: function (nb) {
  21036. this._facetData.partitioningSubdivisions = nb;
  21037. },
  21038. enumerable: true,
  21039. configurable: true
  21040. });
  21041. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21042. /**
  21043. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21044. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21045. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21046. */
  21047. get: function () {
  21048. return this._facetData.partitioningBBoxRatio;
  21049. },
  21050. set: function (ratio) {
  21051. this._facetData.partitioningBBoxRatio = ratio;
  21052. },
  21053. enumerable: true,
  21054. configurable: true
  21055. });
  21056. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21057. /**
  21058. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21059. * Works only for updatable meshes.
  21060. * Doesn't work with multi-materials
  21061. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21062. */
  21063. get: function () {
  21064. return this._facetData.facetDepthSort;
  21065. },
  21066. set: function (sort) {
  21067. this._facetData.facetDepthSort = sort;
  21068. },
  21069. enumerable: true,
  21070. configurable: true
  21071. });
  21072. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21073. /**
  21074. * The location (Vector3) where the facet depth sort must be computed from.
  21075. * By default, the active camera position.
  21076. * Used only when facet depth sort is enabled
  21077. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21078. */
  21079. get: function () {
  21080. return this._facetData.facetDepthSortFrom;
  21081. },
  21082. set: function (location) {
  21083. this._facetData.facetDepthSortFrom = location;
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21089. /**
  21090. * gets a boolean indicating if facetData is enabled
  21091. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21092. */
  21093. get: function () {
  21094. return this._facetData.facetDataEnabled;
  21095. },
  21096. enumerable: true,
  21097. configurable: true
  21098. });
  21099. /** @hidden */
  21100. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21101. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21102. return false;
  21103. }
  21104. this._markSubMeshesAsMiscDirty();
  21105. return true;
  21106. };
  21107. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21108. /** Set a function to call when this mesh collides with another one */
  21109. set: function (callback) {
  21110. if (this._onCollideObserver) {
  21111. this.onCollideObservable.remove(this._onCollideObserver);
  21112. }
  21113. this._onCollideObserver = this.onCollideObservable.add(callback);
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21119. /** Set a function to call when the collision's position changes */
  21120. set: function (callback) {
  21121. if (this._onCollisionPositionChangeObserver) {
  21122. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21123. }
  21124. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21125. },
  21126. enumerable: true,
  21127. configurable: true
  21128. });
  21129. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21130. /**
  21131. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21132. */
  21133. get: function () {
  21134. return this._visibility;
  21135. },
  21136. /**
  21137. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21138. */
  21139. set: function (value) {
  21140. if (this._visibility === value) {
  21141. return;
  21142. }
  21143. this._visibility = value;
  21144. this._markSubMeshesAsMiscDirty();
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Object.defineProperty(AbstractMesh.prototype, "material", {
  21150. /** Gets or sets current material */
  21151. get: function () {
  21152. return this._material;
  21153. },
  21154. set: function (value) {
  21155. if (this._material === value) {
  21156. return;
  21157. }
  21158. // remove from material mesh map id needed
  21159. if (this._material && this._material.meshMap) {
  21160. this._material.meshMap[this.uniqueId] = undefined;
  21161. }
  21162. this._material = value;
  21163. if (value && value.meshMap) {
  21164. value.meshMap[this.uniqueId] = this;
  21165. }
  21166. if (this.onMaterialChangedObservable.hasObservers) {
  21167. this.onMaterialChangedObservable.notifyObservers(this);
  21168. }
  21169. if (!this.subMeshes) {
  21170. return;
  21171. }
  21172. this._unBindEffect();
  21173. },
  21174. enumerable: true,
  21175. configurable: true
  21176. });
  21177. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21178. /**
  21179. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21180. * @see http://doc.babylonjs.com/babylon101/shadows
  21181. */
  21182. get: function () {
  21183. return this._receiveShadows;
  21184. },
  21185. set: function (value) {
  21186. if (this._receiveShadows === value) {
  21187. return;
  21188. }
  21189. this._receiveShadows = value;
  21190. this._markSubMeshesAsLightDirty();
  21191. },
  21192. enumerable: true,
  21193. configurable: true
  21194. });
  21195. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21196. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21197. get: function () {
  21198. return this._hasVertexAlpha;
  21199. },
  21200. set: function (value) {
  21201. if (this._hasVertexAlpha === value) {
  21202. return;
  21203. }
  21204. this._hasVertexAlpha = value;
  21205. this._markSubMeshesAsAttributesDirty();
  21206. this._markSubMeshesAsMiscDirty();
  21207. },
  21208. enumerable: true,
  21209. configurable: true
  21210. });
  21211. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21212. /** 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) */
  21213. get: function () {
  21214. return this._useVertexColors;
  21215. },
  21216. set: function (value) {
  21217. if (this._useVertexColors === value) {
  21218. return;
  21219. }
  21220. this._useVertexColors = value;
  21221. this._markSubMeshesAsAttributesDirty();
  21222. },
  21223. enumerable: true,
  21224. configurable: true
  21225. });
  21226. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21227. /**
  21228. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21229. */
  21230. get: function () {
  21231. return this._computeBonesUsingShaders;
  21232. },
  21233. set: function (value) {
  21234. if (this._computeBonesUsingShaders === value) {
  21235. return;
  21236. }
  21237. this._computeBonesUsingShaders = value;
  21238. this._markSubMeshesAsAttributesDirty();
  21239. },
  21240. enumerable: true,
  21241. configurable: true
  21242. });
  21243. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21244. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21245. get: function () {
  21246. return this._numBoneInfluencers;
  21247. },
  21248. set: function (value) {
  21249. if (this._numBoneInfluencers === value) {
  21250. return;
  21251. }
  21252. this._numBoneInfluencers = value;
  21253. this._markSubMeshesAsAttributesDirty();
  21254. },
  21255. enumerable: true,
  21256. configurable: true
  21257. });
  21258. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21259. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21260. get: function () {
  21261. return this._applyFog;
  21262. },
  21263. set: function (value) {
  21264. if (this._applyFog === value) {
  21265. return;
  21266. }
  21267. this._applyFog = value;
  21268. this._markSubMeshesAsMiscDirty();
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21274. /**
  21275. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21276. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21277. */
  21278. get: function () {
  21279. return this._layerMask;
  21280. },
  21281. set: function (value) {
  21282. if (value === this._layerMask) {
  21283. return;
  21284. }
  21285. this._layerMask = value;
  21286. this._resyncLightSources();
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21292. /**
  21293. * Gets or sets a collision mask used to mask collisions (default is -1).
  21294. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21295. */
  21296. get: function () {
  21297. return this._collisionMask;
  21298. },
  21299. set: function (mask) {
  21300. this._collisionMask = !isNaN(mask) ? mask : -1;
  21301. },
  21302. enumerable: true,
  21303. configurable: true
  21304. });
  21305. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21306. /**
  21307. * Gets or sets the current collision group mask (-1 by default).
  21308. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21309. */
  21310. get: function () {
  21311. return this._collisionGroup;
  21312. },
  21313. set: function (mask) {
  21314. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21320. /** @hidden */
  21321. get: function () {
  21322. return null;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21328. get: function () {
  21329. return this._skeleton;
  21330. },
  21331. /**
  21332. * Gets or sets a skeleton to apply skining transformations
  21333. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21334. */
  21335. set: function (value) {
  21336. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21337. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21338. }
  21339. if (value && value.needInitialSkinMatrix) {
  21340. value._registerMeshWithPoseMatrix(this);
  21341. }
  21342. this._skeleton = value;
  21343. if (!this._skeleton) {
  21344. this._bonesTransformMatrices = null;
  21345. }
  21346. this._markSubMeshesAsAttributesDirty();
  21347. },
  21348. enumerable: true,
  21349. configurable: true
  21350. });
  21351. /**
  21352. * Returns the string "AbstractMesh"
  21353. * @returns "AbstractMesh"
  21354. */
  21355. AbstractMesh.prototype.getClassName = function () {
  21356. return "AbstractMesh";
  21357. };
  21358. /**
  21359. * Gets a string representation of the current mesh
  21360. * @param fullDetails defines a boolean indicating if full details must be included
  21361. * @returns a string representation of the current mesh
  21362. */
  21363. AbstractMesh.prototype.toString = function (fullDetails) {
  21364. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21365. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21366. if (this._skeleton) {
  21367. ret += ", skeleton: " + this._skeleton.name;
  21368. }
  21369. if (fullDetails) {
  21370. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21371. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21372. }
  21373. return ret;
  21374. };
  21375. /** @hidden */
  21376. AbstractMesh.prototype._rebuild = function () {
  21377. this.onRebuildObservable.notifyObservers(this);
  21378. if (this._occlusionQuery) {
  21379. this._occlusionQuery = null;
  21380. }
  21381. if (!this.subMeshes) {
  21382. return;
  21383. }
  21384. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21385. var subMesh = _a[_i];
  21386. subMesh._rebuild();
  21387. }
  21388. };
  21389. /** @hidden */
  21390. AbstractMesh.prototype._resyncLightSources = function () {
  21391. this._lightSources.length = 0;
  21392. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21393. var light = _a[_i];
  21394. if (!light.isEnabled()) {
  21395. continue;
  21396. }
  21397. if (light.canAffectMesh(this)) {
  21398. this._lightSources.push(light);
  21399. }
  21400. }
  21401. this._markSubMeshesAsLightDirty();
  21402. };
  21403. /** @hidden */
  21404. AbstractMesh.prototype._resyncLighSource = function (light) {
  21405. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21406. var index = this._lightSources.indexOf(light);
  21407. if (index === -1) {
  21408. if (!isIn) {
  21409. return;
  21410. }
  21411. this._lightSources.push(light);
  21412. }
  21413. else {
  21414. if (isIn) {
  21415. return;
  21416. }
  21417. this._lightSources.splice(index, 1);
  21418. }
  21419. this._markSubMeshesAsLightDirty();
  21420. };
  21421. /** @hidden */
  21422. AbstractMesh.prototype._unBindEffect = function () {
  21423. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21424. var subMesh = _a[_i];
  21425. subMesh.setEffect(null);
  21426. }
  21427. };
  21428. /** @hidden */
  21429. AbstractMesh.prototype._removeLightSource = function (light) {
  21430. var index = this._lightSources.indexOf(light);
  21431. if (index === -1) {
  21432. return;
  21433. }
  21434. this._lightSources.splice(index, 1);
  21435. this._markSubMeshesAsLightDirty();
  21436. };
  21437. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21438. if (!this.subMeshes) {
  21439. return;
  21440. }
  21441. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21442. var subMesh = _a[_i];
  21443. if (subMesh._materialDefines) {
  21444. func(subMesh._materialDefines);
  21445. }
  21446. }
  21447. };
  21448. /** @hidden */
  21449. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21450. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21451. };
  21452. /** @hidden */
  21453. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21454. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21455. };
  21456. /** @hidden */
  21457. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21458. if (!this.subMeshes) {
  21459. return;
  21460. }
  21461. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21462. var subMesh = _a[_i];
  21463. var material = subMesh.getMaterial();
  21464. if (material) {
  21465. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21466. }
  21467. }
  21468. };
  21469. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21470. /**
  21471. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21472. */
  21473. get: function () {
  21474. return this._scaling;
  21475. },
  21476. set: function (newScaling) {
  21477. this._scaling = newScaling;
  21478. if (this.physicsImpostor) {
  21479. this.physicsImpostor.forceUpdate();
  21480. }
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21486. // Methods
  21487. /**
  21488. * Returns true if the mesh is blocked. Implemented by child classes
  21489. */
  21490. get: function () {
  21491. return false;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. /**
  21497. * Returns the mesh itself by default. Implemented by child classes
  21498. * @param camera defines the camera to use to pick the right LOD level
  21499. * @returns the currentAbstractMesh
  21500. */
  21501. AbstractMesh.prototype.getLOD = function (camera) {
  21502. return this;
  21503. };
  21504. /**
  21505. * Returns 0 by default. Implemented by child classes
  21506. * @returns an integer
  21507. */
  21508. AbstractMesh.prototype.getTotalVertices = function () {
  21509. return 0;
  21510. };
  21511. /**
  21512. * Returns null by default. Implemented by child classes
  21513. * @returns null
  21514. */
  21515. AbstractMesh.prototype.getIndices = function () {
  21516. return null;
  21517. };
  21518. /**
  21519. * Returns the array of the requested vertex data kind. Implemented by child classes
  21520. * @param kind defines the vertex data kind to use
  21521. * @returns null
  21522. */
  21523. AbstractMesh.prototype.getVerticesData = function (kind) {
  21524. return null;
  21525. };
  21526. /**
  21527. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21528. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21529. * Note that a new underlying VertexBuffer object is created each call.
  21530. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21531. * @param kind defines vertex data kind:
  21532. * * BABYLON.VertexBuffer.PositionKind
  21533. * * BABYLON.VertexBuffer.UVKind
  21534. * * BABYLON.VertexBuffer.UV2Kind
  21535. * * BABYLON.VertexBuffer.UV3Kind
  21536. * * BABYLON.VertexBuffer.UV4Kind
  21537. * * BABYLON.VertexBuffer.UV5Kind
  21538. * * BABYLON.VertexBuffer.UV6Kind
  21539. * * BABYLON.VertexBuffer.ColorKind
  21540. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21541. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21542. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21543. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21544. * @param data defines the data source
  21545. * @param updatable defines if the data must be flagged as updatable (or static)
  21546. * @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
  21547. * @returns the current mesh
  21548. */
  21549. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21550. return this;
  21551. };
  21552. /**
  21553. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21554. * If the mesh has no geometry, it is simply returned as it is.
  21555. * @param kind defines vertex data kind:
  21556. * * BABYLON.VertexBuffer.PositionKind
  21557. * * BABYLON.VertexBuffer.UVKind
  21558. * * BABYLON.VertexBuffer.UV2Kind
  21559. * * BABYLON.VertexBuffer.UV3Kind
  21560. * * BABYLON.VertexBuffer.UV4Kind
  21561. * * BABYLON.VertexBuffer.UV5Kind
  21562. * * BABYLON.VertexBuffer.UV6Kind
  21563. * * BABYLON.VertexBuffer.ColorKind
  21564. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21565. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21566. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21567. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21568. * @param data defines the data source
  21569. * @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
  21570. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21571. * @returns the current mesh
  21572. */
  21573. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21574. return this;
  21575. };
  21576. /**
  21577. * Sets the mesh indices,
  21578. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21579. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21580. * @param totalVertices Defines the total number of vertices
  21581. * @returns the current mesh
  21582. */
  21583. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21584. return this;
  21585. };
  21586. /**
  21587. * Gets a boolean indicating if specific vertex data is present
  21588. * @param kind defines the vertex data kind to use
  21589. * @returns true is data kind is present
  21590. */
  21591. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21592. return false;
  21593. };
  21594. /**
  21595. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21596. * @returns a BoundingInfo
  21597. */
  21598. AbstractMesh.prototype.getBoundingInfo = function () {
  21599. if (this._masterMesh) {
  21600. return this._masterMesh.getBoundingInfo();
  21601. }
  21602. if (!this._boundingInfo) {
  21603. // this._boundingInfo is being created here
  21604. this._updateBoundingInfo();
  21605. }
  21606. // cannot be null.
  21607. return this._boundingInfo;
  21608. };
  21609. /**
  21610. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21611. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21612. * @returns the current mesh
  21613. */
  21614. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21615. if (includeDescendants === void 0) { includeDescendants = true; }
  21616. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21617. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21618. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21619. if (maxDimension === 0) {
  21620. return this;
  21621. }
  21622. var scale = 1 / maxDimension;
  21623. this.scaling.scaleInPlace(scale);
  21624. return this;
  21625. };
  21626. /**
  21627. * Overwrite the current bounding info
  21628. * @param boundingInfo defines the new bounding info
  21629. * @returns the current mesh
  21630. */
  21631. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21632. this._boundingInfo = boundingInfo;
  21633. return this;
  21634. };
  21635. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21636. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21637. get: function () {
  21638. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. /** @hidden */
  21644. AbstractMesh.prototype._preActivate = function () {
  21645. };
  21646. /** @hidden */
  21647. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21648. };
  21649. /** @hidden */
  21650. AbstractMesh.prototype._activate = function (renderId) {
  21651. this._renderId = renderId;
  21652. };
  21653. /**
  21654. * Gets the current world matrix
  21655. * @returns a Matrix
  21656. */
  21657. AbstractMesh.prototype.getWorldMatrix = function () {
  21658. if (this._masterMesh) {
  21659. return this._masterMesh.getWorldMatrix();
  21660. }
  21661. return _super.prototype.getWorldMatrix.call(this);
  21662. };
  21663. /** @hidden */
  21664. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21665. if (this._masterMesh) {
  21666. return this._masterMesh._getWorldMatrixDeterminant();
  21667. }
  21668. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21669. };
  21670. // ================================== Point of View Movement =================================
  21671. /**
  21672. * Perform relative position change from the point of view of behind the front of the mesh.
  21673. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21674. * Supports definition of mesh facing forward or backward
  21675. * @param amountRight defines the distance on the right axis
  21676. * @param amountUp defines the distance on the up axis
  21677. * @param amountForward defines the distance on the forward axis
  21678. * @returns the current mesh
  21679. */
  21680. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21681. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21682. return this;
  21683. };
  21684. /**
  21685. * Calculate relative position change from the point of view of behind the front of the mesh.
  21686. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21687. * Supports definition of mesh facing forward or backward
  21688. * @param amountRight defines the distance on the right axis
  21689. * @param amountUp defines the distance on the up axis
  21690. * @param amountForward defines the distance on the forward axis
  21691. * @returns the new displacement vector
  21692. */
  21693. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21694. var rotMatrix = new BABYLON.Matrix();
  21695. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21696. rotQuaternion.toRotationMatrix(rotMatrix);
  21697. var translationDelta = BABYLON.Vector3.Zero();
  21698. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21699. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21700. return translationDelta;
  21701. };
  21702. // ================================== Point of View Rotation =================================
  21703. /**
  21704. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21705. * Supports definition of mesh facing forward or backward
  21706. * @param flipBack defines the flip
  21707. * @param twirlClockwise defines the twirl
  21708. * @param tiltRight defines the tilt
  21709. * @returns the current mesh
  21710. */
  21711. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21712. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21713. return this;
  21714. };
  21715. /**
  21716. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21717. * Supports definition of mesh facing forward or backward.
  21718. * @param flipBack defines the flip
  21719. * @param twirlClockwise defines the twirl
  21720. * @param tiltRight defines the tilt
  21721. * @returns the new rotation vector
  21722. */
  21723. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21724. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21725. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21726. };
  21727. /**
  21728. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21729. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21730. * @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
  21731. * @returns the new bounding vectors
  21732. */
  21733. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21734. if (includeDescendants === void 0) { includeDescendants = true; }
  21735. if (predicate === void 0) { predicate = null; }
  21736. // Ensures that all world matrix will be recomputed.
  21737. this.getScene().incrementRenderId();
  21738. this.computeWorldMatrix(true);
  21739. var min;
  21740. var max;
  21741. var boundingInfo = this.getBoundingInfo();
  21742. if (!this.subMeshes) {
  21743. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21744. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21745. }
  21746. else {
  21747. min = boundingInfo.boundingBox.minimumWorld;
  21748. max = boundingInfo.boundingBox.maximumWorld;
  21749. }
  21750. if (includeDescendants) {
  21751. var descendants = this.getDescendants(false);
  21752. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21753. var descendant = descendants_1[_i];
  21754. var childMesh = descendant;
  21755. childMesh.computeWorldMatrix(true);
  21756. // Filters meshes based on custom predicate function.
  21757. if (predicate && !predicate(childMesh)) {
  21758. continue;
  21759. }
  21760. //make sure we have the needed params to get mix and max
  21761. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21762. continue;
  21763. }
  21764. var childBoundingInfo = childMesh.getBoundingInfo();
  21765. var boundingBox = childBoundingInfo.boundingBox;
  21766. var minBox = boundingBox.minimumWorld;
  21767. var maxBox = boundingBox.maximumWorld;
  21768. BABYLON.Tools.CheckExtends(minBox, min, max);
  21769. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21770. }
  21771. }
  21772. return {
  21773. min: min,
  21774. max: max
  21775. };
  21776. };
  21777. /** @hidden */
  21778. AbstractMesh.prototype._updateBoundingInfo = function () {
  21779. if (this._boundingInfo) {
  21780. this._boundingInfo.update(this.worldMatrixFromCache);
  21781. }
  21782. else {
  21783. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  21784. }
  21785. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21786. return this;
  21787. };
  21788. /** @hidden */
  21789. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21790. if (!this.subMeshes) {
  21791. return this;
  21792. }
  21793. var count = this.subMeshes.length;
  21794. for (var subIndex = 0; subIndex < count; subIndex++) {
  21795. var subMesh = this.subMeshes[subIndex];
  21796. if (count > 1 || !subMesh.IsGlobal) {
  21797. subMesh.updateBoundingInfo(matrix);
  21798. }
  21799. }
  21800. return this;
  21801. };
  21802. /** @hidden */
  21803. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21804. // Bounding info
  21805. this._updateBoundingInfo();
  21806. };
  21807. /**
  21808. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21809. * A mesh is in the frustum if its bounding box intersects the frustum
  21810. * @param frustumPlanes defines the frustum to test
  21811. * @returns true if the mesh is in the frustum planes
  21812. */
  21813. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21814. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21815. };
  21816. /**
  21817. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21818. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21819. * @param frustumPlanes defines the frustum to test
  21820. * @returns true if the mesh is completely in the frustum planes
  21821. */
  21822. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21823. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21824. };
  21825. /**
  21826. * True if the mesh intersects another mesh or a SolidParticle object
  21827. * @param mesh defines a target mesh or SolidParticle to test
  21828. * @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)
  21829. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21830. * @returns true if there is an intersection
  21831. */
  21832. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21833. if (precise === void 0) { precise = false; }
  21834. if (!this._boundingInfo || !mesh._boundingInfo) {
  21835. return false;
  21836. }
  21837. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21838. return true;
  21839. }
  21840. if (includeDescendants) {
  21841. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21842. var child = _a[_i];
  21843. if (child.intersectsMesh(mesh, precise, true)) {
  21844. return true;
  21845. }
  21846. }
  21847. }
  21848. return false;
  21849. };
  21850. /**
  21851. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21852. * @param point defines the point to test
  21853. * @returns true if there is an intersection
  21854. */
  21855. AbstractMesh.prototype.intersectsPoint = function (point) {
  21856. if (!this._boundingInfo) {
  21857. return false;
  21858. }
  21859. return this._boundingInfo.intersectsPoint(point);
  21860. };
  21861. /**
  21862. * Gets the position of the current mesh in camera space
  21863. * @param camera defines the camera to use
  21864. * @returns a position
  21865. */
  21866. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21867. if (camera === void 0) { camera = null; }
  21868. if (!camera) {
  21869. camera = this.getScene().activeCamera;
  21870. }
  21871. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21872. };
  21873. /**
  21874. * Returns the distance from the mesh to the active camera
  21875. * @param camera defines the camera to use
  21876. * @returns the distance
  21877. */
  21878. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21879. if (camera === void 0) { camera = null; }
  21880. if (!camera) {
  21881. camera = this.getScene().activeCamera;
  21882. }
  21883. return this.absolutePosition.subtract(camera.position).length();
  21884. };
  21885. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21886. // Collisions
  21887. /**
  21888. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21889. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21890. */
  21891. get: function () {
  21892. return this._checkCollisions;
  21893. },
  21894. set: function (collisionEnabled) {
  21895. this._checkCollisions = collisionEnabled;
  21896. if (this.getScene().workerCollisions) {
  21897. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21898. }
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21904. /**
  21905. * Gets Collider object used to compute collisions (not physics)
  21906. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21907. */
  21908. get: function () {
  21909. return this._collider;
  21910. },
  21911. enumerable: true,
  21912. configurable: true
  21913. });
  21914. /**
  21915. * Move the mesh using collision engine
  21916. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21917. * @param displacement defines the requested displacement vector
  21918. * @returns the current mesh
  21919. */
  21920. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21921. var globalPosition = this.getAbsolutePosition();
  21922. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21923. if (!this._collider) {
  21924. this._collider = new BABYLON.Collider();
  21925. }
  21926. this._collider._radius = this.ellipsoid;
  21927. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21928. return this;
  21929. };
  21930. // Collisions
  21931. /** @hidden */
  21932. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21933. this._generatePointsArray();
  21934. if (!this._positions) {
  21935. return this;
  21936. }
  21937. // Transformation
  21938. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21939. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21940. subMesh._lastColliderWorldVertices = [];
  21941. subMesh._trianglePlanes = [];
  21942. var start = subMesh.verticesStart;
  21943. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21944. for (var i = start; i < end; i++) {
  21945. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21946. }
  21947. }
  21948. // Collide
  21949. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21950. if (collider.collisionFound) {
  21951. collider.collidedMesh = this;
  21952. }
  21953. return this;
  21954. };
  21955. /** @hidden */
  21956. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21957. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21958. var len = subMeshes.length;
  21959. for (var index = 0; index < len; index++) {
  21960. var subMesh = subMeshes.data[index];
  21961. // Bounding test
  21962. if (len > 1 && !subMesh._checkCollision(collider)) {
  21963. continue;
  21964. }
  21965. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21966. }
  21967. return this;
  21968. };
  21969. /** @hidden */
  21970. AbstractMesh.prototype._checkCollision = function (collider) {
  21971. // Bounding box test
  21972. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21973. return this;
  21974. }
  21975. // Transformation matrix
  21976. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21977. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21978. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21979. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21980. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21981. return this;
  21982. };
  21983. // Picking
  21984. /** @hidden */
  21985. AbstractMesh.prototype._generatePointsArray = function () {
  21986. return false;
  21987. };
  21988. /**
  21989. * Checks if the passed Ray intersects with the mesh
  21990. * @param ray defines the ray to use
  21991. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21992. * @returns the picking info
  21993. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21994. */
  21995. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21996. var pickingInfo = new BABYLON.PickingInfo();
  21997. var intersectionTreshold = this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0;
  21998. var boundingInfo = this._boundingInfo;
  21999. if (!this.subMeshes || !boundingInfo || !ray.intersectsSphere(boundingInfo.boundingSphere, intersectionTreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionTreshold)) {
  22000. return pickingInfo;
  22001. }
  22002. if (!this._generatePointsArray()) {
  22003. return pickingInfo;
  22004. }
  22005. var intersectInfo = null;
  22006. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  22007. var len = subMeshes.length;
  22008. for (var index = 0; index < len; index++) {
  22009. var subMesh = subMeshes.data[index];
  22010. // Bounding test
  22011. if (len > 1 && !subMesh.canIntersects(ray)) {
  22012. continue;
  22013. }
  22014. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  22015. if (currentIntersectInfo) {
  22016. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22017. intersectInfo = currentIntersectInfo;
  22018. intersectInfo.subMeshId = index;
  22019. if (fastCheck) {
  22020. break;
  22021. }
  22022. }
  22023. }
  22024. }
  22025. if (intersectInfo) {
  22026. // Get picked point
  22027. var world = this.getWorldMatrix();
  22028. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  22029. var direction = ray.direction.scaleToRef(intersectInfo.distance, BABYLON.Tmp.Vector3[0]);
  22030. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  22031. var pickedPoint = worldDirection.addInPlace(worldOrigin);
  22032. // Return result
  22033. pickingInfo.hit = true;
  22034. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22035. pickingInfo.pickedPoint = pickedPoint;
  22036. pickingInfo.pickedMesh = this;
  22037. pickingInfo.bu = intersectInfo.bu || 0;
  22038. pickingInfo.bv = intersectInfo.bv || 0;
  22039. pickingInfo.faceId = intersectInfo.faceId;
  22040. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22041. return pickingInfo;
  22042. }
  22043. return pickingInfo;
  22044. };
  22045. /**
  22046. * Clones the current mesh
  22047. * @param name defines the mesh name
  22048. * @param newParent defines the new mesh parent
  22049. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22050. * @returns the new mesh
  22051. */
  22052. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22053. return null;
  22054. };
  22055. /**
  22056. * Disposes all the submeshes of the current meshnp
  22057. * @returns the current mesh
  22058. */
  22059. AbstractMesh.prototype.releaseSubMeshes = function () {
  22060. if (this.subMeshes) {
  22061. while (this.subMeshes.length) {
  22062. this.subMeshes[0].dispose();
  22063. }
  22064. }
  22065. else {
  22066. this.subMeshes = new Array();
  22067. }
  22068. return this;
  22069. };
  22070. /**
  22071. * Releases resources associated with this abstract mesh.
  22072. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22073. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22074. */
  22075. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22076. var _this = this;
  22077. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22078. var index;
  22079. // Smart Array Retainers.
  22080. this.getScene().freeActiveMeshes();
  22081. this.getScene().freeRenderingGroups();
  22082. // Action manager
  22083. if (this.actionManager !== undefined && this.actionManager !== null) {
  22084. this.actionManager.dispose();
  22085. this.actionManager = null;
  22086. }
  22087. // Skeleton
  22088. this._skeleton = null;
  22089. // Intersections in progress
  22090. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22091. var other = this._intersectionsInProgress[index];
  22092. var pos = other._intersectionsInProgress.indexOf(this);
  22093. other._intersectionsInProgress.splice(pos, 1);
  22094. }
  22095. this._intersectionsInProgress = [];
  22096. // Lights
  22097. var lights = this.getScene().lights;
  22098. lights.forEach(function (light) {
  22099. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22100. if (meshIndex !== -1) {
  22101. light.includedOnlyMeshes.splice(meshIndex, 1);
  22102. }
  22103. meshIndex = light.excludedMeshes.indexOf(_this);
  22104. if (meshIndex !== -1) {
  22105. light.excludedMeshes.splice(meshIndex, 1);
  22106. }
  22107. // Shadow generators
  22108. var generator = light.getShadowGenerator();
  22109. if (generator) {
  22110. var shadowMap = generator.getShadowMap();
  22111. if (shadowMap && shadowMap.renderList) {
  22112. meshIndex = shadowMap.renderList.indexOf(_this);
  22113. if (meshIndex !== -1) {
  22114. shadowMap.renderList.splice(meshIndex, 1);
  22115. }
  22116. }
  22117. }
  22118. });
  22119. // SubMeshes
  22120. if (this.getClassName() !== "InstancedMesh") {
  22121. this.releaseSubMeshes();
  22122. }
  22123. // Query
  22124. var engine = this.getScene().getEngine();
  22125. if (this._occlusionQuery) {
  22126. this.isOcclusionQueryInProgress = false;
  22127. engine.deleteQuery(this._occlusionQuery);
  22128. this._occlusionQuery = null;
  22129. }
  22130. // Engine
  22131. engine.wipeCaches();
  22132. // Remove from scene
  22133. this.getScene().removeMesh(this);
  22134. if (disposeMaterialAndTextures) {
  22135. if (this.material) {
  22136. this.material.dispose(false, true);
  22137. }
  22138. }
  22139. if (!doNotRecurse) {
  22140. // Particles
  22141. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22142. if (this.getScene().particleSystems[index].emitter === this) {
  22143. this.getScene().particleSystems[index].dispose();
  22144. index--;
  22145. }
  22146. }
  22147. }
  22148. // facet data
  22149. if (this._facetData.facetDataEnabled) {
  22150. this.disableFacetData();
  22151. }
  22152. this.onAfterWorldMatrixUpdateObservable.clear();
  22153. this.onCollideObservable.clear();
  22154. this.onCollisionPositionChangeObservable.clear();
  22155. this.onRebuildObservable.clear();
  22156. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22157. };
  22158. /**
  22159. * Adds the passed mesh as a child to the current mesh
  22160. * @param mesh defines the child mesh
  22161. * @returns the current mesh
  22162. */
  22163. AbstractMesh.prototype.addChild = function (mesh) {
  22164. mesh.setParent(this);
  22165. return this;
  22166. };
  22167. /**
  22168. * Removes the passed mesh from the current mesh children list
  22169. * @param mesh defines the child mesh
  22170. * @returns the current mesh
  22171. */
  22172. AbstractMesh.prototype.removeChild = function (mesh) {
  22173. mesh.setParent(null);
  22174. return this;
  22175. };
  22176. // Facet data
  22177. /** @hidden */
  22178. AbstractMesh.prototype._initFacetData = function () {
  22179. var data = this._facetData;
  22180. if (!data.facetNormals) {
  22181. data.facetNormals = new Array();
  22182. }
  22183. if (!data.facetPositions) {
  22184. data.facetPositions = new Array();
  22185. }
  22186. if (!data.facetPartitioning) {
  22187. data.facetPartitioning = new Array();
  22188. }
  22189. data.facetNb = (this.getIndices().length / 3) | 0;
  22190. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22191. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22192. for (var f = 0; f < data.facetNb; f++) {
  22193. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22194. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22195. }
  22196. data.facetDataEnabled = true;
  22197. return this;
  22198. };
  22199. /**
  22200. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22201. * This method can be called within the render loop.
  22202. * 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
  22203. * @returns the current mesh
  22204. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22205. */
  22206. AbstractMesh.prototype.updateFacetData = function () {
  22207. var data = this._facetData;
  22208. if (!data.facetDataEnabled) {
  22209. this._initFacetData();
  22210. }
  22211. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22212. var indices = this.getIndices();
  22213. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22214. var bInfo = this.getBoundingInfo();
  22215. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22216. // init arrays, matrix and sort function on first call
  22217. data.facetDepthSortEnabled = true;
  22218. if (indices instanceof Uint16Array) {
  22219. data.depthSortedIndices = new Uint16Array(indices);
  22220. }
  22221. else if (indices instanceof Uint32Array) {
  22222. data.depthSortedIndices = new Uint32Array(indices);
  22223. }
  22224. else {
  22225. var needs32bits = false;
  22226. for (var i = 0; i < indices.length; i++) {
  22227. if (indices[i] > 65535) {
  22228. needs32bits = true;
  22229. break;
  22230. }
  22231. }
  22232. if (needs32bits) {
  22233. data.depthSortedIndices = new Uint32Array(indices);
  22234. }
  22235. else {
  22236. data.depthSortedIndices = new Uint16Array(indices);
  22237. }
  22238. }
  22239. data.facetDepthSortFunction = function (f1, f2) {
  22240. return (f2.sqDistance - f1.sqDistance);
  22241. };
  22242. if (!data.facetDepthSortFrom) {
  22243. var camera = this.getScene().activeCamera;
  22244. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22245. }
  22246. data.depthSortedFacets = [];
  22247. for (var f = 0; f < data.facetNb; f++) {
  22248. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22249. data.depthSortedFacets.push(depthSortedFacet);
  22250. }
  22251. data.invertedMatrix = BABYLON.Matrix.Identity();
  22252. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22253. }
  22254. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22255. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22256. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22257. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22258. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22259. data.subDiv.max = data.partitioningSubdivisions;
  22260. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22261. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22262. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22263. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22264. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22265. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22266. // set the parameters for ComputeNormals()
  22267. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22268. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22269. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22270. data.facetParameters.bInfo = bInfo;
  22271. data.facetParameters.bbSize = data.bbSize;
  22272. data.facetParameters.subDiv = data.subDiv;
  22273. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22274. data.facetParameters.depthSort = data.facetDepthSort;
  22275. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22276. this.computeWorldMatrix(true);
  22277. this._worldMatrix.invertToRef(data.invertedMatrix);
  22278. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22279. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22280. }
  22281. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22282. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22283. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22284. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22285. var l = (data.depthSortedIndices.length / 3) | 0;
  22286. for (var f = 0; f < l; f++) {
  22287. var sind = data.depthSortedFacets[f].ind;
  22288. data.depthSortedIndices[f * 3] = indices[sind];
  22289. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22290. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22291. }
  22292. this.updateIndices(data.depthSortedIndices);
  22293. }
  22294. return this;
  22295. };
  22296. /**
  22297. * Returns the facetLocalNormals array.
  22298. * The normals are expressed in the mesh local spac
  22299. * @returns an array of Vector3
  22300. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22301. */
  22302. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22303. if (!this._facetData.facetNormals) {
  22304. this.updateFacetData();
  22305. }
  22306. return this._facetData.facetNormals;
  22307. };
  22308. /**
  22309. * Returns the facetLocalPositions array.
  22310. * The facet positions are expressed in the mesh local space
  22311. * @returns an array of Vector3
  22312. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22313. */
  22314. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22315. if (!this._facetData.facetPositions) {
  22316. this.updateFacetData();
  22317. }
  22318. return this._facetData.facetPositions;
  22319. };
  22320. /**
  22321. * Returns the facetLocalPartioning array
  22322. * @returns an array of array of numbers
  22323. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22324. */
  22325. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22326. if (!this._facetData.facetPartitioning) {
  22327. this.updateFacetData();
  22328. }
  22329. return this._facetData.facetPartitioning;
  22330. };
  22331. /**
  22332. * Returns the i-th facet position in the world system.
  22333. * This method allocates a new Vector3 per call
  22334. * @param i defines the facet index
  22335. * @returns a new Vector3
  22336. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22337. */
  22338. AbstractMesh.prototype.getFacetPosition = function (i) {
  22339. var pos = BABYLON.Vector3.Zero();
  22340. this.getFacetPositionToRef(i, pos);
  22341. return pos;
  22342. };
  22343. /**
  22344. * Sets the reference Vector3 with the i-th facet position in the world system
  22345. * @param i defines the facet index
  22346. * @param ref defines the target vector
  22347. * @returns the current mesh
  22348. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22349. */
  22350. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22351. var localPos = (this.getFacetLocalPositions())[i];
  22352. var world = this.getWorldMatrix();
  22353. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22354. return this;
  22355. };
  22356. /**
  22357. * Returns the i-th facet normal in the world system.
  22358. * This method allocates a new Vector3 per call
  22359. * @param i defines the facet index
  22360. * @returns a new Vector3
  22361. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22362. */
  22363. AbstractMesh.prototype.getFacetNormal = function (i) {
  22364. var norm = BABYLON.Vector3.Zero();
  22365. this.getFacetNormalToRef(i, norm);
  22366. return norm;
  22367. };
  22368. /**
  22369. * Sets the reference Vector3 with the i-th facet normal in the world system
  22370. * @param i defines the facet index
  22371. * @param ref defines the target vector
  22372. * @returns the current mesh
  22373. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22374. */
  22375. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22376. var localNorm = (this.getFacetLocalNormals())[i];
  22377. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22378. return this;
  22379. };
  22380. /**
  22381. * 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)
  22382. * @param x defines x coordinate
  22383. * @param y defines y coordinate
  22384. * @param z defines z coordinate
  22385. * @returns the array of facet indexes
  22386. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22387. */
  22388. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22389. var bInfo = this.getBoundingInfo();
  22390. var data = this._facetData;
  22391. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22392. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22393. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22394. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22395. return null;
  22396. }
  22397. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22398. };
  22399. /**
  22400. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22401. * @param projected sets as the (x,y,z) world projection on the facet
  22402. * @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
  22403. * @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
  22404. * @param x defines x coordinate
  22405. * @param y defines y coordinate
  22406. * @param z defines z coordinate
  22407. * @returns the face index if found (or null instead)
  22408. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22409. */
  22410. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22411. if (checkFace === void 0) { checkFace = false; }
  22412. if (facing === void 0) { facing = true; }
  22413. var world = this.getWorldMatrix();
  22414. var invMat = BABYLON.Tmp.Matrix[5];
  22415. world.invertToRef(invMat);
  22416. var invVect = BABYLON.Tmp.Vector3[8];
  22417. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22418. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22419. if (projected) {
  22420. // tranform the local computed projected vector to world coordinates
  22421. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22422. }
  22423. return closest;
  22424. };
  22425. /**
  22426. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22427. * @param projected sets as the (x,y,z) local projection on the facet
  22428. * @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
  22429. * @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
  22430. * @param x defines x coordinate
  22431. * @param y defines y coordinate
  22432. * @param z defines z coordinate
  22433. * @returns the face index if found (or null instead)
  22434. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22435. */
  22436. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22437. if (checkFace === void 0) { checkFace = false; }
  22438. if (facing === void 0) { facing = true; }
  22439. var closest = null;
  22440. var tmpx = 0.0;
  22441. var tmpy = 0.0;
  22442. var tmpz = 0.0;
  22443. var d = 0.0; // tmp dot facet normal * facet position
  22444. var t0 = 0.0;
  22445. var projx = 0.0;
  22446. var projy = 0.0;
  22447. var projz = 0.0;
  22448. // Get all the facets in the same partitioning block than (x, y, z)
  22449. var facetPositions = this.getFacetLocalPositions();
  22450. var facetNormals = this.getFacetLocalNormals();
  22451. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22452. if (!facetsInBlock) {
  22453. return null;
  22454. }
  22455. // Get the closest facet to (x, y, z)
  22456. var shortest = Number.MAX_VALUE; // init distance vars
  22457. var tmpDistance = shortest;
  22458. var fib; // current facet in the block
  22459. var norm; // current facet normal
  22460. var p0; // current facet barycenter position
  22461. // loop on all the facets in the current partitioning block
  22462. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22463. fib = facetsInBlock[idx];
  22464. norm = facetNormals[fib];
  22465. p0 = facetPositions[fib];
  22466. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22467. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22468. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22469. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22470. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22471. projx = x + norm.x * t0;
  22472. projy = y + norm.y * t0;
  22473. projz = z + norm.z * t0;
  22474. tmpx = projx - x;
  22475. tmpy = projy - y;
  22476. tmpz = projz - z;
  22477. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22478. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22479. shortest = tmpDistance;
  22480. closest = fib;
  22481. if (projected) {
  22482. projected.x = projx;
  22483. projected.y = projy;
  22484. projected.z = projz;
  22485. }
  22486. }
  22487. }
  22488. }
  22489. return closest;
  22490. };
  22491. /**
  22492. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22493. * @returns the parameters
  22494. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22495. */
  22496. AbstractMesh.prototype.getFacetDataParameters = function () {
  22497. return this._facetData.facetParameters;
  22498. };
  22499. /**
  22500. * Disables the feature FacetData and frees the related memory
  22501. * @returns the current mesh
  22502. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22503. */
  22504. AbstractMesh.prototype.disableFacetData = function () {
  22505. if (this._facetData.facetDataEnabled) {
  22506. this._facetData.facetDataEnabled = false;
  22507. this._facetData.facetPositions = new Array();
  22508. this._facetData.facetNormals = new Array();
  22509. this._facetData.facetPartitioning = new Array();
  22510. this._facetData.facetParameters = null;
  22511. this._facetData.depthSortedIndices = new Uint32Array(0);
  22512. }
  22513. return this;
  22514. };
  22515. /**
  22516. * Updates the AbstractMesh indices array
  22517. * @param indices defines the data source
  22518. * @returns the current mesh
  22519. */
  22520. AbstractMesh.prototype.updateIndices = function (indices) {
  22521. return this;
  22522. };
  22523. /**
  22524. * Creates new normals data for the mesh
  22525. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22526. * @returns the current mesh
  22527. */
  22528. AbstractMesh.prototype.createNormals = function (updatable) {
  22529. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22530. var indices = this.getIndices();
  22531. var normals;
  22532. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22533. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22534. }
  22535. else {
  22536. normals = [];
  22537. }
  22538. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22539. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22540. return this;
  22541. };
  22542. /**
  22543. * Align the mesh with a normal
  22544. * @param normal defines the normal to use
  22545. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22546. * @returns the current mesh
  22547. */
  22548. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22549. if (!upDirection) {
  22550. upDirection = BABYLON.Axis.Y;
  22551. }
  22552. var axisX = BABYLON.Tmp.Vector3[0];
  22553. var axisZ = BABYLON.Tmp.Vector3[1];
  22554. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22555. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22556. if (this.rotationQuaternion) {
  22557. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22558. }
  22559. else {
  22560. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22561. }
  22562. return this;
  22563. };
  22564. /** @hidden */
  22565. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22566. return false;
  22567. };
  22568. /** No occlusion */
  22569. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22570. /** Occlusion set to optimisitic */
  22571. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22572. /** Occlusion set to strict */
  22573. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22574. /** Use an accurante occlusion algorithm */
  22575. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22576. /** Use a conservative occlusion algorithm */
  22577. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22578. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22579. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22580. /** Culling strategy with bounding sphere only and then frustum culling */
  22581. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22582. return AbstractMesh;
  22583. }(BABYLON.TransformNode));
  22584. BABYLON.AbstractMesh = AbstractMesh;
  22585. })(BABYLON || (BABYLON = {}));
  22586. //# sourceMappingURL=babylon.abstractMesh.js.map
  22587. var BABYLON;
  22588. (function (BABYLON) {
  22589. /**
  22590. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22591. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22592. * 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.
  22593. */
  22594. var Light = /** @class */ (function (_super) {
  22595. __extends(Light, _super);
  22596. /**
  22597. * Creates a Light object in the scene.
  22598. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22599. * @param name The firendly name of the light
  22600. * @param scene The scene the light belongs too
  22601. */
  22602. function Light(name, scene) {
  22603. var _this = _super.call(this, name, scene) || this;
  22604. /**
  22605. * Diffuse gives the basic color to an object.
  22606. */
  22607. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22608. /**
  22609. * Specular produces a highlight color on an object.
  22610. * Note: This is note affecting PBR materials.
  22611. */
  22612. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22613. /**
  22614. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22615. * falling off base on range or angle.
  22616. * This can be set to any values in Light.FALLOFF_x.
  22617. *
  22618. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22619. * other types of materials.
  22620. */
  22621. _this.falloffType = Light.FALLOFF_DEFAULT;
  22622. /**
  22623. * Strength of the light.
  22624. * Note: By default it is define in the framework own unit.
  22625. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22626. */
  22627. _this.intensity = 1.0;
  22628. _this._range = Number.MAX_VALUE;
  22629. _this._inverseSquaredRange = 0;
  22630. /**
  22631. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22632. * of light.
  22633. */
  22634. _this._photometricScale = 1.0;
  22635. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22636. _this._radius = 0.00001;
  22637. /**
  22638. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22639. * exceeding the number allowed of the materials.
  22640. */
  22641. _this.renderPriority = 0;
  22642. _this._shadowEnabled = true;
  22643. _this._excludeWithLayerMask = 0;
  22644. _this._includeOnlyWithLayerMask = 0;
  22645. _this._lightmapMode = 0;
  22646. /**
  22647. * @hidden Internal use only.
  22648. */
  22649. _this._excludedMeshesIds = new Array();
  22650. /**
  22651. * @hidden Internal use only.
  22652. */
  22653. _this._includedOnlyMeshesIds = new Array();
  22654. _this.getScene().addLight(_this);
  22655. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22656. _this._buildUniformLayout();
  22657. _this.includedOnlyMeshes = new Array();
  22658. _this.excludedMeshes = new Array();
  22659. _this._resyncMeshes();
  22660. return _this;
  22661. }
  22662. Object.defineProperty(Light.prototype, "range", {
  22663. /**
  22664. * Defines how far from the source the light is impacting in scene units.
  22665. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22666. */
  22667. get: function () {
  22668. return this._range;
  22669. },
  22670. /**
  22671. * Defines how far from the source the light is impacting in scene units.
  22672. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22673. */
  22674. set: function (value) {
  22675. this._range = value;
  22676. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22677. },
  22678. enumerable: true,
  22679. configurable: true
  22680. });
  22681. Object.defineProperty(Light.prototype, "intensityMode", {
  22682. /**
  22683. * Gets the photometric scale used to interpret the intensity.
  22684. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22685. */
  22686. get: function () {
  22687. return this._intensityMode;
  22688. },
  22689. /**
  22690. * Sets the photometric scale used to interpret the intensity.
  22691. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22692. */
  22693. set: function (value) {
  22694. this._intensityMode = value;
  22695. this._computePhotometricScale();
  22696. },
  22697. enumerable: true,
  22698. configurable: true
  22699. });
  22700. Object.defineProperty(Light.prototype, "radius", {
  22701. /**
  22702. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22703. */
  22704. get: function () {
  22705. return this._radius;
  22706. },
  22707. /**
  22708. * sets the light radius used by PBR Materials to simulate soft area lights.
  22709. */
  22710. set: function (value) {
  22711. this._radius = value;
  22712. this._computePhotometricScale();
  22713. },
  22714. enumerable: true,
  22715. configurable: true
  22716. });
  22717. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22718. /**
  22719. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22720. * the current shadow generator.
  22721. */
  22722. get: function () {
  22723. return this._shadowEnabled;
  22724. },
  22725. /**
  22726. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22727. * the current shadow generator.
  22728. */
  22729. set: function (value) {
  22730. if (this._shadowEnabled === value) {
  22731. return;
  22732. }
  22733. this._shadowEnabled = value;
  22734. this._markMeshesAsLightDirty();
  22735. },
  22736. enumerable: true,
  22737. configurable: true
  22738. });
  22739. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22740. /**
  22741. * Gets the only meshes impacted by this light.
  22742. */
  22743. get: function () {
  22744. return this._includedOnlyMeshes;
  22745. },
  22746. /**
  22747. * Sets the only meshes impacted by this light.
  22748. */
  22749. set: function (value) {
  22750. this._includedOnlyMeshes = value;
  22751. this._hookArrayForIncludedOnly(value);
  22752. },
  22753. enumerable: true,
  22754. configurable: true
  22755. });
  22756. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22757. /**
  22758. * Gets the meshes not impacted by this light.
  22759. */
  22760. get: function () {
  22761. return this._excludedMeshes;
  22762. },
  22763. /**
  22764. * Sets the meshes not impacted by this light.
  22765. */
  22766. set: function (value) {
  22767. this._excludedMeshes = value;
  22768. this._hookArrayForExcluded(value);
  22769. },
  22770. enumerable: true,
  22771. configurable: true
  22772. });
  22773. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22774. /**
  22775. * Gets the layer id use to find what meshes are not impacted by the light.
  22776. * Inactive if 0
  22777. */
  22778. get: function () {
  22779. return this._excludeWithLayerMask;
  22780. },
  22781. /**
  22782. * Sets the layer id use to find what meshes are not impacted by the light.
  22783. * Inactive if 0
  22784. */
  22785. set: function (value) {
  22786. this._excludeWithLayerMask = value;
  22787. this._resyncMeshes();
  22788. },
  22789. enumerable: true,
  22790. configurable: true
  22791. });
  22792. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22793. /**
  22794. * Gets the layer id use to find what meshes are impacted by the light.
  22795. * Inactive if 0
  22796. */
  22797. get: function () {
  22798. return this._includeOnlyWithLayerMask;
  22799. },
  22800. /**
  22801. * Sets the layer id use to find what meshes are impacted by the light.
  22802. * Inactive if 0
  22803. */
  22804. set: function (value) {
  22805. this._includeOnlyWithLayerMask = value;
  22806. this._resyncMeshes();
  22807. },
  22808. enumerable: true,
  22809. configurable: true
  22810. });
  22811. Object.defineProperty(Light.prototype, "lightmapMode", {
  22812. /**
  22813. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22814. */
  22815. get: function () {
  22816. return this._lightmapMode;
  22817. },
  22818. /**
  22819. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22820. */
  22821. set: function (value) {
  22822. if (this._lightmapMode === value) {
  22823. return;
  22824. }
  22825. this._lightmapMode = value;
  22826. this._markMeshesAsLightDirty();
  22827. },
  22828. enumerable: true,
  22829. configurable: true
  22830. });
  22831. /**
  22832. * Returns the string "Light".
  22833. * @returns the class name
  22834. */
  22835. Light.prototype.getClassName = function () {
  22836. return "Light";
  22837. };
  22838. /**
  22839. * Converts the light information to a readable string for debug purpose.
  22840. * @param fullDetails Supports for multiple levels of logging within scene loading
  22841. * @returns the human readable light info
  22842. */
  22843. Light.prototype.toString = function (fullDetails) {
  22844. var ret = "Name: " + this.name;
  22845. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22846. if (this.animations) {
  22847. for (var i = 0; i < this.animations.length; i++) {
  22848. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22849. }
  22850. }
  22851. if (fullDetails) {
  22852. }
  22853. return ret;
  22854. };
  22855. /** @hidden */
  22856. Light.prototype._syncParentEnabledState = function () {
  22857. _super.prototype._syncParentEnabledState.call(this);
  22858. this._resyncMeshes();
  22859. };
  22860. /**
  22861. * Set the enabled state of this node.
  22862. * @param value - the new enabled state
  22863. */
  22864. Light.prototype.setEnabled = function (value) {
  22865. _super.prototype.setEnabled.call(this, value);
  22866. this._resyncMeshes();
  22867. };
  22868. /**
  22869. * Returns the Light associated shadow generator if any.
  22870. * @return the associated shadow generator.
  22871. */
  22872. Light.prototype.getShadowGenerator = function () {
  22873. return this._shadowGenerator;
  22874. };
  22875. /**
  22876. * Returns a Vector3, the absolute light position in the World.
  22877. * @returns the world space position of the light
  22878. */
  22879. Light.prototype.getAbsolutePosition = function () {
  22880. return BABYLON.Vector3.Zero();
  22881. };
  22882. /**
  22883. * Specifies if the light will affect the passed mesh.
  22884. * @param mesh The mesh to test against the light
  22885. * @return true the mesh is affected otherwise, false.
  22886. */
  22887. Light.prototype.canAffectMesh = function (mesh) {
  22888. if (!mesh) {
  22889. return true;
  22890. }
  22891. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22892. return false;
  22893. }
  22894. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22895. return false;
  22896. }
  22897. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22898. return false;
  22899. }
  22900. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22901. return false;
  22902. }
  22903. return true;
  22904. };
  22905. /**
  22906. * Sort function to order lights for rendering.
  22907. * @param a First Light object to compare to second.
  22908. * @param b Second Light object to compare first.
  22909. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22910. */
  22911. Light.CompareLightsPriority = function (a, b) {
  22912. //shadow-casting lights have priority over non-shadow-casting lights
  22913. //the renderPrioirty is a secondary sort criterion
  22914. if (a.shadowEnabled !== b.shadowEnabled) {
  22915. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22916. }
  22917. return b.renderPriority - a.renderPriority;
  22918. };
  22919. /**
  22920. * Releases resources associated with this node.
  22921. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22922. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22923. */
  22924. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22925. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22926. if (this._shadowGenerator) {
  22927. this._shadowGenerator.dispose();
  22928. this._shadowGenerator = null;
  22929. }
  22930. // Animations
  22931. this.getScene().stopAnimation(this);
  22932. // Remove from meshes
  22933. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22934. var mesh = _a[_i];
  22935. mesh._removeLightSource(this);
  22936. }
  22937. this._uniformBuffer.dispose();
  22938. // Remove from scene
  22939. this.getScene().removeLight(this);
  22940. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22941. };
  22942. /**
  22943. * Returns the light type ID (integer).
  22944. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22945. */
  22946. Light.prototype.getTypeID = function () {
  22947. return 0;
  22948. };
  22949. /**
  22950. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22951. * @returns the scaled intensity in intensity mode unit
  22952. */
  22953. Light.prototype.getScaledIntensity = function () {
  22954. return this._photometricScale * this.intensity;
  22955. };
  22956. /**
  22957. * Returns a new Light object, named "name", from the current one.
  22958. * @param name The name of the cloned light
  22959. * @returns the new created light
  22960. */
  22961. Light.prototype.clone = function (name) {
  22962. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22963. if (!constructor) {
  22964. return null;
  22965. }
  22966. return BABYLON.SerializationHelper.Clone(constructor, this);
  22967. };
  22968. /**
  22969. * Serializes the current light into a Serialization object.
  22970. * @returns the serialized object.
  22971. */
  22972. Light.prototype.serialize = function () {
  22973. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22974. // Type
  22975. serializationObject.type = this.getTypeID();
  22976. // Parent
  22977. if (this.parent) {
  22978. serializationObject.parentId = this.parent.id;
  22979. }
  22980. // Inclusion / exclusions
  22981. if (this.excludedMeshes.length > 0) {
  22982. serializationObject.excludedMeshesIds = [];
  22983. this.excludedMeshes.forEach(function (mesh) {
  22984. serializationObject.excludedMeshesIds.push(mesh.id);
  22985. });
  22986. }
  22987. if (this.includedOnlyMeshes.length > 0) {
  22988. serializationObject.includedOnlyMeshesIds = [];
  22989. this.includedOnlyMeshes.forEach(function (mesh) {
  22990. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22991. });
  22992. }
  22993. // Animations
  22994. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22995. serializationObject.ranges = this.serializeAnimationRanges();
  22996. return serializationObject;
  22997. };
  22998. /**
  22999. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  23000. * This new light is named "name" and added to the passed scene.
  23001. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  23002. * @param name The friendly name of the light
  23003. * @param scene The scene the new light will belong to
  23004. * @returns the constructor function
  23005. */
  23006. Light.GetConstructorFromName = function (type, name, scene) {
  23007. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  23008. if (constructorFunc) {
  23009. return constructorFunc;
  23010. }
  23011. // Default to no light for none present once.
  23012. return null;
  23013. };
  23014. /**
  23015. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  23016. * @param parsedLight The JSON representation of the light
  23017. * @param scene The scene to create the parsed light in
  23018. * @returns the created light after parsing
  23019. */
  23020. Light.Parse = function (parsedLight, scene) {
  23021. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  23022. if (!constructor) {
  23023. return null;
  23024. }
  23025. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  23026. // Inclusion / exclusions
  23027. if (parsedLight.excludedMeshesIds) {
  23028. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  23029. }
  23030. if (parsedLight.includedOnlyMeshesIds) {
  23031. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  23032. }
  23033. // Parent
  23034. if (parsedLight.parentId) {
  23035. light._waitingParentId = parsedLight.parentId;
  23036. }
  23037. // Animations
  23038. if (parsedLight.animations) {
  23039. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23040. var parsedAnimation = parsedLight.animations[animationIndex];
  23041. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23042. }
  23043. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23044. }
  23045. if (parsedLight.autoAnimate) {
  23046. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23047. }
  23048. return light;
  23049. };
  23050. Light.prototype._hookArrayForExcluded = function (array) {
  23051. var _this = this;
  23052. var oldPush = array.push;
  23053. array.push = function () {
  23054. var items = [];
  23055. for (var _i = 0; _i < arguments.length; _i++) {
  23056. items[_i] = arguments[_i];
  23057. }
  23058. var result = oldPush.apply(array, items);
  23059. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23060. var item = items_1[_a];
  23061. item._resyncLighSource(_this);
  23062. }
  23063. return result;
  23064. };
  23065. var oldSplice = array.splice;
  23066. array.splice = function (index, deleteCount) {
  23067. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23068. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23069. var item = deleted_1[_i];
  23070. item._resyncLighSource(_this);
  23071. }
  23072. return deleted;
  23073. };
  23074. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23075. var item = array_1[_i];
  23076. item._resyncLighSource(this);
  23077. }
  23078. };
  23079. Light.prototype._hookArrayForIncludedOnly = function (array) {
  23080. var _this = this;
  23081. var oldPush = array.push;
  23082. array.push = function () {
  23083. var items = [];
  23084. for (var _i = 0; _i < arguments.length; _i++) {
  23085. items[_i] = arguments[_i];
  23086. }
  23087. var result = oldPush.apply(array, items);
  23088. _this._resyncMeshes();
  23089. return result;
  23090. };
  23091. var oldSplice = array.splice;
  23092. array.splice = function (index, deleteCount) {
  23093. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23094. _this._resyncMeshes();
  23095. return deleted;
  23096. };
  23097. this._resyncMeshes();
  23098. };
  23099. Light.prototype._resyncMeshes = function () {
  23100. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23101. var mesh = _a[_i];
  23102. mesh._resyncLighSource(this);
  23103. }
  23104. };
  23105. /**
  23106. * Forces the meshes to update their light related information in their rendering used effects
  23107. * @hidden Internal Use Only
  23108. */
  23109. Light.prototype._markMeshesAsLightDirty = function () {
  23110. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23111. var mesh = _a[_i];
  23112. if (mesh._lightSources.indexOf(this) !== -1) {
  23113. mesh._markSubMeshesAsLightDirty();
  23114. }
  23115. }
  23116. };
  23117. /**
  23118. * Recomputes the cached photometric scale if needed.
  23119. */
  23120. Light.prototype._computePhotometricScale = function () {
  23121. this._photometricScale = this._getPhotometricScale();
  23122. this.getScene().resetCachedMaterial();
  23123. };
  23124. /**
  23125. * Returns the Photometric Scale according to the light type and intensity mode.
  23126. */
  23127. Light.prototype._getPhotometricScale = function () {
  23128. var photometricScale = 0.0;
  23129. var lightTypeID = this.getTypeID();
  23130. //get photometric mode
  23131. var photometricMode = this.intensityMode;
  23132. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23133. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23134. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23135. }
  23136. else {
  23137. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23138. }
  23139. }
  23140. //compute photometric scale
  23141. switch (lightTypeID) {
  23142. case Light.LIGHTTYPEID_POINTLIGHT:
  23143. case Light.LIGHTTYPEID_SPOTLIGHT:
  23144. switch (photometricMode) {
  23145. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23146. photometricScale = 1.0 / (4.0 * Math.PI);
  23147. break;
  23148. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23149. photometricScale = 1.0;
  23150. break;
  23151. case Light.INTENSITYMODE_LUMINANCE:
  23152. photometricScale = this.radius * this.radius;
  23153. break;
  23154. }
  23155. break;
  23156. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23157. switch (photometricMode) {
  23158. case Light.INTENSITYMODE_ILLUMINANCE:
  23159. photometricScale = 1.0;
  23160. break;
  23161. case Light.INTENSITYMODE_LUMINANCE:
  23162. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23163. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23164. var apexAngleRadians = this.radius;
  23165. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23166. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23167. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23168. photometricScale = solidAngle;
  23169. break;
  23170. }
  23171. break;
  23172. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23173. // No fall off in hemisperic light.
  23174. photometricScale = 1.0;
  23175. break;
  23176. }
  23177. return photometricScale;
  23178. };
  23179. /**
  23180. * Reorder the light in the scene according to their defined priority.
  23181. * @hidden Internal Use Only
  23182. */
  23183. Light.prototype._reorderLightsInScene = function () {
  23184. var scene = this.getScene();
  23185. if (this._renderPriority != 0) {
  23186. scene.requireLightSorting = true;
  23187. }
  23188. this.getScene().sortLightsByPriority();
  23189. };
  23190. /**
  23191. * Falloff Default: light is falling off following the material specification:
  23192. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23193. */
  23194. Light.FALLOFF_DEFAULT = 0;
  23195. /**
  23196. * Falloff Physical: light is falling off following the inverse squared distance law.
  23197. */
  23198. Light.FALLOFF_PHYSICAL = 1;
  23199. /**
  23200. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23201. * to enhance interoperability with other engines.
  23202. */
  23203. Light.FALLOFF_GLTF = 2;
  23204. /**
  23205. * Falloff Standard: light is falling off like in the standard material
  23206. * to enhance interoperability with other materials.
  23207. */
  23208. Light.FALLOFF_STANDARD = 3;
  23209. //lightmapMode Consts
  23210. /**
  23211. * If every light affecting the material is in this lightmapMode,
  23212. * material.lightmapTexture adds or multiplies
  23213. * (depends on material.useLightmapAsShadowmap)
  23214. * after every other light calculations.
  23215. */
  23216. Light.LIGHTMAP_DEFAULT = 0;
  23217. /**
  23218. * material.lightmapTexture as only diffuse lighting from this light
  23219. * adds only specular lighting from this light
  23220. * adds dynamic shadows
  23221. */
  23222. Light.LIGHTMAP_SPECULAR = 1;
  23223. /**
  23224. * material.lightmapTexture as only lighting
  23225. * no light calculation from this light
  23226. * only adds dynamic shadows from this light
  23227. */
  23228. Light.LIGHTMAP_SHADOWSONLY = 2;
  23229. // Intensity Mode Consts
  23230. /**
  23231. * Each light type uses the default quantity according to its type:
  23232. * point/spot lights use luminous intensity
  23233. * directional lights use illuminance
  23234. */
  23235. Light.INTENSITYMODE_AUTOMATIC = 0;
  23236. /**
  23237. * lumen (lm)
  23238. */
  23239. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23240. /**
  23241. * candela (lm/sr)
  23242. */
  23243. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23244. /**
  23245. * lux (lm/m^2)
  23246. */
  23247. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23248. /**
  23249. * nit (cd/m^2)
  23250. */
  23251. Light.INTENSITYMODE_LUMINANCE = 4;
  23252. // Light types ids const.
  23253. /**
  23254. * Light type const id of the point light.
  23255. */
  23256. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23257. /**
  23258. * Light type const id of the directional light.
  23259. */
  23260. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23261. /**
  23262. * Light type const id of the spot light.
  23263. */
  23264. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23265. /**
  23266. * Light type const id of the hemispheric light.
  23267. */
  23268. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23269. __decorate([
  23270. BABYLON.serializeAsColor3()
  23271. ], Light.prototype, "diffuse", void 0);
  23272. __decorate([
  23273. BABYLON.serializeAsColor3()
  23274. ], Light.prototype, "specular", void 0);
  23275. __decorate([
  23276. BABYLON.serialize()
  23277. ], Light.prototype, "falloffType", void 0);
  23278. __decorate([
  23279. BABYLON.serialize()
  23280. ], Light.prototype, "intensity", void 0);
  23281. __decorate([
  23282. BABYLON.serialize()
  23283. ], Light.prototype, "range", null);
  23284. __decorate([
  23285. BABYLON.serialize()
  23286. ], Light.prototype, "intensityMode", null);
  23287. __decorate([
  23288. BABYLON.serialize()
  23289. ], Light.prototype, "radius", null);
  23290. __decorate([
  23291. BABYLON.serialize()
  23292. ], Light.prototype, "_renderPriority", void 0);
  23293. __decorate([
  23294. BABYLON.expandToProperty("_reorderLightsInScene")
  23295. ], Light.prototype, "renderPriority", void 0);
  23296. __decorate([
  23297. BABYLON.serialize("shadowEnabled")
  23298. ], Light.prototype, "_shadowEnabled", void 0);
  23299. __decorate([
  23300. BABYLON.serialize("excludeWithLayerMask")
  23301. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23302. __decorate([
  23303. BABYLON.serialize("includeOnlyWithLayerMask")
  23304. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23305. __decorate([
  23306. BABYLON.serialize("lightmapMode")
  23307. ], Light.prototype, "_lightmapMode", void 0);
  23308. return Light;
  23309. }(BABYLON.Node));
  23310. BABYLON.Light = Light;
  23311. })(BABYLON || (BABYLON = {}));
  23312. //# sourceMappingURL=babylon.light.js.map
  23313. var BABYLON;
  23314. (function (BABYLON) {
  23315. /**
  23316. * This is the base class of all the camera used in the application.
  23317. * @see http://doc.babylonjs.com/features/cameras
  23318. */
  23319. var Camera = /** @class */ (function (_super) {
  23320. __extends(Camera, _super);
  23321. /**
  23322. * Instantiates a new camera object.
  23323. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23324. * @see http://doc.babylonjs.com/features/cameras
  23325. * @param name Defines the name of the camera in the scene
  23326. * @param position Defines the position of the camera
  23327. * @param scene Defines the scene the camera belongs too
  23328. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23329. */
  23330. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23331. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23332. var _this = _super.call(this, name, scene) || this;
  23333. /**
  23334. * The vector the camera should consider as up.
  23335. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23336. */
  23337. _this.upVector = BABYLON.Vector3.Up();
  23338. /**
  23339. * Define the current limit on the left side for an orthographic camera
  23340. * In scene unit
  23341. */
  23342. _this.orthoLeft = null;
  23343. /**
  23344. * Define the current limit on the right side for an orthographic camera
  23345. * In scene unit
  23346. */
  23347. _this.orthoRight = null;
  23348. /**
  23349. * Define the current limit on the bottom side for an orthographic camera
  23350. * In scene unit
  23351. */
  23352. _this.orthoBottom = null;
  23353. /**
  23354. * Define the current limit on the top side for an orthographic camera
  23355. * In scene unit
  23356. */
  23357. _this.orthoTop = null;
  23358. /**
  23359. * Field Of View is set in Radians. (default is 0.8)
  23360. */
  23361. _this.fov = 0.8;
  23362. /**
  23363. * Define the minimum distance the camera can see from.
  23364. * This is important to note that the depth buffer are not infinite and the closer it starts
  23365. * the more your scene might encounter depth fighting issue.
  23366. */
  23367. _this.minZ = 1;
  23368. /**
  23369. * Define the maximum distance the camera can see to.
  23370. * This is important to note that the depth buffer are not infinite and the further it end
  23371. * the more your scene might encounter depth fighting issue.
  23372. */
  23373. _this.maxZ = 10000.0;
  23374. /**
  23375. * Define the default inertia of the camera.
  23376. * This helps giving a smooth feeling to the camera movement.
  23377. */
  23378. _this.inertia = 0.9;
  23379. /**
  23380. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23381. */
  23382. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23383. /**
  23384. * Define wether the camera is intermediate.
  23385. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23386. */
  23387. _this.isIntermediate = false;
  23388. /**
  23389. * Define the viewport of the camera.
  23390. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23391. */
  23392. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23393. /**
  23394. * Restricts the camera to viewing objects with the same layerMask.
  23395. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23396. */
  23397. _this.layerMask = 0x0FFFFFFF;
  23398. /**
  23399. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23400. */
  23401. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23402. /**
  23403. * Rig mode of the camera.
  23404. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23405. * This is normally controlled byt the camera themselves as internal use.
  23406. */
  23407. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23408. /**
  23409. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  23410. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23411. * else in the scene.
  23412. */
  23413. _this.customRenderTargets = new Array();
  23414. /**
  23415. * When set, the camera will render to this render target instead of the default canvas
  23416. */
  23417. _this.outputRenderTarget = null;
  23418. /**
  23419. * Observable triggered when the camera view matrix has changed.
  23420. */
  23421. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23422. /**
  23423. * Observable triggered when the camera Projection matrix has changed.
  23424. */
  23425. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23426. /**
  23427. * Observable triggered when the inputs have been processed.
  23428. */
  23429. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23430. /**
  23431. * Observable triggered when reset has been called and applied to the camera.
  23432. */
  23433. _this.onRestoreStateObservable = new BABYLON.Observable();
  23434. /** @hidden */
  23435. _this._rigCameras = new Array();
  23436. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23437. /** @hidden */
  23438. _this._skipRendering = false;
  23439. /** @hidden */
  23440. _this._projectionMatrix = new BABYLON.Matrix();
  23441. /** @hidden */
  23442. _this._postProcesses = new Array();
  23443. /** @hidden */
  23444. _this._activeMeshes = new BABYLON.SmartArray(256);
  23445. _this._globalPosition = BABYLON.Vector3.Zero();
  23446. /** hidden */
  23447. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23448. _this._doNotComputeProjectionMatrix = false;
  23449. _this._transformMatrix = BABYLON.Matrix.Zero();
  23450. _this._refreshFrustumPlanes = true;
  23451. _this.getScene().addCamera(_this);
  23452. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23453. _this.getScene().activeCamera = _this;
  23454. }
  23455. _this.position = position;
  23456. return _this;
  23457. }
  23458. /**
  23459. * Store current camera state (fov, position, etc..)
  23460. * @returns the camera
  23461. */
  23462. Camera.prototype.storeState = function () {
  23463. this._stateStored = true;
  23464. this._storedFov = this.fov;
  23465. return this;
  23466. };
  23467. /**
  23468. * Restores the camera state values if it has been stored. You must call storeState() first
  23469. */
  23470. Camera.prototype._restoreStateValues = function () {
  23471. if (!this._stateStored) {
  23472. return false;
  23473. }
  23474. this.fov = this._storedFov;
  23475. return true;
  23476. };
  23477. /**
  23478. * Restored camera state. You must call storeState() first.
  23479. * @returns true if restored and false otherwise
  23480. */
  23481. Camera.prototype.restoreState = function () {
  23482. if (this._restoreStateValues()) {
  23483. this.onRestoreStateObservable.notifyObservers(this);
  23484. return true;
  23485. }
  23486. return false;
  23487. };
  23488. /**
  23489. * Gets the class name of the camera.
  23490. * @returns the class name
  23491. */
  23492. Camera.prototype.getClassName = function () {
  23493. return "Camera";
  23494. };
  23495. /**
  23496. * Gets a string representation of the camera usefull for debug purpose.
  23497. * @param fullDetails Defines that a more verboe level of logging is required
  23498. * @returns the string representation
  23499. */
  23500. Camera.prototype.toString = function (fullDetails) {
  23501. var ret = "Name: " + this.name;
  23502. ret += ", type: " + this.getClassName();
  23503. if (this.animations) {
  23504. for (var i = 0; i < this.animations.length; i++) {
  23505. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23506. }
  23507. }
  23508. if (fullDetails) {
  23509. }
  23510. return ret;
  23511. };
  23512. Object.defineProperty(Camera.prototype, "globalPosition", {
  23513. /**
  23514. * Gets the current world space position of the camera.
  23515. */
  23516. get: function () {
  23517. return this._globalPosition;
  23518. },
  23519. enumerable: true,
  23520. configurable: true
  23521. });
  23522. /**
  23523. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23524. * @returns the active meshe list
  23525. */
  23526. Camera.prototype.getActiveMeshes = function () {
  23527. return this._activeMeshes;
  23528. };
  23529. /**
  23530. * Check wether a mesh is part of the current active mesh list of the camera
  23531. * @param mesh Defines the mesh to check
  23532. * @returns true if active, false otherwise
  23533. */
  23534. Camera.prototype.isActiveMesh = function (mesh) {
  23535. return (this._activeMeshes.indexOf(mesh) !== -1);
  23536. };
  23537. /**
  23538. * Is this camera ready to be used/rendered
  23539. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23540. * @return true if the camera is ready
  23541. */
  23542. Camera.prototype.isReady = function (completeCheck) {
  23543. if (completeCheck === void 0) { completeCheck = false; }
  23544. if (completeCheck) {
  23545. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23546. var pp = _a[_i];
  23547. if (pp && !pp.isReady()) {
  23548. return false;
  23549. }
  23550. }
  23551. }
  23552. return _super.prototype.isReady.call(this, completeCheck);
  23553. };
  23554. /** @hidden */
  23555. Camera.prototype._initCache = function () {
  23556. _super.prototype._initCache.call(this);
  23557. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23558. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23559. this._cache.mode = undefined;
  23560. this._cache.minZ = undefined;
  23561. this._cache.maxZ = undefined;
  23562. this._cache.fov = undefined;
  23563. this._cache.fovMode = undefined;
  23564. this._cache.aspectRatio = undefined;
  23565. this._cache.orthoLeft = undefined;
  23566. this._cache.orthoRight = undefined;
  23567. this._cache.orthoBottom = undefined;
  23568. this._cache.orthoTop = undefined;
  23569. this._cache.renderWidth = undefined;
  23570. this._cache.renderHeight = undefined;
  23571. };
  23572. /** @hidden */
  23573. Camera.prototype._updateCache = function (ignoreParentClass) {
  23574. if (!ignoreParentClass) {
  23575. _super.prototype._updateCache.call(this);
  23576. }
  23577. this._cache.position.copyFrom(this.position);
  23578. this._cache.upVector.copyFrom(this.upVector);
  23579. };
  23580. /** @hidden */
  23581. Camera.prototype._isSynchronized = function () {
  23582. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23583. };
  23584. /** @hidden */
  23585. Camera.prototype._isSynchronizedViewMatrix = function () {
  23586. if (!_super.prototype._isSynchronized.call(this)) {
  23587. return false;
  23588. }
  23589. return this._cache.position.equals(this.position)
  23590. && this._cache.upVector.equals(this.upVector)
  23591. && this.isSynchronizedWithParent();
  23592. };
  23593. /** @hidden */
  23594. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23595. var check = this._cache.mode === this.mode
  23596. && this._cache.minZ === this.minZ
  23597. && this._cache.maxZ === this.maxZ;
  23598. if (!check) {
  23599. return false;
  23600. }
  23601. var engine = this.getEngine();
  23602. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23603. check = this._cache.fov === this.fov
  23604. && this._cache.fovMode === this.fovMode
  23605. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23606. }
  23607. else {
  23608. check = this._cache.orthoLeft === this.orthoLeft
  23609. && this._cache.orthoRight === this.orthoRight
  23610. && this._cache.orthoBottom === this.orthoBottom
  23611. && this._cache.orthoTop === this.orthoTop
  23612. && this._cache.renderWidth === engine.getRenderWidth()
  23613. && this._cache.renderHeight === engine.getRenderHeight();
  23614. }
  23615. return check;
  23616. };
  23617. /**
  23618. * Attach the input controls to a specific dom element to get the input from.
  23619. * @param element Defines the element the controls should be listened from
  23620. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23621. */
  23622. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23623. };
  23624. /**
  23625. * Detach the current controls from the specified dom element.
  23626. * @param element Defines the element to stop listening the inputs from
  23627. */
  23628. Camera.prototype.detachControl = function (element) {
  23629. };
  23630. /**
  23631. * Update the camera state according to the different inputs gathered during the frame.
  23632. */
  23633. Camera.prototype.update = function () {
  23634. this._checkInputs();
  23635. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23636. this._updateRigCameras();
  23637. }
  23638. };
  23639. /** @hidden */
  23640. Camera.prototype._checkInputs = function () {
  23641. this.onAfterCheckInputsObservable.notifyObservers(this);
  23642. };
  23643. Object.defineProperty(Camera.prototype, "rigCameras", {
  23644. /** @hidden */
  23645. get: function () {
  23646. return this._rigCameras;
  23647. },
  23648. enumerable: true,
  23649. configurable: true
  23650. });
  23651. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23652. /**
  23653. * Gets the post process used by the rig cameras
  23654. */
  23655. get: function () {
  23656. return this._rigPostProcess;
  23657. },
  23658. enumerable: true,
  23659. configurable: true
  23660. });
  23661. /**
  23662. * Internal, gets the first post proces.
  23663. * @returns the first post process to be run on this camera.
  23664. */
  23665. Camera.prototype._getFirstPostProcess = function () {
  23666. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23667. if (this._postProcesses[ppIndex] !== null) {
  23668. return this._postProcesses[ppIndex];
  23669. }
  23670. }
  23671. return null;
  23672. };
  23673. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23674. // invalidate framebuffer
  23675. var firstPostProcess = this._getFirstPostProcess();
  23676. if (firstPostProcess) {
  23677. firstPostProcess.markTextureDirty();
  23678. }
  23679. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23680. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23681. var cam = this._rigCameras[i];
  23682. var rigPostProcess = cam._rigPostProcess;
  23683. // for VR rig, there does not have to be a post process
  23684. if (rigPostProcess) {
  23685. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23686. if (isPass) {
  23687. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23688. cam.isIntermediate = this._postProcesses.length === 0;
  23689. }
  23690. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23691. rigPostProcess.markTextureDirty();
  23692. }
  23693. else {
  23694. cam._postProcesses = this._postProcesses.slice(0);
  23695. }
  23696. }
  23697. };
  23698. /**
  23699. * Attach a post process to the camera.
  23700. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23701. * @param postProcess The post process to attach to the camera
  23702. * @param insertAt The position of the post process in case several of them are in use in the scene
  23703. * @returns the position the post process has been inserted at
  23704. */
  23705. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23706. if (insertAt === void 0) { insertAt = null; }
  23707. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23708. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23709. return 0;
  23710. }
  23711. if (insertAt == null || insertAt < 0) {
  23712. this._postProcesses.push(postProcess);
  23713. }
  23714. else if (this._postProcesses[insertAt] === null) {
  23715. this._postProcesses[insertAt] = postProcess;
  23716. }
  23717. else {
  23718. this._postProcesses.splice(insertAt, 0, postProcess);
  23719. }
  23720. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23721. return this._postProcesses.indexOf(postProcess);
  23722. };
  23723. /**
  23724. * Detach a post process to the camera.
  23725. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23726. * @param postProcess The post process to detach from the camera
  23727. */
  23728. Camera.prototype.detachPostProcess = function (postProcess) {
  23729. var idx = this._postProcesses.indexOf(postProcess);
  23730. if (idx !== -1) {
  23731. this._postProcesses[idx] = null;
  23732. }
  23733. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23734. };
  23735. /**
  23736. * Gets the current world matrix of the camera
  23737. */
  23738. Camera.prototype.getWorldMatrix = function () {
  23739. if (this._isSynchronizedViewMatrix()) {
  23740. return this._worldMatrix;
  23741. }
  23742. // Getting the the view matrix will also compute the world matrix.
  23743. this.getViewMatrix();
  23744. return this._worldMatrix;
  23745. };
  23746. /** @hidden */
  23747. Camera.prototype._getViewMatrix = function () {
  23748. return BABYLON.Matrix.Identity();
  23749. };
  23750. /**
  23751. * Gets the current view matrix of the camera.
  23752. * @param force forces the camera to recompute the matrix without looking at the cached state
  23753. * @returns the view matrix
  23754. */
  23755. Camera.prototype.getViewMatrix = function (force) {
  23756. if (!force && this._isSynchronizedViewMatrix()) {
  23757. return this._computedViewMatrix;
  23758. }
  23759. this.updateCache();
  23760. this._computedViewMatrix = this._getViewMatrix();
  23761. this._currentRenderId = this.getScene().getRenderId();
  23762. this._childRenderId = this._currentRenderId;
  23763. this._refreshFrustumPlanes = true;
  23764. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23765. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23766. }
  23767. this.onViewMatrixChangedObservable.notifyObservers(this);
  23768. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23769. return this._computedViewMatrix;
  23770. };
  23771. /**
  23772. * Freeze the projection matrix.
  23773. * It will prevent the cache check of the camera projection compute and can speed up perf
  23774. * if no parameter of the camera are meant to change
  23775. * @param projection Defines manually a projection if necessary
  23776. */
  23777. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23778. this._doNotComputeProjectionMatrix = true;
  23779. if (projection !== undefined) {
  23780. this._projectionMatrix = projection;
  23781. }
  23782. };
  23783. /**
  23784. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23785. */
  23786. Camera.prototype.unfreezeProjectionMatrix = function () {
  23787. this._doNotComputeProjectionMatrix = false;
  23788. };
  23789. /**
  23790. * Gets the current projection matrix of the camera.
  23791. * @param force forces the camera to recompute the matrix without looking at the cached state
  23792. * @returns the projection matrix
  23793. */
  23794. Camera.prototype.getProjectionMatrix = function (force) {
  23795. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23796. return this._projectionMatrix;
  23797. }
  23798. // Cache
  23799. this._cache.mode = this.mode;
  23800. this._cache.minZ = this.minZ;
  23801. this._cache.maxZ = this.maxZ;
  23802. // Matrix
  23803. this._refreshFrustumPlanes = true;
  23804. var engine = this.getEngine();
  23805. var scene = this.getScene();
  23806. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23807. this._cache.fov = this.fov;
  23808. this._cache.fovMode = this.fovMode;
  23809. this._cache.aspectRatio = engine.getAspectRatio(this);
  23810. if (this.minZ <= 0) {
  23811. this.minZ = 0.1;
  23812. }
  23813. if (scene.useRightHandedSystem) {
  23814. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23815. }
  23816. else {
  23817. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23818. }
  23819. }
  23820. else {
  23821. var halfWidth = engine.getRenderWidth() / 2.0;
  23822. var halfHeight = engine.getRenderHeight() / 2.0;
  23823. if (scene.useRightHandedSystem) {
  23824. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23825. }
  23826. else {
  23827. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23828. }
  23829. this._cache.orthoLeft = this.orthoLeft;
  23830. this._cache.orthoRight = this.orthoRight;
  23831. this._cache.orthoBottom = this.orthoBottom;
  23832. this._cache.orthoTop = this.orthoTop;
  23833. this._cache.renderWidth = engine.getRenderWidth();
  23834. this._cache.renderHeight = engine.getRenderHeight();
  23835. }
  23836. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23837. return this._projectionMatrix;
  23838. };
  23839. /**
  23840. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23841. * @returns a Matrix
  23842. */
  23843. Camera.prototype.getTransformationMatrix = function () {
  23844. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23845. return this._transformMatrix;
  23846. };
  23847. Camera.prototype._updateFrustumPlanes = function () {
  23848. if (!this._refreshFrustumPlanes) {
  23849. return;
  23850. }
  23851. this.getTransformationMatrix();
  23852. if (!this._frustumPlanes) {
  23853. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23854. }
  23855. else {
  23856. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23857. }
  23858. this._refreshFrustumPlanes = false;
  23859. };
  23860. /**
  23861. * Checks if a cullable object (mesh...) is in the camera frustum
  23862. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23863. * @param target The object to check
  23864. * @returns true if the object is in frustum otherwise false
  23865. */
  23866. Camera.prototype.isInFrustum = function (target) {
  23867. this._updateFrustumPlanes();
  23868. return target.isInFrustum(this._frustumPlanes);
  23869. };
  23870. /**
  23871. * Checks if a cullable object (mesh...) is in the camera frustum
  23872. * Unlike isInFrustum this cheks the full bounding box
  23873. * @param target The object to check
  23874. * @returns true if the object is in frustum otherwise false
  23875. */
  23876. Camera.prototype.isCompletelyInFrustum = function (target) {
  23877. this._updateFrustumPlanes();
  23878. return target.isCompletelyInFrustum(this._frustumPlanes);
  23879. };
  23880. /**
  23881. * Gets a ray in the forward direction from the camera.
  23882. * @param length Defines the length of the ray to create
  23883. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23884. * @param origin Defines the start point of the ray which defaults to the camera position
  23885. * @returns the forward ray
  23886. */
  23887. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23888. if (length === void 0) { length = 100; }
  23889. if (!transform) {
  23890. transform = this.getWorldMatrix();
  23891. }
  23892. if (!origin) {
  23893. origin = this.position;
  23894. }
  23895. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23896. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23897. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23898. return new BABYLON.Ray(origin, direction, length);
  23899. };
  23900. /**
  23901. * Releases resources associated with this node.
  23902. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23903. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23904. */
  23905. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23906. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23907. // Observables
  23908. this.onViewMatrixChangedObservable.clear();
  23909. this.onProjectionMatrixChangedObservable.clear();
  23910. this.onAfterCheckInputsObservable.clear();
  23911. this.onRestoreStateObservable.clear();
  23912. // Inputs
  23913. if (this.inputs) {
  23914. this.inputs.clear();
  23915. }
  23916. // Animations
  23917. this.getScene().stopAnimation(this);
  23918. // Remove from scene
  23919. this.getScene().removeCamera(this);
  23920. while (this._rigCameras.length > 0) {
  23921. var camera = this._rigCameras.pop();
  23922. if (camera) {
  23923. camera.dispose();
  23924. }
  23925. }
  23926. // Postprocesses
  23927. if (this._rigPostProcess) {
  23928. this._rigPostProcess.dispose(this);
  23929. this._rigPostProcess = null;
  23930. this._postProcesses = [];
  23931. }
  23932. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23933. this._rigPostProcess = null;
  23934. this._postProcesses = [];
  23935. }
  23936. else {
  23937. var i = this._postProcesses.length;
  23938. while (--i >= 0) {
  23939. var postProcess = this._postProcesses[i];
  23940. if (postProcess) {
  23941. postProcess.dispose(this);
  23942. }
  23943. }
  23944. }
  23945. // Render targets
  23946. var i = this.customRenderTargets.length;
  23947. while (--i >= 0) {
  23948. this.customRenderTargets[i].dispose();
  23949. }
  23950. this.customRenderTargets = [];
  23951. // Active Meshes
  23952. this._activeMeshes.dispose();
  23953. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23954. };
  23955. Object.defineProperty(Camera.prototype, "leftCamera", {
  23956. /**
  23957. * Gets the left camera of a rig setup in case of Rigged Camera
  23958. */
  23959. get: function () {
  23960. if (this._rigCameras.length < 1) {
  23961. return null;
  23962. }
  23963. return this._rigCameras[0];
  23964. },
  23965. enumerable: true,
  23966. configurable: true
  23967. });
  23968. Object.defineProperty(Camera.prototype, "rightCamera", {
  23969. /**
  23970. * Gets the right camera of a rig setup in case of Rigged Camera
  23971. */
  23972. get: function () {
  23973. if (this._rigCameras.length < 2) {
  23974. return null;
  23975. }
  23976. return this._rigCameras[1];
  23977. },
  23978. enumerable: true,
  23979. configurable: true
  23980. });
  23981. /**
  23982. * Gets the left camera target of a rig setup in case of Rigged Camera
  23983. * @returns the target position
  23984. */
  23985. Camera.prototype.getLeftTarget = function () {
  23986. if (this._rigCameras.length < 1) {
  23987. return null;
  23988. }
  23989. return this._rigCameras[0].getTarget();
  23990. };
  23991. /**
  23992. * Gets the right camera target of a rig setup in case of Rigged Camera
  23993. * @returns the target position
  23994. */
  23995. Camera.prototype.getRightTarget = function () {
  23996. if (this._rigCameras.length < 2) {
  23997. return null;
  23998. }
  23999. return this._rigCameras[1].getTarget();
  24000. };
  24001. /**
  24002. * @hidden
  24003. */
  24004. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  24005. if (this.cameraRigMode === mode) {
  24006. return;
  24007. }
  24008. while (this._rigCameras.length > 0) {
  24009. var camera = this._rigCameras.pop();
  24010. if (camera) {
  24011. camera.dispose();
  24012. }
  24013. }
  24014. this.cameraRigMode = mode;
  24015. this._cameraRigParams = {};
  24016. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  24017. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  24018. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  24019. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  24020. // create the rig cameras, unless none
  24021. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24022. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  24023. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  24024. if (leftCamera && rightCamera) {
  24025. this._rigCameras.push(leftCamera);
  24026. this._rigCameras.push(rightCamera);
  24027. }
  24028. }
  24029. switch (this.cameraRigMode) {
  24030. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  24031. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24032. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  24033. break;
  24034. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24035. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24036. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24037. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24038. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24039. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24040. break;
  24041. case Camera.RIG_MODE_VR:
  24042. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24043. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24044. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24045. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24046. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24047. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24048. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24049. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24050. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24051. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24052. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24053. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24054. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24055. if (metrics.compensateDistortion) {
  24056. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24057. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24058. }
  24059. break;
  24060. case Camera.RIG_MODE_WEBVR:
  24061. if (rigParams.vrDisplay) {
  24062. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24063. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24064. //Left eye
  24065. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24066. this._rigCameras[0].setCameraRigParameter("left", true);
  24067. //leaving this for future reference
  24068. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24069. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24070. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24071. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24072. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24073. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24074. this._rigCameras[0].parent = this;
  24075. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24076. //Right eye
  24077. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24078. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24079. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24080. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24081. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24082. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24083. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24084. this._rigCameras[1].parent = this;
  24085. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24086. if (Camera.UseAlternateWebVRRendering) {
  24087. this._rigCameras[1]._skipRendering = true;
  24088. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24089. }
  24090. }
  24091. break;
  24092. }
  24093. this._cascadePostProcessesToRigCams();
  24094. this.update();
  24095. };
  24096. Camera.prototype._getVRProjectionMatrix = function () {
  24097. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24098. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24099. return this._projectionMatrix;
  24100. };
  24101. Camera.prototype._updateCameraRotationMatrix = function () {
  24102. //Here for WebVR
  24103. };
  24104. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24105. //Here for WebVR
  24106. };
  24107. /**
  24108. * This function MUST be overwritten by the different WebVR cameras available.
  24109. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24110. */
  24111. Camera.prototype._getWebVRProjectionMatrix = function () {
  24112. return BABYLON.Matrix.Identity();
  24113. };
  24114. /**
  24115. * This function MUST be overwritten by the different WebVR cameras available.
  24116. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24117. */
  24118. Camera.prototype._getWebVRViewMatrix = function () {
  24119. return BABYLON.Matrix.Identity();
  24120. };
  24121. /** @hidden */
  24122. Camera.prototype.setCameraRigParameter = function (name, value) {
  24123. if (!this._cameraRigParams) {
  24124. this._cameraRigParams = {};
  24125. }
  24126. this._cameraRigParams[name] = value;
  24127. //provisionnally:
  24128. if (name === "interaxialDistance") {
  24129. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24130. }
  24131. };
  24132. /**
  24133. * needs to be overridden by children so sub has required properties to be copied
  24134. * @hidden
  24135. */
  24136. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24137. return null;
  24138. };
  24139. /**
  24140. * May need to be overridden by children
  24141. * @hidden
  24142. */
  24143. Camera.prototype._updateRigCameras = function () {
  24144. for (var i = 0; i < this._rigCameras.length; i++) {
  24145. this._rigCameras[i].minZ = this.minZ;
  24146. this._rigCameras[i].maxZ = this.maxZ;
  24147. this._rigCameras[i].fov = this.fov;
  24148. }
  24149. // only update viewport when ANAGLYPH
  24150. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24151. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24152. }
  24153. };
  24154. /** @hidden */
  24155. Camera.prototype._setupInputs = function () {
  24156. };
  24157. /**
  24158. * Serialiaze the camera setup to a json represention
  24159. * @returns the JSON representation
  24160. */
  24161. Camera.prototype.serialize = function () {
  24162. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24163. // Type
  24164. serializationObject.type = this.getClassName();
  24165. // Parent
  24166. if (this.parent) {
  24167. serializationObject.parentId = this.parent.id;
  24168. }
  24169. if (this.inputs) {
  24170. this.inputs.serialize(serializationObject);
  24171. }
  24172. // Animations
  24173. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24174. serializationObject.ranges = this.serializeAnimationRanges();
  24175. return serializationObject;
  24176. };
  24177. /**
  24178. * Clones the current camera.
  24179. * @param name The cloned camera name
  24180. * @returns the cloned camera
  24181. */
  24182. Camera.prototype.clone = function (name) {
  24183. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24184. };
  24185. /**
  24186. * Gets the direction of the camera relative to a given local axis.
  24187. * @param localAxis Defines the reference axis to provide a relative direction.
  24188. * @return the direction
  24189. */
  24190. Camera.prototype.getDirection = function (localAxis) {
  24191. var result = BABYLON.Vector3.Zero();
  24192. this.getDirectionToRef(localAxis, result);
  24193. return result;
  24194. };
  24195. /**
  24196. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24197. * @param localAxis Defines the reference axis to provide a relative direction.
  24198. * @param result Defines the vector to store the result in
  24199. */
  24200. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24201. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24202. };
  24203. /**
  24204. * Gets a camera constructor for a given camera type
  24205. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24206. * @param name The name of the camera the result will be able to instantiate
  24207. * @param scene The scene the result will construct the camera in
  24208. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24209. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24210. * @returns a factory method to construc the camera
  24211. */
  24212. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24213. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24214. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24215. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24216. interaxial_distance: interaxial_distance,
  24217. isStereoscopicSideBySide: isStereoscopicSideBySide
  24218. });
  24219. if (constructorFunc) {
  24220. return constructorFunc;
  24221. }
  24222. // Default to universal camera
  24223. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24224. };
  24225. /**
  24226. * Compute the world matrix of the camera.
  24227. * @returns the camera workd matrix
  24228. */
  24229. Camera.prototype.computeWorldMatrix = function () {
  24230. return this.getWorldMatrix();
  24231. };
  24232. /**
  24233. * Parse a JSON and creates the camera from the parsed information
  24234. * @param parsedCamera The JSON to parse
  24235. * @param scene The scene to instantiate the camera in
  24236. * @returns the newly constructed camera
  24237. */
  24238. Camera.Parse = function (parsedCamera, scene) {
  24239. var type = parsedCamera.type;
  24240. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24241. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24242. // Parent
  24243. if (parsedCamera.parentId) {
  24244. camera._waitingParentId = parsedCamera.parentId;
  24245. }
  24246. //If camera has an input manager, let it parse inputs settings
  24247. if (camera.inputs) {
  24248. camera.inputs.parse(parsedCamera);
  24249. camera._setupInputs();
  24250. }
  24251. if (camera.setPosition) { // need to force position
  24252. camera.position.copyFromFloats(0, 0, 0);
  24253. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24254. }
  24255. // Target
  24256. if (parsedCamera.target) {
  24257. if (camera.setTarget) {
  24258. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24259. }
  24260. }
  24261. // Apply 3d rig, when found
  24262. if (parsedCamera.cameraRigMode) {
  24263. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24264. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24265. }
  24266. // Animations
  24267. if (parsedCamera.animations) {
  24268. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24269. var parsedAnimation = parsedCamera.animations[animationIndex];
  24270. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24271. }
  24272. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24273. }
  24274. if (parsedCamera.autoAnimate) {
  24275. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24276. }
  24277. return camera;
  24278. };
  24279. /**
  24280. * This is the default projection mode used by the cameras.
  24281. * It helps recreating a feeling of perspective and better appreciate depth.
  24282. * This is the best way to simulate real life cameras.
  24283. */
  24284. Camera.PERSPECTIVE_CAMERA = 0;
  24285. /**
  24286. * This helps creating camera with an orthographic mode.
  24287. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  24288. */
  24289. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24290. /**
  24291. * This is the default FOV mode for perspective cameras.
  24292. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24293. */
  24294. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24295. /**
  24296. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24297. */
  24298. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24299. /**
  24300. * This specifies ther is no need for a camera rig.
  24301. * Basically only one eye is rendered corresponding to the camera.
  24302. */
  24303. Camera.RIG_MODE_NONE = 0;
  24304. /**
  24305. * Simulates a camera Rig with one blue eye and one red eye.
  24306. * This can be use with 3d blue and red glasses.
  24307. */
  24308. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24309. /**
  24310. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24311. */
  24312. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24313. /**
  24314. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24315. */
  24316. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24317. /**
  24318. * Defines that both eyes of the camera will be rendered over under each other.
  24319. */
  24320. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24321. /**
  24322. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24323. */
  24324. Camera.RIG_MODE_VR = 20;
  24325. /**
  24326. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24327. */
  24328. Camera.RIG_MODE_WEBVR = 21;
  24329. /**
  24330. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24331. */
  24332. Camera.RIG_MODE_CUSTOM = 22;
  24333. /**
  24334. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24335. */
  24336. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24337. /**
  24338. * @hidden
  24339. * Might be removed once multiview will be a thing
  24340. */
  24341. Camera.UseAlternateWebVRRendering = false;
  24342. __decorate([
  24343. BABYLON.serializeAsVector3()
  24344. ], Camera.prototype, "position", void 0);
  24345. __decorate([
  24346. BABYLON.serializeAsVector3()
  24347. ], Camera.prototype, "upVector", void 0);
  24348. __decorate([
  24349. BABYLON.serialize()
  24350. ], Camera.prototype, "orthoLeft", void 0);
  24351. __decorate([
  24352. BABYLON.serialize()
  24353. ], Camera.prototype, "orthoRight", void 0);
  24354. __decorate([
  24355. BABYLON.serialize()
  24356. ], Camera.prototype, "orthoBottom", void 0);
  24357. __decorate([
  24358. BABYLON.serialize()
  24359. ], Camera.prototype, "orthoTop", void 0);
  24360. __decorate([
  24361. BABYLON.serialize()
  24362. ], Camera.prototype, "fov", void 0);
  24363. __decorate([
  24364. BABYLON.serialize()
  24365. ], Camera.prototype, "minZ", void 0);
  24366. __decorate([
  24367. BABYLON.serialize()
  24368. ], Camera.prototype, "maxZ", void 0);
  24369. __decorate([
  24370. BABYLON.serialize()
  24371. ], Camera.prototype, "inertia", void 0);
  24372. __decorate([
  24373. BABYLON.serialize()
  24374. ], Camera.prototype, "mode", void 0);
  24375. __decorate([
  24376. BABYLON.serialize()
  24377. ], Camera.prototype, "layerMask", void 0);
  24378. __decorate([
  24379. BABYLON.serialize()
  24380. ], Camera.prototype, "fovMode", void 0);
  24381. __decorate([
  24382. BABYLON.serialize()
  24383. ], Camera.prototype, "cameraRigMode", void 0);
  24384. __decorate([
  24385. BABYLON.serialize()
  24386. ], Camera.prototype, "interaxialDistance", void 0);
  24387. __decorate([
  24388. BABYLON.serialize()
  24389. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24390. return Camera;
  24391. }(BABYLON.Node));
  24392. BABYLON.Camera = Camera;
  24393. })(BABYLON || (BABYLON = {}));
  24394. //# sourceMappingURL=babylon.camera.js.map
  24395. var BABYLON;
  24396. (function (BABYLON) {
  24397. /**
  24398. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24399. * It is enable to manage the different groups as well as the different necessary sort functions.
  24400. * This should not be used directly aside of the few static configurations
  24401. */
  24402. var RenderingManager = /** @class */ (function () {
  24403. /**
  24404. * Instantiates a new rendering group for a particular scene
  24405. * @param scene Defines the scene the groups belongs to
  24406. */
  24407. function RenderingManager(scene) {
  24408. /**
  24409. * @hidden
  24410. */
  24411. this._useSceneAutoClearSetup = false;
  24412. this._renderingGroups = new Array();
  24413. this._autoClearDepthStencil = {};
  24414. this._customOpaqueSortCompareFn = {};
  24415. this._customAlphaTestSortCompareFn = {};
  24416. this._customTransparentSortCompareFn = {};
  24417. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24418. this._scene = scene;
  24419. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24420. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24421. }
  24422. }
  24423. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24424. if (depth === void 0) { depth = true; }
  24425. if (stencil === void 0) { stencil = true; }
  24426. if (this._depthStencilBufferAlreadyCleaned) {
  24427. return;
  24428. }
  24429. this._scene.getEngine().clear(null, false, depth, stencil);
  24430. this._depthStencilBufferAlreadyCleaned = true;
  24431. };
  24432. /**
  24433. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24434. * @hidden
  24435. */
  24436. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24437. // Update the observable context (not null as it only goes away on dispose)
  24438. var info = this._renderingGroupInfo;
  24439. info.scene = this._scene;
  24440. info.camera = this._scene.activeCamera;
  24441. // Dispatch sprites
  24442. if (this._scene.spriteManagers && renderSprites) {
  24443. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24444. var manager = this._scene.spriteManagers[index];
  24445. this.dispatchSprites(manager);
  24446. }
  24447. }
  24448. // Render
  24449. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24450. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24451. var renderingGroup = this._renderingGroups[index];
  24452. if (!renderingGroup) {
  24453. continue;
  24454. }
  24455. var renderingGroupMask = Math.pow(2, index);
  24456. info.renderingGroupId = index;
  24457. // Before Observable
  24458. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24459. // Clear depth/stencil if needed
  24460. if (RenderingManager.AUTOCLEAR) {
  24461. var autoClear = this._useSceneAutoClearSetup ?
  24462. this._scene.getAutoClearDepthStencilSetup(index) :
  24463. this._autoClearDepthStencil[index];
  24464. if (autoClear && autoClear.autoClear) {
  24465. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24466. }
  24467. }
  24468. // Render
  24469. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24470. var step = _a[_i];
  24471. step.action(index);
  24472. }
  24473. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24474. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24475. var step = _c[_b];
  24476. step.action(index);
  24477. }
  24478. // After Observable
  24479. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24480. }
  24481. };
  24482. /**
  24483. * Resets the different information of the group to prepare a new frame
  24484. * @hidden
  24485. */
  24486. RenderingManager.prototype.reset = function () {
  24487. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24488. var renderingGroup = this._renderingGroups[index];
  24489. if (renderingGroup) {
  24490. renderingGroup.prepare();
  24491. }
  24492. }
  24493. };
  24494. /**
  24495. * Dispose and release the group and its associated resources.
  24496. * @hidden
  24497. */
  24498. RenderingManager.prototype.dispose = function () {
  24499. this.freeRenderingGroups();
  24500. this._renderingGroups.length = 0;
  24501. this._renderingGroupInfo = null;
  24502. };
  24503. /**
  24504. * Clear the info related to rendering groups preventing retention points during dispose.
  24505. */
  24506. RenderingManager.prototype.freeRenderingGroups = function () {
  24507. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24508. var renderingGroup = this._renderingGroups[index];
  24509. if (renderingGroup) {
  24510. renderingGroup.dispose();
  24511. }
  24512. }
  24513. };
  24514. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24515. if (this._renderingGroups[renderingGroupId] === undefined) {
  24516. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24517. }
  24518. };
  24519. /**
  24520. * Add a sprite manager to the rendering manager in order to render it this frame.
  24521. * @param spriteManager Define the sprite manager to render
  24522. */
  24523. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24524. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24525. this._prepareRenderingGroup(renderingGroupId);
  24526. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24527. };
  24528. /**
  24529. * Add a particle system to the rendering manager in order to render it this frame.
  24530. * @param particleSystem Define the particle system to render
  24531. */
  24532. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24533. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24534. this._prepareRenderingGroup(renderingGroupId);
  24535. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24536. };
  24537. /**
  24538. * Add a submesh to the manager in order to render it this frame
  24539. * @param subMesh The submesh to dispatch
  24540. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24541. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24542. */
  24543. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24544. if (mesh === undefined) {
  24545. mesh = subMesh.getMesh();
  24546. }
  24547. var renderingGroupId = mesh.renderingGroupId || 0;
  24548. this._prepareRenderingGroup(renderingGroupId);
  24549. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24550. };
  24551. /**
  24552. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24553. * This allowed control for front to back rendering or reversly depending of the special needs.
  24554. *
  24555. * @param renderingGroupId The rendering group id corresponding to its index
  24556. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24557. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24558. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24559. */
  24560. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24561. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24562. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24563. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24564. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24565. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24566. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24567. if (this._renderingGroups[renderingGroupId]) {
  24568. var group = this._renderingGroups[renderingGroupId];
  24569. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24570. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24571. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24572. }
  24573. };
  24574. /**
  24575. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24576. *
  24577. * @param renderingGroupId The rendering group id corresponding to its index
  24578. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24579. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24580. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24581. */
  24582. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24583. if (depth === void 0) { depth = true; }
  24584. if (stencil === void 0) { stencil = true; }
  24585. this._autoClearDepthStencil[renderingGroupId] = {
  24586. autoClear: autoClearDepthStencil,
  24587. depth: depth,
  24588. stencil: stencil
  24589. };
  24590. };
  24591. /**
  24592. * Gets the current auto clear configuration for one rendering group of the rendering
  24593. * manager.
  24594. * @param index the rendering group index to get the information for
  24595. * @returns The auto clear setup for the requested rendering group
  24596. */
  24597. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24598. return this._autoClearDepthStencil[index];
  24599. };
  24600. /**
  24601. * The max id used for rendering groups (not included)
  24602. */
  24603. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24604. /**
  24605. * The min id used for rendering groups (included)
  24606. */
  24607. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24608. /**
  24609. * Used to globally prevent autoclearing scenes.
  24610. */
  24611. RenderingManager.AUTOCLEAR = true;
  24612. return RenderingManager;
  24613. }());
  24614. BABYLON.RenderingManager = RenderingManager;
  24615. })(BABYLON || (BABYLON = {}));
  24616. //# sourceMappingURL=babylon.renderingManager.js.map
  24617. var BABYLON;
  24618. (function (BABYLON) {
  24619. /**
  24620. * This represents the object necessary to create a rendering group.
  24621. * This is exclusively used and created by the rendering manager.
  24622. * To modify the behavior, you use the available helpers in your scene or meshes.
  24623. * @hidden
  24624. */
  24625. var RenderingGroup = /** @class */ (function () {
  24626. /**
  24627. * Creates a new rendering group.
  24628. * @param index The rendering group index
  24629. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24630. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24631. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24632. */
  24633. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24634. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24635. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24636. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24637. this.index = index;
  24638. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24639. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24640. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24641. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24642. this._particleSystems = new BABYLON.SmartArray(256);
  24643. this._spriteManagers = new BABYLON.SmartArray(256);
  24644. this._edgesRenderers = new BABYLON.SmartArray(16);
  24645. this._scene = scene;
  24646. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24647. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24648. this.transparentSortCompareFn = transparentSortCompareFn;
  24649. }
  24650. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24651. /**
  24652. * Set the opaque sort comparison function.
  24653. * If null the sub meshes will be render in the order they were created
  24654. */
  24655. set: function (value) {
  24656. this._opaqueSortCompareFn = value;
  24657. if (value) {
  24658. this._renderOpaque = this.renderOpaqueSorted;
  24659. }
  24660. else {
  24661. this._renderOpaque = RenderingGroup.renderUnsorted;
  24662. }
  24663. },
  24664. enumerable: true,
  24665. configurable: true
  24666. });
  24667. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24668. /**
  24669. * Set the alpha test sort comparison function.
  24670. * If null the sub meshes will be render in the order they were created
  24671. */
  24672. set: function (value) {
  24673. this._alphaTestSortCompareFn = value;
  24674. if (value) {
  24675. this._renderAlphaTest = this.renderAlphaTestSorted;
  24676. }
  24677. else {
  24678. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24679. }
  24680. },
  24681. enumerable: true,
  24682. configurable: true
  24683. });
  24684. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24685. /**
  24686. * Set the transparent sort comparison function.
  24687. * If null the sub meshes will be render in the order they were created
  24688. */
  24689. set: function (value) {
  24690. if (value) {
  24691. this._transparentSortCompareFn = value;
  24692. }
  24693. else {
  24694. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24695. }
  24696. this._renderTransparent = this.renderTransparentSorted;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. /**
  24702. * Render all the sub meshes contained in the group.
  24703. * @param customRenderFunction Used to override the default render behaviour of the group.
  24704. * @returns true if rendered some submeshes.
  24705. */
  24706. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24707. if (customRenderFunction) {
  24708. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24709. return;
  24710. }
  24711. var engine = this._scene.getEngine();
  24712. // Depth only
  24713. if (this._depthOnlySubMeshes.length !== 0) {
  24714. engine.setColorWrite(false);
  24715. this._renderAlphaTest(this._depthOnlySubMeshes);
  24716. engine.setColorWrite(true);
  24717. }
  24718. // Opaque
  24719. if (this._opaqueSubMeshes.length !== 0) {
  24720. this._renderOpaque(this._opaqueSubMeshes);
  24721. }
  24722. // Alpha test
  24723. if (this._alphaTestSubMeshes.length !== 0) {
  24724. this._renderAlphaTest(this._alphaTestSubMeshes);
  24725. }
  24726. var stencilState = engine.getStencilBuffer();
  24727. engine.setStencilBuffer(false);
  24728. // Sprites
  24729. if (renderSprites) {
  24730. this._renderSprites();
  24731. }
  24732. // Particles
  24733. if (renderParticles) {
  24734. this._renderParticles(activeMeshes);
  24735. }
  24736. if (this.onBeforeTransparentRendering) {
  24737. this.onBeforeTransparentRendering();
  24738. }
  24739. // Transparent
  24740. if (this._transparentSubMeshes.length !== 0) {
  24741. this._renderTransparent(this._transparentSubMeshes);
  24742. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24743. }
  24744. // Set back stencil to false in case it changes before the edge renderer.
  24745. engine.setStencilBuffer(false);
  24746. // Edges
  24747. if (this._edgesRenderers.length) {
  24748. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24749. this._edgesRenderers.data[edgesRendererIndex].render();
  24750. }
  24751. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24752. }
  24753. // Restore Stencil state.
  24754. engine.setStencilBuffer(stencilState);
  24755. };
  24756. /**
  24757. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24758. * @param subMeshes The submeshes to render
  24759. */
  24760. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24761. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24762. };
  24763. /**
  24764. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24765. * @param subMeshes The submeshes to render
  24766. */
  24767. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24768. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24769. };
  24770. /**
  24771. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24772. * @param subMeshes The submeshes to render
  24773. */
  24774. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24775. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24776. };
  24777. /**
  24778. * Renders the submeshes in a specified order.
  24779. * @param subMeshes The submeshes to sort before render
  24780. * @param sortCompareFn The comparison function use to sort
  24781. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24782. * @param transparent Specifies to activate blending if true
  24783. */
  24784. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24785. var subIndex = 0;
  24786. var subMesh;
  24787. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24788. for (; subIndex < subMeshes.length; subIndex++) {
  24789. subMesh = subMeshes.data[subIndex];
  24790. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24791. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24792. }
  24793. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24794. if (sortCompareFn) {
  24795. sortedArray.sort(sortCompareFn);
  24796. }
  24797. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24798. subMesh = sortedArray[subIndex];
  24799. if (transparent) {
  24800. var material = subMesh.getMaterial();
  24801. if (material && material.needDepthPrePass) {
  24802. var engine = material.getScene().getEngine();
  24803. engine.setColorWrite(false);
  24804. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24805. subMesh.render(false);
  24806. engine.setColorWrite(true);
  24807. }
  24808. }
  24809. subMesh.render(transparent);
  24810. }
  24811. };
  24812. /**
  24813. * Renders the submeshes in the order they were dispatched (no sort applied).
  24814. * @param subMeshes The submeshes to render
  24815. */
  24816. RenderingGroup.renderUnsorted = function (subMeshes) {
  24817. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24818. var submesh = subMeshes.data[subIndex];
  24819. submesh.render(false);
  24820. }
  24821. };
  24822. /**
  24823. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24824. * are rendered back to front if in the same alpha index.
  24825. *
  24826. * @param a The first submesh
  24827. * @param b The second submesh
  24828. * @returns The result of the comparison
  24829. */
  24830. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24831. // Alpha index first
  24832. if (a._alphaIndex > b._alphaIndex) {
  24833. return 1;
  24834. }
  24835. if (a._alphaIndex < b._alphaIndex) {
  24836. return -1;
  24837. }
  24838. // Then distance to camera
  24839. return RenderingGroup.backToFrontSortCompare(a, b);
  24840. };
  24841. /**
  24842. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24843. * are rendered back to front.
  24844. *
  24845. * @param a The first submesh
  24846. * @param b The second submesh
  24847. * @returns The result of the comparison
  24848. */
  24849. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24850. // Then distance to camera
  24851. if (a._distanceToCamera < b._distanceToCamera) {
  24852. return 1;
  24853. }
  24854. if (a._distanceToCamera > b._distanceToCamera) {
  24855. return -1;
  24856. }
  24857. return 0;
  24858. };
  24859. /**
  24860. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24861. * are rendered front to back (prevent overdraw).
  24862. *
  24863. * @param a The first submesh
  24864. * @param b The second submesh
  24865. * @returns The result of the comparison
  24866. */
  24867. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24868. // Then distance to camera
  24869. if (a._distanceToCamera < b._distanceToCamera) {
  24870. return -1;
  24871. }
  24872. if (a._distanceToCamera > b._distanceToCamera) {
  24873. return 1;
  24874. }
  24875. return 0;
  24876. };
  24877. /**
  24878. * Resets the different lists of submeshes to prepare a new frame.
  24879. */
  24880. RenderingGroup.prototype.prepare = function () {
  24881. this._opaqueSubMeshes.reset();
  24882. this._transparentSubMeshes.reset();
  24883. this._alphaTestSubMeshes.reset();
  24884. this._depthOnlySubMeshes.reset();
  24885. this._particleSystems.reset();
  24886. this._spriteManagers.reset();
  24887. this._edgesRenderers.reset();
  24888. };
  24889. RenderingGroup.prototype.dispose = function () {
  24890. this._opaqueSubMeshes.dispose();
  24891. this._transparentSubMeshes.dispose();
  24892. this._alphaTestSubMeshes.dispose();
  24893. this._depthOnlySubMeshes.dispose();
  24894. this._particleSystems.dispose();
  24895. this._spriteManagers.dispose();
  24896. this._edgesRenderers.dispose();
  24897. };
  24898. /**
  24899. * Inserts the submesh in its correct queue depending on its material.
  24900. * @param subMesh The submesh to dispatch
  24901. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24902. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24903. */
  24904. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24905. // Get mesh and materials if not provided
  24906. if (mesh === undefined) {
  24907. mesh = subMesh.getMesh();
  24908. }
  24909. if (material === undefined) {
  24910. material = subMesh.getMaterial();
  24911. }
  24912. if (material === null || material === undefined) {
  24913. return;
  24914. }
  24915. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24916. this._transparentSubMeshes.push(subMesh);
  24917. }
  24918. else if (material.needAlphaTesting()) { // Alpha test
  24919. if (material.needDepthPrePass) {
  24920. this._depthOnlySubMeshes.push(subMesh);
  24921. }
  24922. this._alphaTestSubMeshes.push(subMesh);
  24923. }
  24924. else {
  24925. if (material.needDepthPrePass) {
  24926. this._depthOnlySubMeshes.push(subMesh);
  24927. }
  24928. this._opaqueSubMeshes.push(subMesh); // Opaque
  24929. }
  24930. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24931. this._edgesRenderers.push(mesh._edgesRenderer);
  24932. }
  24933. };
  24934. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24935. this._spriteManagers.push(spriteManager);
  24936. };
  24937. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24938. this._particleSystems.push(particleSystem);
  24939. };
  24940. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24941. if (this._particleSystems.length === 0) {
  24942. return;
  24943. }
  24944. // Particles
  24945. var activeCamera = this._scene.activeCamera;
  24946. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24947. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24948. var particleSystem = this._particleSystems.data[particleIndex];
  24949. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24950. continue;
  24951. }
  24952. var emitter = particleSystem.emitter;
  24953. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24954. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24955. }
  24956. }
  24957. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24958. };
  24959. RenderingGroup.prototype._renderSprites = function () {
  24960. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24961. return;
  24962. }
  24963. // Sprites
  24964. var activeCamera = this._scene.activeCamera;
  24965. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24966. for (var id = 0; id < this._spriteManagers.length; id++) {
  24967. var spriteManager = this._spriteManagers.data[id];
  24968. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24969. spriteManager.render();
  24970. }
  24971. }
  24972. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24973. };
  24974. return RenderingGroup;
  24975. }());
  24976. BABYLON.RenderingGroup = RenderingGroup;
  24977. })(BABYLON || (BABYLON = {}));
  24978. //# sourceMappingURL=babylon.renderingGroup.js.map
  24979. var BABYLON;
  24980. (function (BABYLON) {
  24981. /**
  24982. * Groups all the scene component constants in one place to ease maintenance.
  24983. * @hidden
  24984. */
  24985. var SceneComponentConstants = /** @class */ (function () {
  24986. function SceneComponentConstants() {
  24987. }
  24988. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24989. SceneComponentConstants.NAME_LAYER = "Layer";
  24990. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24991. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24992. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24993. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24994. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24995. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24996. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24997. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24998. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24999. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  25000. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  25001. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  25002. SceneComponentConstants.NAME_OCTREE = "Octree";
  25003. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  25004. SceneComponentConstants.NAME_AUDIO = "Audio";
  25005. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  25006. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25007. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  25008. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25009. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  25010. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  25011. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  25012. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  25013. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  25014. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  25015. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  25016. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  25017. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  25018. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  25019. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  25020. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  25021. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  25022. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  25023. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  25024. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  25025. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  25026. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  25027. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  25028. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  25029. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  25030. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  25031. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  25032. return SceneComponentConstants;
  25033. }());
  25034. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25035. /**
  25036. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25037. * @hidden
  25038. */
  25039. var Stage = /** @class */ (function (_super) {
  25040. __extends(Stage, _super);
  25041. /**
  25042. * Hide ctor from the rest of the world.
  25043. * @param items The items to add.
  25044. */
  25045. function Stage(items) {
  25046. return _super.apply(this, items) || this;
  25047. }
  25048. /**
  25049. * Creates a new Stage.
  25050. * @returns A new instance of a Stage
  25051. */
  25052. Stage.Create = function () {
  25053. return Object.create(Stage.prototype);
  25054. };
  25055. /**
  25056. * Registers a step in an ordered way in the targeted stage.
  25057. * @param index Defines the position to register the step in
  25058. * @param component Defines the component attached to the step
  25059. * @param action Defines the action to launch during the step
  25060. */
  25061. Stage.prototype.registerStep = function (index, component, action) {
  25062. var i = 0;
  25063. var maxIndex = Number.MAX_VALUE;
  25064. for (; i < this.length; i++) {
  25065. var step = this[i];
  25066. maxIndex = step.index;
  25067. if (index < maxIndex) {
  25068. break;
  25069. }
  25070. }
  25071. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25072. };
  25073. /**
  25074. * Clears all the steps from the stage.
  25075. */
  25076. Stage.prototype.clear = function () {
  25077. this.length = 0;
  25078. };
  25079. return Stage;
  25080. }(Array));
  25081. BABYLON.Stage = Stage;
  25082. })(BABYLON || (BABYLON = {}));
  25083. //# sourceMappingURL=babylon.sceneComponent.js.map
  25084. var BABYLON;
  25085. (function (BABYLON) {
  25086. /**
  25087. * Base class of the scene acting as a container for the different elements composing a scene.
  25088. * This class is dynamically extended by the different components of the scene increasing
  25089. * flexibility and reducing coupling
  25090. */
  25091. var AbstractScene = /** @class */ (function () {
  25092. function AbstractScene() {
  25093. /**
  25094. * Gets the list of root nodes (ie. nodes with no parent)
  25095. */
  25096. this.rootNodes = new Array();
  25097. /** All of the cameras added to this scene
  25098. * @see http://doc.babylonjs.com/babylon101/cameras
  25099. */
  25100. this.cameras = new Array();
  25101. /**
  25102. * All of the lights added to this scene
  25103. * @see http://doc.babylonjs.com/babylon101/lights
  25104. */
  25105. this.lights = new Array();
  25106. /**
  25107. * All of the (abstract) meshes added to this scene
  25108. */
  25109. this.meshes = new Array();
  25110. /**
  25111. * The list of skeletons added to the scene
  25112. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25113. */
  25114. this.skeletons = new Array();
  25115. /**
  25116. * All of the particle systems added to this scene
  25117. * @see http://doc.babylonjs.com/babylon101/particles
  25118. */
  25119. this.particleSystems = new Array();
  25120. /**
  25121. * Gets a list of Animations associated with the scene
  25122. */
  25123. this.animations = [];
  25124. /**
  25125. * All of the animation groups added to this scene
  25126. * @see http://doc.babylonjs.com/how_to/group
  25127. */
  25128. this.animationGroups = new Array();
  25129. /**
  25130. * All of the multi-materials added to this scene
  25131. * @see http://doc.babylonjs.com/how_to/multi_materials
  25132. */
  25133. this.multiMaterials = new Array();
  25134. /**
  25135. * All of the materials added to this scene
  25136. * In the context of a Scene, it is not supposed to be modified manually.
  25137. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25138. * Note also that the order of the Material wihin the array is not significant and might change.
  25139. * @see http://doc.babylonjs.com/babylon101/materials
  25140. */
  25141. this.materials = new Array();
  25142. /**
  25143. * The list of morph target managers added to the scene
  25144. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25145. */
  25146. this.morphTargetManagers = new Array();
  25147. /**
  25148. * The list of geometries used in the scene.
  25149. */
  25150. this.geometries = new Array();
  25151. /**
  25152. * All of the tranform nodes added to this scene
  25153. * In the context of a Scene, it is not supposed to be modified manually.
  25154. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25155. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25156. * @see http://doc.babylonjs.com/how_to/transformnode
  25157. */
  25158. this.transformNodes = new Array();
  25159. /**
  25160. * ActionManagers available on the scene.
  25161. */
  25162. this.actionManagers = new Array();
  25163. /**
  25164. * Textures to keep.
  25165. */
  25166. this.textures = new Array();
  25167. }
  25168. /**
  25169. * Adds a parser in the list of available ones
  25170. * @param name Defines the name of the parser
  25171. * @param parser Defines the parser to add
  25172. */
  25173. AbstractScene.AddParser = function (name, parser) {
  25174. this._BabylonFileParsers[name] = parser;
  25175. };
  25176. /**
  25177. * Gets a general parser from the list of avaialble ones
  25178. * @param name Defines the name of the parser
  25179. * @returns the requested parser or null
  25180. */
  25181. AbstractScene.GetParser = function (name) {
  25182. if (this._BabylonFileParsers[name]) {
  25183. return this._BabylonFileParsers[name];
  25184. }
  25185. return null;
  25186. };
  25187. /**
  25188. * Adds n individual parser in the list of available ones
  25189. * @param name Defines the name of the parser
  25190. * @param parser Defines the parser to add
  25191. */
  25192. AbstractScene.AddIndividualParser = function (name, parser) {
  25193. this._IndividualBabylonFileParsers[name] = parser;
  25194. };
  25195. /**
  25196. * Gets an individual parser from the list of avaialble ones
  25197. * @param name Defines the name of the parser
  25198. * @returns the requested parser or null
  25199. */
  25200. AbstractScene.GetIndividualParser = function (name) {
  25201. if (this._IndividualBabylonFileParsers[name]) {
  25202. return this._IndividualBabylonFileParsers[name];
  25203. }
  25204. return null;
  25205. };
  25206. /**
  25207. * Parser json data and populate both a scene and its associated container object
  25208. * @param jsonData Defines the data to parse
  25209. * @param scene Defines the scene to parse the data for
  25210. * @param container Defines the container attached to the parsing sequence
  25211. * @param rootUrl Defines the root url of the data
  25212. */
  25213. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25214. for (var parserName in this._BabylonFileParsers) {
  25215. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25216. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25217. }
  25218. }
  25219. };
  25220. /**
  25221. * Stores the list of available parsers in the application.
  25222. */
  25223. AbstractScene._BabylonFileParsers = {};
  25224. /**
  25225. * Stores the list of available individual parsers in the application.
  25226. */
  25227. AbstractScene._IndividualBabylonFileParsers = {};
  25228. return AbstractScene;
  25229. }());
  25230. BABYLON.AbstractScene = AbstractScene;
  25231. })(BABYLON || (BABYLON = {}));
  25232. //# sourceMappingURL=babylon.abstractScene.js.map
  25233. var BABYLON;
  25234. (function (BABYLON) {
  25235. /** @hidden */
  25236. var ClickInfo = /** @class */ (function () {
  25237. function ClickInfo() {
  25238. this._singleClick = false;
  25239. this._doubleClick = false;
  25240. this._hasSwiped = false;
  25241. this._ignore = false;
  25242. }
  25243. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25244. get: function () {
  25245. return this._singleClick;
  25246. },
  25247. set: function (b) {
  25248. this._singleClick = b;
  25249. },
  25250. enumerable: true,
  25251. configurable: true
  25252. });
  25253. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25254. get: function () {
  25255. return this._doubleClick;
  25256. },
  25257. set: function (b) {
  25258. this._doubleClick = b;
  25259. },
  25260. enumerable: true,
  25261. configurable: true
  25262. });
  25263. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25264. get: function () {
  25265. return this._hasSwiped;
  25266. },
  25267. set: function (b) {
  25268. this._hasSwiped = b;
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25274. get: function () {
  25275. return this._ignore;
  25276. },
  25277. set: function (b) {
  25278. this._ignore = b;
  25279. },
  25280. enumerable: true,
  25281. configurable: true
  25282. });
  25283. return ClickInfo;
  25284. }());
  25285. /**
  25286. * This class is used by the onRenderingGroupObservable
  25287. */
  25288. var RenderingGroupInfo = /** @class */ (function () {
  25289. function RenderingGroupInfo() {
  25290. }
  25291. return RenderingGroupInfo;
  25292. }());
  25293. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25294. /**
  25295. * Represents a scene to be rendered by the engine.
  25296. * @see http://doc.babylonjs.com/features/scene
  25297. */
  25298. var Scene = /** @class */ (function (_super) {
  25299. __extends(Scene, _super);
  25300. /**
  25301. * Creates a new Scene
  25302. * @param engine defines the engine to use to render this scene
  25303. */
  25304. function Scene(engine, options) {
  25305. var _this = _super.call(this) || this;
  25306. // Members
  25307. /**
  25308. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25309. */
  25310. _this.autoClear = true;
  25311. /**
  25312. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25313. */
  25314. _this.autoClearDepthAndStencil = true;
  25315. /**
  25316. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25317. */
  25318. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25319. /**
  25320. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25321. */
  25322. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25323. _this._forceWireframe = false;
  25324. _this._forcePointsCloud = false;
  25325. /**
  25326. * Gets or sets a boolean indicating if animations are enabled
  25327. */
  25328. _this.animationsEnabled = true;
  25329. _this._animationPropertiesOverride = null;
  25330. /**
  25331. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25332. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25333. */
  25334. _this.useConstantAnimationDeltaTime = false;
  25335. /**
  25336. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25337. * Please note that it requires to run a ray cast through the scene on every frame
  25338. */
  25339. _this.constantlyUpdateMeshUnderPointer = false;
  25340. /**
  25341. * Defines the HTML cursor to use when hovering over interactive elements
  25342. */
  25343. _this.hoverCursor = "pointer";
  25344. /**
  25345. * Defines the HTML default cursor to use (empty by default)
  25346. */
  25347. _this.defaultCursor = "";
  25348. /**
  25349. * This is used to call preventDefault() on pointer down
  25350. * in order to block unwanted artifacts like system double clicks
  25351. */
  25352. _this.preventDefaultOnPointerDown = true;
  25353. /**
  25354. * This is used to call preventDefault() on pointer up
  25355. * in order to block unwanted artifacts like system double clicks
  25356. */
  25357. _this.preventDefaultOnPointerUp = true;
  25358. // Metadata
  25359. /**
  25360. * Gets or sets user defined metadata
  25361. */
  25362. _this.metadata = null;
  25363. /**
  25364. * Use this array to add regular expressions used to disable offline support for specific urls
  25365. */
  25366. _this.disableOfflineSupportExceptionRules = new Array();
  25367. /**
  25368. * An event triggered when the scene is disposed.
  25369. */
  25370. _this.onDisposeObservable = new BABYLON.Observable();
  25371. _this._onDisposeObserver = null;
  25372. /**
  25373. * An event triggered before rendering the scene (right after animations and physics)
  25374. */
  25375. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25376. _this._onBeforeRenderObserver = null;
  25377. /**
  25378. * An event triggered after rendering the scene
  25379. */
  25380. _this.onAfterRenderObservable = new BABYLON.Observable();
  25381. _this._onAfterRenderObserver = null;
  25382. /**
  25383. * An event triggered before animating the scene
  25384. */
  25385. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25386. /**
  25387. * An event triggered after animations processing
  25388. */
  25389. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25390. /**
  25391. * An event triggered before draw calls are ready to be sent
  25392. */
  25393. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25394. /**
  25395. * An event triggered after draw calls have been sent
  25396. */
  25397. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25398. /**
  25399. * An event triggered when the scene is ready
  25400. */
  25401. _this.onReadyObservable = new BABYLON.Observable();
  25402. /**
  25403. * An event triggered before rendering a camera
  25404. */
  25405. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25406. _this._onBeforeCameraRenderObserver = null;
  25407. /**
  25408. * An event triggered after rendering a camera
  25409. */
  25410. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25411. _this._onAfterCameraRenderObserver = null;
  25412. /**
  25413. * An event triggered when active meshes evaluation is about to start
  25414. */
  25415. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25416. /**
  25417. * An event triggered when active meshes evaluation is done
  25418. */
  25419. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25420. /**
  25421. * An event triggered when particles rendering is about to start
  25422. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25423. */
  25424. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25425. /**
  25426. * An event triggered when particles rendering is done
  25427. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25428. */
  25429. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25430. /**
  25431. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25432. */
  25433. _this.onDataLoadedObservable = new BABYLON.Observable();
  25434. /**
  25435. * An event triggered when a camera is created
  25436. */
  25437. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25438. /**
  25439. * An event triggered when a camera is removed
  25440. */
  25441. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25442. /**
  25443. * An event triggered when a light is created
  25444. */
  25445. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25446. /**
  25447. * An event triggered when a light is removed
  25448. */
  25449. _this.onLightRemovedObservable = new BABYLON.Observable();
  25450. /**
  25451. * An event triggered when a geometry is created
  25452. */
  25453. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25454. /**
  25455. * An event triggered when a geometry is removed
  25456. */
  25457. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25458. /**
  25459. * An event triggered when a transform node is created
  25460. */
  25461. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25462. /**
  25463. * An event triggered when a transform node is removed
  25464. */
  25465. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25466. /**
  25467. * An event triggered when a mesh is created
  25468. */
  25469. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25470. /**
  25471. * An event triggered when a mesh is removed
  25472. */
  25473. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25474. /**
  25475. * An event triggered when a material is created
  25476. */
  25477. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25478. /**
  25479. * An event triggered when a material is removed
  25480. */
  25481. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25482. /**
  25483. * An event triggered when a texture is created
  25484. */
  25485. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25486. /**
  25487. * An event triggered when a texture is removed
  25488. */
  25489. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25490. /**
  25491. * An event triggered when render targets are about to be rendered
  25492. * Can happen multiple times per frame.
  25493. */
  25494. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25495. /**
  25496. * An event triggered when render targets were rendered.
  25497. * Can happen multiple times per frame.
  25498. */
  25499. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25500. /**
  25501. * An event triggered before calculating deterministic simulation step
  25502. */
  25503. _this.onBeforeStepObservable = new BABYLON.Observable();
  25504. /**
  25505. * An event triggered after calculating deterministic simulation step
  25506. */
  25507. _this.onAfterStepObservable = new BABYLON.Observable();
  25508. /**
  25509. * An event triggered when the activeCamera property is updated
  25510. */
  25511. _this.onActiveCameraChanged = new BABYLON.Observable();
  25512. /**
  25513. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25514. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25515. * 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)
  25516. */
  25517. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25518. /**
  25519. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25520. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25521. * 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)
  25522. */
  25523. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25524. /**
  25525. * This Observable will when a mesh has been imported into the scene.
  25526. */
  25527. _this.onMeshImportedObservable = new BABYLON.Observable();
  25528. // Animations
  25529. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25530. /**
  25531. * 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).
  25532. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25533. */
  25534. _this.onPrePointerObservable = new BABYLON.Observable();
  25535. /**
  25536. * Observable event triggered each time an input event is received from the rendering canvas
  25537. */
  25538. _this.onPointerObservable = new BABYLON.Observable();
  25539. _this._meshPickProceed = false;
  25540. _this._currentPickResult = null;
  25541. _this._previousPickResult = null;
  25542. _this._totalPointersPressed = 0;
  25543. _this._doubleClickOccured = false;
  25544. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25545. _this.cameraToUseForPointers = null;
  25546. _this._pointerX = 0;
  25547. _this._pointerY = 0;
  25548. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25549. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25550. _this._startingPointerTime = 0;
  25551. _this._previousStartingPointerTime = 0;
  25552. _this._pointerCaptures = {};
  25553. // Deterministic lockstep
  25554. _this._timeAccumulator = 0;
  25555. _this._currentStepId = 0;
  25556. _this._currentInternalStep = 0;
  25557. // Keyboard
  25558. /**
  25559. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25560. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25561. */
  25562. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25563. /**
  25564. * Observable event triggered each time an keyboard event is received from the hosting window
  25565. */
  25566. _this.onKeyboardObservable = new BABYLON.Observable();
  25567. // Coordinates system
  25568. _this._useRightHandedSystem = false;
  25569. // Fog
  25570. _this._fogEnabled = true;
  25571. _this._fogMode = Scene.FOGMODE_NONE;
  25572. /**
  25573. * Gets or sets the fog color to use
  25574. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25575. * (Default is Color3(0.2, 0.2, 0.3))
  25576. */
  25577. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25578. /**
  25579. * Gets or sets the fog density to use
  25580. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25581. * (Default is 0.1)
  25582. */
  25583. _this.fogDensity = 0.1;
  25584. /**
  25585. * Gets or sets the fog start distance to use
  25586. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25587. * (Default is 0)
  25588. */
  25589. _this.fogStart = 0;
  25590. /**
  25591. * Gets or sets the fog end distance to use
  25592. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25593. * (Default is 1000)
  25594. */
  25595. _this.fogEnd = 1000.0;
  25596. // Lights
  25597. _this._shadowsEnabled = true;
  25598. _this._lightsEnabled = true;
  25599. /** All of the active cameras added to this scene. */
  25600. _this.activeCameras = new Array();
  25601. // Textures
  25602. _this._texturesEnabled = true;
  25603. // Particles
  25604. /**
  25605. * Gets or sets a boolean indicating if particles are enabled on this scene
  25606. */
  25607. _this.particlesEnabled = true;
  25608. // Sprites
  25609. /**
  25610. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25611. */
  25612. _this.spritesEnabled = true;
  25613. // Skeletons
  25614. _this._skeletonsEnabled = true;
  25615. // Lens flares
  25616. /**
  25617. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25618. */
  25619. _this.lensFlaresEnabled = true;
  25620. // Collisions
  25621. /**
  25622. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25623. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25624. */
  25625. _this.collisionsEnabled = true;
  25626. /**
  25627. * Defines the gravity applied to this scene (used only for collisions)
  25628. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25629. */
  25630. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25631. // Postprocesses
  25632. /**
  25633. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25634. */
  25635. _this.postProcessesEnabled = true;
  25636. /**
  25637. * The list of postprocesses added to the scene
  25638. */
  25639. _this.postProcesses = new Array();
  25640. // Customs render targets
  25641. /**
  25642. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25643. */
  25644. _this.renderTargetsEnabled = true;
  25645. /**
  25646. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25647. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25648. */
  25649. _this.dumpNextRenderTargets = false;
  25650. /**
  25651. * The list of user defined render targets added to the scene
  25652. */
  25653. _this.customRenderTargets = new Array();
  25654. /**
  25655. * Gets the list of meshes imported to the scene through SceneLoader
  25656. */
  25657. _this.importedMeshesFiles = new Array();
  25658. // Probes
  25659. /**
  25660. * Gets or sets a boolean indicating if probes are enabled on this scene
  25661. */
  25662. _this.probesEnabled = true;
  25663. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25664. // Procedural textures
  25665. /**
  25666. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25667. */
  25668. _this.proceduralTexturesEnabled = true;
  25669. // Performance counters
  25670. _this._totalVertices = new BABYLON.PerfCounter();
  25671. /** @hidden */
  25672. _this._activeIndices = new BABYLON.PerfCounter();
  25673. /** @hidden */
  25674. _this._activeParticles = new BABYLON.PerfCounter();
  25675. /** @hidden */
  25676. _this._activeBones = new BABYLON.PerfCounter();
  25677. _this._animationTime = 0;
  25678. /**
  25679. * Gets or sets a general scale for animation speed
  25680. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25681. */
  25682. _this.animationTimeScale = 1;
  25683. _this._renderId = 0;
  25684. _this._frameId = 0;
  25685. _this._executeWhenReadyTimeoutId = -1;
  25686. _this._intermediateRendering = false;
  25687. _this._viewUpdateFlag = -1;
  25688. _this._projectionUpdateFlag = -1;
  25689. _this._alternateViewUpdateFlag = -1;
  25690. _this._alternateProjectionUpdateFlag = -1;
  25691. /** @hidden */
  25692. _this._toBeDisposed = new Array(256);
  25693. _this._activeRequests = new Array();
  25694. _this._pendingData = new Array();
  25695. _this._isDisposed = false;
  25696. /**
  25697. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25698. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25699. */
  25700. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25701. _this._activeMeshes = new BABYLON.SmartArray(256);
  25702. _this._processedMaterials = new BABYLON.SmartArray(256);
  25703. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25704. /** @hidden */
  25705. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25706. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25707. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25708. /** @hidden */
  25709. _this._activeAnimatables = new Array();
  25710. _this._transformMatrix = BABYLON.Matrix.Zero();
  25711. _this._useAlternateCameraConfiguration = false;
  25712. _this._alternateRendering = false;
  25713. _this._wheelEventName = "";
  25714. /**
  25715. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25716. * This is useful if there are more lights that the maximum simulteanous authorized
  25717. */
  25718. _this.requireLightSorting = false;
  25719. /**
  25720. * @hidden
  25721. * Backing store of defined scene components.
  25722. */
  25723. _this._components = [];
  25724. /**
  25725. * @hidden
  25726. * Backing store of defined scene components.
  25727. */
  25728. _this._serializableComponents = [];
  25729. /**
  25730. * List of components to register on the next registration step.
  25731. */
  25732. _this._transientComponents = [];
  25733. /**
  25734. * @hidden
  25735. * Defines the actions happening before camera updates.
  25736. */
  25737. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25738. /**
  25739. * @hidden
  25740. * Defines the actions happening before clear the canvas.
  25741. */
  25742. _this._beforeClearStage = BABYLON.Stage.Create();
  25743. /**
  25744. * @hidden
  25745. * Defines the actions when collecting render targets for the frame.
  25746. */
  25747. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25748. /**
  25749. * @hidden
  25750. * Defines the actions happening for one camera in the frame.
  25751. */
  25752. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25753. /**
  25754. * @hidden
  25755. * Defines the actions happening during the per mesh ready checks.
  25756. */
  25757. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25758. /**
  25759. * @hidden
  25760. * Defines the actions happening before evaluate active mesh checks.
  25761. */
  25762. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25763. /**
  25764. * @hidden
  25765. * Defines the actions happening during the evaluate sub mesh checks.
  25766. */
  25767. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25768. /**
  25769. * @hidden
  25770. * Defines the actions happening during the active mesh stage.
  25771. */
  25772. _this._activeMeshStage = BABYLON.Stage.Create();
  25773. /**
  25774. * @hidden
  25775. * Defines the actions happening during the per camera render target step.
  25776. */
  25777. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25778. /**
  25779. * @hidden
  25780. * Defines the actions happening just before the active camera is drawing.
  25781. */
  25782. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25783. /**
  25784. * @hidden
  25785. * Defines the actions happening just before a rendering group is drawing.
  25786. */
  25787. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25788. /**
  25789. * @hidden
  25790. * Defines the actions happening just before a mesh is drawing.
  25791. */
  25792. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25793. /**
  25794. * @hidden
  25795. * Defines the actions happening just after a mesh has been drawn.
  25796. */
  25797. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25798. /**
  25799. * @hidden
  25800. * Defines the actions happening just after a rendering group has been drawn.
  25801. */
  25802. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25803. /**
  25804. * @hidden
  25805. * Defines the actions happening just after the active camera has been drawn.
  25806. */
  25807. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25808. /**
  25809. * @hidden
  25810. * Defines the actions happening just after rendering all cameras and computing intersections.
  25811. */
  25812. _this._afterRenderStage = BABYLON.Stage.Create();
  25813. /**
  25814. * @hidden
  25815. * Defines the actions happening when a pointer move event happens.
  25816. */
  25817. _this._pointerMoveStage = BABYLON.Stage.Create();
  25818. /**
  25819. * @hidden
  25820. * Defines the actions happening when a pointer down event happens.
  25821. */
  25822. _this._pointerDownStage = BABYLON.Stage.Create();
  25823. /**
  25824. * @hidden
  25825. * Defines the actions happening when a pointer up event happens.
  25826. */
  25827. _this._pointerUpStage = BABYLON.Stage.Create();
  25828. /**
  25829. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  25830. */
  25831. _this.geometriesById = null;
  25832. _this._defaultMeshCandidates = {
  25833. data: [],
  25834. length: 0
  25835. };
  25836. _this._defaultSubMeshCandidates = {
  25837. data: [],
  25838. length: 0
  25839. };
  25840. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  25841. _this._activeMeshesFrozen = false;
  25842. /** @hidden */
  25843. _this._allowPostProcessClearColor = true;
  25844. /**
  25845. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25846. */
  25847. _this.getDeterministicFrameTime = function () {
  25848. return 1000.0 / 60.0; // frame time in ms
  25849. };
  25850. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25851. _this._blockMaterialDirtyMechanism = false;
  25852. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25853. _this._engine.scenes.push(_this);
  25854. _this._uid = null;
  25855. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25856. if (BABYLON.PostProcessManager) {
  25857. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25858. }
  25859. if (BABYLON.Tools.IsWindowObjectExist()) {
  25860. _this.attachControl();
  25861. }
  25862. //collision coordinator initialization. For now legacy per default.
  25863. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25864. // Uniform Buffer
  25865. _this._createUbo();
  25866. // Default Image processing definition
  25867. if (BABYLON.ImageProcessingConfiguration) {
  25868. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25869. }
  25870. _this.setDefaultCandidateProviders();
  25871. if (options && options.useGeometryIdsMap === true) {
  25872. _this.geometriesById = {};
  25873. }
  25874. _this.useMaterialMeshMap = options && options.useGeometryIdsMap || false;
  25875. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  25876. return _this;
  25877. }
  25878. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25879. /**
  25880. * Texture used in all pbr material as the reflection texture.
  25881. * As in the majority of the scene they are the same (exception for multi room and so on),
  25882. * this is easier to reference from here than from all the materials.
  25883. */
  25884. get: function () {
  25885. return this._environmentTexture;
  25886. },
  25887. /**
  25888. * Texture used in all pbr material as the reflection texture.
  25889. * As in the majority of the scene they are the same (exception for multi room and so on),
  25890. * this is easier to set here than in all the materials.
  25891. */
  25892. set: function (value) {
  25893. if (this._environmentTexture === value) {
  25894. return;
  25895. }
  25896. this._environmentTexture = value;
  25897. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25898. },
  25899. enumerable: true,
  25900. configurable: true
  25901. });
  25902. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25903. /**
  25904. * Default image processing configuration used either in the rendering
  25905. * Forward main pass or through the imageProcessingPostProcess if present.
  25906. * As in the majority of the scene they are the same (exception for multi camera),
  25907. * this is easier to reference from here than from all the materials and post process.
  25908. *
  25909. * No setter as we it is a shared configuration, you can set the values instead.
  25910. */
  25911. get: function () {
  25912. return this._imageProcessingConfiguration;
  25913. },
  25914. enumerable: true,
  25915. configurable: true
  25916. });
  25917. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25918. get: function () {
  25919. return this._forceWireframe;
  25920. },
  25921. /**
  25922. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25923. */
  25924. set: function (value) {
  25925. if (this._forceWireframe === value) {
  25926. return;
  25927. }
  25928. this._forceWireframe = value;
  25929. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25935. get: function () {
  25936. return this._forcePointsCloud;
  25937. },
  25938. /**
  25939. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25940. */
  25941. set: function (value) {
  25942. if (this._forcePointsCloud === value) {
  25943. return;
  25944. }
  25945. this._forcePointsCloud = value;
  25946. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25947. },
  25948. enumerable: true,
  25949. configurable: true
  25950. });
  25951. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25952. /**
  25953. * Gets or sets the animation properties override
  25954. */
  25955. get: function () {
  25956. return this._animationPropertiesOverride;
  25957. },
  25958. set: function (value) {
  25959. this._animationPropertiesOverride = value;
  25960. },
  25961. enumerable: true,
  25962. configurable: true
  25963. });
  25964. Object.defineProperty(Scene.prototype, "onDispose", {
  25965. /** Sets a function to be executed when this scene is disposed. */
  25966. set: function (callback) {
  25967. if (this._onDisposeObserver) {
  25968. this.onDisposeObservable.remove(this._onDisposeObserver);
  25969. }
  25970. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25971. },
  25972. enumerable: true,
  25973. configurable: true
  25974. });
  25975. Object.defineProperty(Scene.prototype, "beforeRender", {
  25976. /** Sets a function to be executed before rendering this scene */
  25977. set: function (callback) {
  25978. if (this._onBeforeRenderObserver) {
  25979. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25980. }
  25981. if (callback) {
  25982. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25983. }
  25984. },
  25985. enumerable: true,
  25986. configurable: true
  25987. });
  25988. Object.defineProperty(Scene.prototype, "afterRender", {
  25989. /** Sets a function to be executed after rendering this scene */
  25990. set: function (callback) {
  25991. if (this._onAfterRenderObserver) {
  25992. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25993. }
  25994. if (callback) {
  25995. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25996. }
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  26002. /** Sets a function to be executed before rendering a camera*/
  26003. set: function (callback) {
  26004. if (this._onBeforeCameraRenderObserver) {
  26005. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  26006. }
  26007. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  26008. },
  26009. enumerable: true,
  26010. configurable: true
  26011. });
  26012. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  26013. /** Sets a function to be executed after rendering a camera*/
  26014. set: function (callback) {
  26015. if (this._onAfterCameraRenderObserver) {
  26016. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  26017. }
  26018. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  26024. /**
  26025. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  26026. */
  26027. get: function () {
  26028. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  26029. },
  26030. enumerable: true,
  26031. configurable: true
  26032. });
  26033. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  26034. get: function () {
  26035. return this._useRightHandedSystem;
  26036. },
  26037. /**
  26038. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26039. */
  26040. set: function (value) {
  26041. if (this._useRightHandedSystem === value) {
  26042. return;
  26043. }
  26044. this._useRightHandedSystem = value;
  26045. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26046. },
  26047. enumerable: true,
  26048. configurable: true
  26049. });
  26050. /**
  26051. * Sets the step Id used by deterministic lock step
  26052. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26053. * @param newStepId defines the step Id
  26054. */
  26055. Scene.prototype.setStepId = function (newStepId) {
  26056. this._currentStepId = newStepId;
  26057. };
  26058. /**
  26059. * Gets the step Id used by deterministic lock step
  26060. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26061. * @returns the step Id
  26062. */
  26063. Scene.prototype.getStepId = function () {
  26064. return this._currentStepId;
  26065. };
  26066. /**
  26067. * Gets the internal step used by deterministic lock step
  26068. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26069. * @returns the internal step
  26070. */
  26071. Scene.prototype.getInternalStep = function () {
  26072. return this._currentInternalStep;
  26073. };
  26074. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26075. get: function () {
  26076. return this._fogEnabled;
  26077. },
  26078. /**
  26079. * Gets or sets a boolean indicating if fog is enabled on this scene
  26080. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26081. * (Default is true)
  26082. */
  26083. set: function (value) {
  26084. if (this._fogEnabled === value) {
  26085. return;
  26086. }
  26087. this._fogEnabled = value;
  26088. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26089. },
  26090. enumerable: true,
  26091. configurable: true
  26092. });
  26093. Object.defineProperty(Scene.prototype, "fogMode", {
  26094. get: function () {
  26095. return this._fogMode;
  26096. },
  26097. /**
  26098. * Gets or sets the fog mode to use
  26099. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26100. * | mode | value |
  26101. * | --- | --- |
  26102. * | FOGMODE_NONE | 0 |
  26103. * | FOGMODE_EXP | 1 |
  26104. * | FOGMODE_EXP2 | 2 |
  26105. * | FOGMODE_LINEAR | 3 |
  26106. */
  26107. set: function (value) {
  26108. if (this._fogMode === value) {
  26109. return;
  26110. }
  26111. this._fogMode = value;
  26112. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26113. },
  26114. enumerable: true,
  26115. configurable: true
  26116. });
  26117. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26118. get: function () {
  26119. return this._shadowsEnabled;
  26120. },
  26121. /**
  26122. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26123. */
  26124. set: function (value) {
  26125. if (this._shadowsEnabled === value) {
  26126. return;
  26127. }
  26128. this._shadowsEnabled = value;
  26129. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26130. },
  26131. enumerable: true,
  26132. configurable: true
  26133. });
  26134. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26135. get: function () {
  26136. return this._lightsEnabled;
  26137. },
  26138. /**
  26139. * Gets or sets a boolean indicating if lights are enabled on this scene
  26140. */
  26141. set: function (value) {
  26142. if (this._lightsEnabled === value) {
  26143. return;
  26144. }
  26145. this._lightsEnabled = value;
  26146. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. Object.defineProperty(Scene.prototype, "activeCamera", {
  26152. /** Gets or sets the current active camera */
  26153. get: function () {
  26154. return this._activeCamera;
  26155. },
  26156. set: function (value) {
  26157. if (value === this._activeCamera) {
  26158. return;
  26159. }
  26160. this._activeCamera = value;
  26161. this.onActiveCameraChanged.notifyObservers(this);
  26162. },
  26163. enumerable: true,
  26164. configurable: true
  26165. });
  26166. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26167. /** The default material used on meshes when no material is affected */
  26168. get: function () {
  26169. if (!this._defaultMaterial) {
  26170. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26171. }
  26172. return this._defaultMaterial;
  26173. },
  26174. /** The default material used on meshes when no material is affected */
  26175. set: function (value) {
  26176. this._defaultMaterial = value;
  26177. },
  26178. enumerable: true,
  26179. configurable: true
  26180. });
  26181. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26182. get: function () {
  26183. return this._texturesEnabled;
  26184. },
  26185. /**
  26186. * Gets or sets a boolean indicating if textures are enabled on this scene
  26187. */
  26188. set: function (value) {
  26189. if (this._texturesEnabled === value) {
  26190. return;
  26191. }
  26192. this._texturesEnabled = value;
  26193. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26194. },
  26195. enumerable: true,
  26196. configurable: true
  26197. });
  26198. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26199. get: function () {
  26200. return this._skeletonsEnabled;
  26201. },
  26202. /**
  26203. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26204. */
  26205. set: function (value) {
  26206. if (this._skeletonsEnabled === value) {
  26207. return;
  26208. }
  26209. this._skeletonsEnabled = value;
  26210. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26211. },
  26212. enumerable: true,
  26213. configurable: true
  26214. });
  26215. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26216. /** @hidden */
  26217. get: function () {
  26218. return this._alternateRendering;
  26219. },
  26220. enumerable: true,
  26221. configurable: true
  26222. });
  26223. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26224. /**
  26225. * Gets the list of frustum planes (built from the active camera)
  26226. */
  26227. get: function () {
  26228. return this._frustumPlanes;
  26229. },
  26230. enumerable: true,
  26231. configurable: true
  26232. });
  26233. /**
  26234. * Registers the transient components if needed.
  26235. */
  26236. Scene.prototype._registerTransientComponents = function () {
  26237. // Register components that have been associated lately to the scene.
  26238. if (this._transientComponents.length > 0) {
  26239. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26240. var component = _a[_i];
  26241. component.register();
  26242. }
  26243. this._transientComponents = [];
  26244. }
  26245. };
  26246. /**
  26247. * @hidden
  26248. * Add a component to the scene.
  26249. * Note that the ccomponent could be registered on th next frame if this is called after
  26250. * the register component stage.
  26251. * @param component Defines the component to add to the scene
  26252. */
  26253. Scene.prototype._addComponent = function (component) {
  26254. this._components.push(component);
  26255. this._transientComponents.push(component);
  26256. var serializableComponent = component;
  26257. if (serializableComponent.addFromContainer) {
  26258. this._serializableComponents.push(serializableComponent);
  26259. }
  26260. };
  26261. /**
  26262. * @hidden
  26263. * Gets a component from the scene.
  26264. * @param name defines the name of the component to retrieve
  26265. * @returns the component or null if not present
  26266. */
  26267. Scene.prototype._getComponent = function (name) {
  26268. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26269. var component = _a[_i];
  26270. if (component.name === name) {
  26271. return component;
  26272. }
  26273. }
  26274. return null;
  26275. };
  26276. /**
  26277. * @hidden
  26278. */
  26279. Scene.prototype._getDefaultMeshCandidates = function () {
  26280. this._defaultMeshCandidates.data = this.meshes;
  26281. this._defaultMeshCandidates.length = this.meshes.length;
  26282. return this._defaultMeshCandidates;
  26283. };
  26284. /**
  26285. * @hidden
  26286. */
  26287. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26288. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26289. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26290. return this._defaultSubMeshCandidates;
  26291. };
  26292. /**
  26293. * Sets the default candidate providers for the scene.
  26294. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26295. * and getCollidingSubMeshCandidates to their default function
  26296. */
  26297. Scene.prototype.setDefaultCandidateProviders = function () {
  26298. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26299. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26300. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26301. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26302. };
  26303. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26304. /**
  26305. * Gets a boolean indicating if collisions are processed on a web worker
  26306. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26307. */
  26308. get: function () {
  26309. return this._workerCollisions;
  26310. },
  26311. set: function (enabled) {
  26312. if (!BABYLON.CollisionCoordinatorLegacy) {
  26313. return;
  26314. }
  26315. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26316. this._workerCollisions = enabled;
  26317. if (this.collisionCoordinator) {
  26318. this.collisionCoordinator.destroy();
  26319. }
  26320. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26321. this.collisionCoordinator.init(this);
  26322. },
  26323. enumerable: true,
  26324. configurable: true
  26325. });
  26326. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26327. /**
  26328. * Gets the mesh that is currently under the pointer
  26329. */
  26330. get: function () {
  26331. return this._pointerOverMesh;
  26332. },
  26333. enumerable: true,
  26334. configurable: true
  26335. });
  26336. Object.defineProperty(Scene.prototype, "pointerX", {
  26337. /**
  26338. * Gets the current on-screen X position of the pointer
  26339. */
  26340. get: function () {
  26341. return this._pointerX;
  26342. },
  26343. enumerable: true,
  26344. configurable: true
  26345. });
  26346. Object.defineProperty(Scene.prototype, "pointerY", {
  26347. /**
  26348. * Gets the current on-screen Y position of the pointer
  26349. */
  26350. get: function () {
  26351. return this._pointerY;
  26352. },
  26353. enumerable: true,
  26354. configurable: true
  26355. });
  26356. /**
  26357. * Gets the cached material (ie. the latest rendered one)
  26358. * @returns the cached material
  26359. */
  26360. Scene.prototype.getCachedMaterial = function () {
  26361. return this._cachedMaterial;
  26362. };
  26363. /**
  26364. * Gets the cached effect (ie. the latest rendered one)
  26365. * @returns the cached effect
  26366. */
  26367. Scene.prototype.getCachedEffect = function () {
  26368. return this._cachedEffect;
  26369. };
  26370. /**
  26371. * Gets the cached visibility state (ie. the latest rendered one)
  26372. * @returns the cached visibility state
  26373. */
  26374. Scene.prototype.getCachedVisibility = function () {
  26375. return this._cachedVisibility;
  26376. };
  26377. /**
  26378. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26379. * @param material defines the current material
  26380. * @param effect defines the current effect
  26381. * @param visibility defines the current visibility state
  26382. * @returns true if one parameter is not cached
  26383. */
  26384. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26385. if (visibility === void 0) { visibility = 1; }
  26386. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26387. };
  26388. /**
  26389. * Gets the engine associated with the scene
  26390. * @returns an Engine
  26391. */
  26392. Scene.prototype.getEngine = function () {
  26393. return this._engine;
  26394. };
  26395. /**
  26396. * Gets the total number of vertices rendered per frame
  26397. * @returns the total number of vertices rendered per frame
  26398. */
  26399. Scene.prototype.getTotalVertices = function () {
  26400. return this._totalVertices.current;
  26401. };
  26402. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26403. /**
  26404. * Gets the performance counter for total vertices
  26405. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26406. */
  26407. get: function () {
  26408. return this._totalVertices;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. /**
  26414. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26415. * @returns the total number of active indices rendered per frame
  26416. */
  26417. Scene.prototype.getActiveIndices = function () {
  26418. return this._activeIndices.current;
  26419. };
  26420. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26421. /**
  26422. * Gets the performance counter for active indices
  26423. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26424. */
  26425. get: function () {
  26426. return this._activeIndices;
  26427. },
  26428. enumerable: true,
  26429. configurable: true
  26430. });
  26431. /**
  26432. * Gets the total number of active particles rendered per frame
  26433. * @returns the total number of active particles rendered per frame
  26434. */
  26435. Scene.prototype.getActiveParticles = function () {
  26436. return this._activeParticles.current;
  26437. };
  26438. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26439. /**
  26440. * Gets the performance counter for active particles
  26441. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26442. */
  26443. get: function () {
  26444. return this._activeParticles;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. /**
  26450. * Gets the total number of active bones rendered per frame
  26451. * @returns the total number of active bones rendered per frame
  26452. */
  26453. Scene.prototype.getActiveBones = function () {
  26454. return this._activeBones.current;
  26455. };
  26456. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26457. /**
  26458. * Gets the performance counter for active bones
  26459. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26460. */
  26461. get: function () {
  26462. return this._activeBones;
  26463. },
  26464. enumerable: true,
  26465. configurable: true
  26466. });
  26467. /**
  26468. * Gets the array of active meshes
  26469. * @returns an array of AbstractMesh
  26470. */
  26471. Scene.prototype.getActiveMeshes = function () {
  26472. return this._activeMeshes;
  26473. };
  26474. /**
  26475. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26476. * @returns a number
  26477. */
  26478. Scene.prototype.getAnimationRatio = function () {
  26479. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26480. };
  26481. /**
  26482. * Gets an unique Id for the current render phase
  26483. * @returns a number
  26484. */
  26485. Scene.prototype.getRenderId = function () {
  26486. return this._renderId;
  26487. };
  26488. /**
  26489. * Gets an unique Id for the current frame
  26490. * @returns a number
  26491. */
  26492. Scene.prototype.getFrameId = function () {
  26493. return this._frameId;
  26494. };
  26495. /** Call this function if you want to manually increment the render Id*/
  26496. Scene.prototype.incrementRenderId = function () {
  26497. this._renderId++;
  26498. };
  26499. Scene.prototype._updatePointerPosition = function (evt) {
  26500. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26501. if (!canvasRect) {
  26502. return;
  26503. }
  26504. this._pointerX = evt.clientX - canvasRect.left;
  26505. this._pointerY = evt.clientY - canvasRect.top;
  26506. this._unTranslatedPointerX = this._pointerX;
  26507. this._unTranslatedPointerY = this._pointerY;
  26508. };
  26509. Scene.prototype._createUbo = function () {
  26510. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26511. this._sceneUbo.addUniform("viewProjection", 16);
  26512. this._sceneUbo.addUniform("view", 16);
  26513. };
  26514. Scene.prototype._createAlternateUbo = function () {
  26515. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26516. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26517. this._alternateSceneUbo.addUniform("view", 16);
  26518. };
  26519. // Pointers handling
  26520. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26521. if (pointerInfo.pickInfo) {
  26522. if (!pointerInfo.pickInfo.ray) {
  26523. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26524. }
  26525. }
  26526. };
  26527. /**
  26528. * Use this method to simulate a pointer move on a mesh
  26529. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26530. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26531. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26532. * @returns the current scene
  26533. */
  26534. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26535. var evt = new PointerEvent("pointermove", pointerEventInit);
  26536. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26537. return this;
  26538. }
  26539. return this._processPointerMove(pickResult, evt);
  26540. };
  26541. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26542. var canvas = this._engine.getRenderingCanvas();
  26543. if (!canvas) {
  26544. return this;
  26545. }
  26546. // Restore pointer
  26547. canvas.style.cursor = this.defaultCursor;
  26548. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26549. if (isMeshPicked) {
  26550. this.setPointerOverMesh(pickResult.pickedMesh);
  26551. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26552. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26553. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26554. }
  26555. else {
  26556. canvas.style.cursor = this.hoverCursor;
  26557. }
  26558. }
  26559. }
  26560. else {
  26561. this.setPointerOverMesh(null);
  26562. }
  26563. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26564. var step = _a[_i];
  26565. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26566. }
  26567. if (pickResult) {
  26568. var type = evt.type === this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26569. if (this.onPointerMove) {
  26570. this.onPointerMove(evt, pickResult, type);
  26571. }
  26572. if (this.onPointerObservable.hasObservers()) {
  26573. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26574. this._setRayOnPointerInfo(pi);
  26575. this.onPointerObservable.notifyObservers(pi, type);
  26576. }
  26577. }
  26578. return this;
  26579. };
  26580. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26581. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26582. if (pickResult) {
  26583. pi.ray = pickResult.ray;
  26584. }
  26585. this.onPrePointerObservable.notifyObservers(pi, type);
  26586. if (pi.skipOnPointerObservable) {
  26587. return true;
  26588. }
  26589. else {
  26590. return false;
  26591. }
  26592. };
  26593. /**
  26594. * Use this method to simulate a pointer down on a mesh
  26595. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26596. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26597. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26598. * @returns the current scene
  26599. */
  26600. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26601. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26602. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26603. return this;
  26604. }
  26605. return this._processPointerDown(pickResult, evt);
  26606. };
  26607. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26608. var _this = this;
  26609. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26610. this._pickedDownMesh = pickResult.pickedMesh;
  26611. var actionManager = pickResult.pickedMesh.actionManager;
  26612. if (actionManager) {
  26613. if (actionManager.hasPickTriggers) {
  26614. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26615. switch (evt.button) {
  26616. case 0:
  26617. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26618. break;
  26619. case 1:
  26620. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26621. break;
  26622. case 2:
  26623. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26624. break;
  26625. }
  26626. }
  26627. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26628. window.setTimeout(function () {
  26629. 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);
  26630. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26631. if (_this._totalPointersPressed !== 0 &&
  26632. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26633. !_this._isPointerSwiping()) {
  26634. _this._startingPointerTime = 0;
  26635. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26636. }
  26637. }
  26638. }, Scene.LongPressDelay);
  26639. }
  26640. }
  26641. }
  26642. else {
  26643. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26644. var step = _a[_i];
  26645. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26646. }
  26647. }
  26648. if (pickResult) {
  26649. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26650. if (this.onPointerDown) {
  26651. this.onPointerDown(evt, pickResult, type);
  26652. }
  26653. if (this.onPointerObservable.hasObservers()) {
  26654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26655. this._setRayOnPointerInfo(pi);
  26656. this.onPointerObservable.notifyObservers(pi, type);
  26657. }
  26658. }
  26659. return this;
  26660. };
  26661. /**
  26662. * Use this method to simulate a pointer up on a mesh
  26663. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26664. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26665. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26666. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  26667. * @returns the current scene
  26668. */
  26669. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) {
  26670. var evt = new PointerEvent("pointerup", pointerEventInit);
  26671. var clickInfo = new ClickInfo();
  26672. if (doubleTap) {
  26673. clickInfo.doubleClick = true;
  26674. }
  26675. else {
  26676. clickInfo.singleClick = true;
  26677. }
  26678. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26679. return this;
  26680. }
  26681. return this._processPointerUp(pickResult, evt, clickInfo);
  26682. };
  26683. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26684. if (pickResult && pickResult && pickResult.pickedMesh) {
  26685. this._pickedUpMesh = pickResult.pickedMesh;
  26686. if (this._pickedDownMesh === this._pickedUpMesh) {
  26687. if (this.onPointerPick) {
  26688. this.onPointerPick(evt, pickResult);
  26689. }
  26690. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26691. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26692. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26693. this._setRayOnPointerInfo(pi);
  26694. this.onPointerObservable.notifyObservers(pi, type_1);
  26695. }
  26696. }
  26697. if (pickResult.pickedMesh.actionManager) {
  26698. if (clickInfo.ignore) {
  26699. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26700. }
  26701. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26702. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26703. }
  26704. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26705. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26706. }
  26707. }
  26708. }
  26709. else {
  26710. if (!clickInfo.ignore) {
  26711. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26712. var step = _a[_i];
  26713. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26714. }
  26715. }
  26716. }
  26717. if (this._pickedDownMesh &&
  26718. this._pickedDownMesh.actionManager &&
  26719. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26720. this._pickedDownMesh !== this._pickedUpMesh) {
  26721. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26722. }
  26723. var type = 0;
  26724. if (this.onPointerObservable.hasObservers()) {
  26725. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  26726. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26727. type = BABYLON.PointerEventTypes.POINTERTAP;
  26728. }
  26729. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26730. type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26731. }
  26732. if (type) {
  26733. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26734. this._setRayOnPointerInfo(pi);
  26735. this.onPointerObservable.notifyObservers(pi, type);
  26736. }
  26737. }
  26738. if (!clickInfo.ignore) {
  26739. type = BABYLON.PointerEventTypes.POINTERUP;
  26740. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26741. this._setRayOnPointerInfo(pi);
  26742. this.onPointerObservable.notifyObservers(pi, type);
  26743. }
  26744. }
  26745. if (this.onPointerUp && !clickInfo.ignore) {
  26746. this.onPointerUp(evt, pickResult, type);
  26747. }
  26748. return this;
  26749. };
  26750. /**
  26751. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26752. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26753. * @returns true if the pointer was captured
  26754. */
  26755. Scene.prototype.isPointerCaptured = function (pointerId) {
  26756. if (pointerId === void 0) { pointerId = 0; }
  26757. return this._pointerCaptures[pointerId];
  26758. };
  26759. /** @hidden */
  26760. Scene.prototype._isPointerSwiping = function () {
  26761. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26762. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26763. };
  26764. /**
  26765. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26766. * @param attachUp defines if you want to attach events to pointerup
  26767. * @param attachDown defines if you want to attach events to pointerdown
  26768. * @param attachMove defines if you want to attach events to pointermove
  26769. */
  26770. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26771. var _this = this;
  26772. if (attachUp === void 0) { attachUp = true; }
  26773. if (attachDown === void 0) { attachDown = true; }
  26774. if (attachMove === void 0) { attachMove = true; }
  26775. this._initActionManager = function (act, clickInfo) {
  26776. if (!_this._meshPickProceed) {
  26777. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26778. _this._currentPickResult = pickResult;
  26779. if (pickResult) {
  26780. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26781. }
  26782. _this._meshPickProceed = true;
  26783. }
  26784. return act;
  26785. };
  26786. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26787. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26788. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26789. btn !== _this._previousButtonPressed) {
  26790. _this._doubleClickOccured = false;
  26791. clickInfo.singleClick = true;
  26792. clickInfo.ignore = false;
  26793. cb(clickInfo, _this._currentPickResult);
  26794. }
  26795. };
  26796. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26797. var clickInfo = new ClickInfo();
  26798. _this._currentPickResult = null;
  26799. var act = null;
  26800. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26801. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26802. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26803. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26804. act = _this._initActionManager(act, clickInfo);
  26805. if (act) {
  26806. checkPicking = act.hasPickTriggers;
  26807. }
  26808. }
  26809. var needToIgnoreNext = false;
  26810. if (checkPicking) {
  26811. var btn = evt.button;
  26812. clickInfo.hasSwiped = _this._isPointerSwiping();
  26813. if (!clickInfo.hasSwiped) {
  26814. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26815. if (!checkSingleClickImmediately) {
  26816. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26817. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26818. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26819. act = _this._initActionManager(act, clickInfo);
  26820. if (act) {
  26821. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26822. }
  26823. }
  26824. }
  26825. if (checkSingleClickImmediately) {
  26826. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26827. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26828. btn !== _this._previousButtonPressed) {
  26829. clickInfo.singleClick = true;
  26830. cb(clickInfo, _this._currentPickResult);
  26831. needToIgnoreNext = true;
  26832. }
  26833. }
  26834. // at least one double click is required to be check and exclusive double click is enabled
  26835. else {
  26836. // wait that no double click has been raised during the double click delay
  26837. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26838. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26839. }
  26840. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26841. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26842. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26843. act = _this._initActionManager(act, clickInfo);
  26844. if (act) {
  26845. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26846. }
  26847. }
  26848. if (checkDoubleClick) {
  26849. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26850. if (btn === _this._previousButtonPressed &&
  26851. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26852. !_this._doubleClickOccured) {
  26853. // pointer has not moved for 2 clicks, it's a double click
  26854. if (!clickInfo.hasSwiped &&
  26855. !_this._isPointerSwiping()) {
  26856. _this._previousStartingPointerTime = 0;
  26857. _this._doubleClickOccured = true;
  26858. clickInfo.doubleClick = true;
  26859. clickInfo.ignore = false;
  26860. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26861. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26862. }
  26863. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26864. cb(clickInfo, _this._currentPickResult);
  26865. }
  26866. // if the two successive clicks are too far, it's just two simple clicks
  26867. else {
  26868. _this._doubleClickOccured = false;
  26869. _this._previousStartingPointerTime = _this._startingPointerTime;
  26870. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26871. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26872. _this._previousButtonPressed = btn;
  26873. if (Scene.ExclusiveDoubleClickMode) {
  26874. if (_this._previousDelayedSimpleClickTimeout) {
  26875. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26876. }
  26877. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26878. cb(clickInfo, _this._previousPickResult);
  26879. }
  26880. else {
  26881. cb(clickInfo, _this._currentPickResult);
  26882. }
  26883. }
  26884. needToIgnoreNext = true;
  26885. }
  26886. // just the first click of the double has been raised
  26887. else {
  26888. _this._doubleClickOccured = false;
  26889. _this._previousStartingPointerTime = _this._startingPointerTime;
  26890. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26891. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26892. _this._previousButtonPressed = btn;
  26893. }
  26894. }
  26895. }
  26896. }
  26897. if (!needToIgnoreNext) {
  26898. cb(clickInfo, _this._currentPickResult);
  26899. }
  26900. };
  26901. this._onPointerMove = function (evt) {
  26902. _this._updatePointerPosition(evt);
  26903. // PreObservable support
  26904. if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26905. return;
  26906. }
  26907. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26908. return;
  26909. }
  26910. if (!_this.pointerMovePredicate) {
  26911. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26912. }
  26913. // Meshes
  26914. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26915. _this._processPointerMove(pickResult, evt);
  26916. };
  26917. this._onPointerDown = function (evt) {
  26918. _this._totalPointersPressed++;
  26919. _this._pickedDownMesh = null;
  26920. _this._meshPickProceed = false;
  26921. _this._updatePointerPosition(evt);
  26922. if (_this.preventDefaultOnPointerDown && canvas) {
  26923. evt.preventDefault();
  26924. canvas.focus();
  26925. }
  26926. _this._startingPointerPosition.x = _this._pointerX;
  26927. _this._startingPointerPosition.y = _this._pointerY;
  26928. _this._startingPointerTime = Date.now();
  26929. // PreObservable support
  26930. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26931. return;
  26932. }
  26933. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26934. return;
  26935. }
  26936. _this._pointerCaptures[evt.pointerId] = true;
  26937. if (!_this.pointerDownPredicate) {
  26938. _this.pointerDownPredicate = function (mesh) {
  26939. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26940. };
  26941. }
  26942. // Meshes
  26943. _this._pickedDownMesh = null;
  26944. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26945. _this._processPointerDown(pickResult, evt);
  26946. };
  26947. this._onPointerUp = function (evt) {
  26948. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26949. return; // So we need to test it the pointer down was pressed before.
  26950. }
  26951. _this._totalPointersPressed--;
  26952. _this._pickedUpMesh = null;
  26953. _this._meshPickProceed = false;
  26954. _this._updatePointerPosition(evt);
  26955. if (_this.preventDefaultOnPointerUp && canvas) {
  26956. evt.preventDefault();
  26957. canvas.focus();
  26958. }
  26959. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26960. _this._pointerCaptures[evt.pointerId] = false;
  26961. // PreObservable support
  26962. if (_this.onPrePointerObservable.hasObservers()) {
  26963. if (!clickInfo.ignore) {
  26964. if (!clickInfo.hasSwiped) {
  26965. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26966. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26967. return;
  26968. }
  26969. }
  26970. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26971. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26972. return;
  26973. }
  26974. }
  26975. }
  26976. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26977. return;
  26978. }
  26979. }
  26980. }
  26981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26982. return;
  26983. }
  26984. if (!_this.pointerUpPredicate) {
  26985. _this.pointerUpPredicate = function (mesh) {
  26986. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26987. };
  26988. }
  26989. // Meshes
  26990. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26991. _this._initActionManager(null, clickInfo);
  26992. }
  26993. if (!pickResult) {
  26994. pickResult = _this._currentPickResult;
  26995. }
  26996. _this._processPointerUp(pickResult, evt, clickInfo);
  26997. _this._previousPickResult = _this._currentPickResult;
  26998. });
  26999. };
  27000. this._onKeyDown = function (evt) {
  27001. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  27002. if (_this.onPreKeyboardObservable.hasObservers()) {
  27003. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27004. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27005. if (pi.skipOnPointerObservable) {
  27006. return;
  27007. }
  27008. }
  27009. if (_this.onKeyboardObservable.hasObservers()) {
  27010. var pi = new BABYLON.KeyboardInfo(type, evt);
  27011. _this.onKeyboardObservable.notifyObservers(pi, type);
  27012. }
  27013. if (_this.actionManager) {
  27014. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27015. }
  27016. };
  27017. this._onKeyUp = function (evt) {
  27018. var type = BABYLON.KeyboardEventTypes.KEYUP;
  27019. if (_this.onPreKeyboardObservable.hasObservers()) {
  27020. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27021. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27022. if (pi.skipOnPointerObservable) {
  27023. return;
  27024. }
  27025. }
  27026. if (_this.onKeyboardObservable.hasObservers()) {
  27027. var pi = new BABYLON.KeyboardInfo(type, evt);
  27028. _this.onKeyboardObservable.notifyObservers(pi, type);
  27029. }
  27030. if (_this.actionManager) {
  27031. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27032. }
  27033. };
  27034. var engine = this.getEngine();
  27035. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  27036. if (!canvas) {
  27037. return;
  27038. }
  27039. canvas.addEventListener("keydown", _this._onKeyDown, false);
  27040. canvas.addEventListener("keyup", _this._onKeyUp, false);
  27041. });
  27042. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  27043. if (!canvas) {
  27044. return;
  27045. }
  27046. canvas.removeEventListener("keydown", _this._onKeyDown);
  27047. canvas.removeEventListener("keyup", _this._onKeyUp);
  27048. });
  27049. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27050. var canvas = this._engine.getRenderingCanvas();
  27051. if (!canvas) {
  27052. return;
  27053. }
  27054. if (attachMove) {
  27055. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27056. // Wheel
  27057. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  27058. document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  27059. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  27060. canvas.addEventListener(this._wheelEventName, this._onPointerMove, false);
  27061. }
  27062. if (attachDown) {
  27063. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27064. }
  27065. if (attachUp) {
  27066. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27067. }
  27068. canvas.tabIndex = 1;
  27069. };
  27070. /** Detaches all event handlers*/
  27071. Scene.prototype.detachControl = function () {
  27072. var engine = this.getEngine();
  27073. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27074. var canvas = engine.getRenderingCanvas();
  27075. if (!canvas) {
  27076. return;
  27077. }
  27078. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27079. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27080. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27081. if (this._onCanvasBlurObserver) {
  27082. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27083. }
  27084. if (this._onCanvasFocusObserver) {
  27085. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27086. }
  27087. // Wheel
  27088. canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
  27089. // Keyboard
  27090. canvas.removeEventListener("keydown", this._onKeyDown);
  27091. canvas.removeEventListener("keyup", this._onKeyUp);
  27092. // Observables
  27093. this.onKeyboardObservable.clear();
  27094. this.onPreKeyboardObservable.clear();
  27095. this.onPointerObservable.clear();
  27096. this.onPrePointerObservable.clear();
  27097. };
  27098. /**
  27099. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27100. * Delay loaded resources are not taking in account
  27101. * @return true if all required resources are ready
  27102. */
  27103. Scene.prototype.isReady = function () {
  27104. if (this._isDisposed) {
  27105. return false;
  27106. }
  27107. var index;
  27108. var engine = this.getEngine();
  27109. // Effects
  27110. if (!engine.areAllEffectsReady()) {
  27111. return false;
  27112. }
  27113. // Pending data
  27114. if (this._pendingData.length > 0) {
  27115. return false;
  27116. }
  27117. // Meshes
  27118. for (index = 0; index < this.meshes.length; index++) {
  27119. var mesh = this.meshes[index];
  27120. if (!mesh.isEnabled()) {
  27121. continue;
  27122. }
  27123. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27124. continue;
  27125. }
  27126. if (!mesh.isReady(true)) {
  27127. return false;
  27128. }
  27129. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27130. // Is Ready For Mesh
  27131. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27132. var step = _a[_i];
  27133. if (!step.action(mesh, hardwareInstancedRendering)) {
  27134. return false;
  27135. }
  27136. }
  27137. }
  27138. // Geometries
  27139. for (index = 0; index < this.geometries.length; index++) {
  27140. var geometry = this.geometries[index];
  27141. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27142. return false;
  27143. }
  27144. }
  27145. // Post-processes
  27146. if (this.activeCameras && this.activeCameras.length > 0) {
  27147. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27148. var camera = _c[_b];
  27149. if (!camera.isReady(true)) {
  27150. return false;
  27151. }
  27152. }
  27153. }
  27154. else if (this.activeCamera) {
  27155. if (!this.activeCamera.isReady(true)) {
  27156. return false;
  27157. }
  27158. }
  27159. // Particles
  27160. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27161. var particleSystem = _e[_d];
  27162. if (!particleSystem.isReady()) {
  27163. return false;
  27164. }
  27165. }
  27166. return true;
  27167. };
  27168. /** Resets all cached information relative to material (including effect and visibility) */
  27169. Scene.prototype.resetCachedMaterial = function () {
  27170. this._cachedMaterial = null;
  27171. this._cachedEffect = null;
  27172. this._cachedVisibility = null;
  27173. };
  27174. /**
  27175. * Registers a function to be called before every frame render
  27176. * @param func defines the function to register
  27177. */
  27178. Scene.prototype.registerBeforeRender = function (func) {
  27179. this.onBeforeRenderObservable.add(func);
  27180. };
  27181. /**
  27182. * Unregisters a function called before every frame render
  27183. * @param func defines the function to unregister
  27184. */
  27185. Scene.prototype.unregisterBeforeRender = function (func) {
  27186. this.onBeforeRenderObservable.removeCallback(func);
  27187. };
  27188. /**
  27189. * Registers a function to be called after every frame render
  27190. * @param func defines the function to register
  27191. */
  27192. Scene.prototype.registerAfterRender = function (func) {
  27193. this.onAfterRenderObservable.add(func);
  27194. };
  27195. /**
  27196. * Unregisters a function called after every frame render
  27197. * @param func defines the function to unregister
  27198. */
  27199. Scene.prototype.unregisterAfterRender = function (func) {
  27200. this.onAfterRenderObservable.removeCallback(func);
  27201. };
  27202. Scene.prototype._executeOnceBeforeRender = function (func) {
  27203. var _this = this;
  27204. var execFunc = function () {
  27205. func();
  27206. setTimeout(function () {
  27207. _this.unregisterBeforeRender(execFunc);
  27208. });
  27209. };
  27210. this.registerBeforeRender(execFunc);
  27211. };
  27212. /**
  27213. * The provided function will run before render once and will be disposed afterwards.
  27214. * A timeout delay can be provided so that the function will be executed in N ms.
  27215. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27216. * @param func The function to be executed.
  27217. * @param timeout optional delay in ms
  27218. */
  27219. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27220. var _this = this;
  27221. if (timeout !== undefined) {
  27222. setTimeout(function () {
  27223. _this._executeOnceBeforeRender(func);
  27224. }, timeout);
  27225. }
  27226. else {
  27227. this._executeOnceBeforeRender(func);
  27228. }
  27229. };
  27230. /** @hidden */
  27231. Scene.prototype._addPendingData = function (data) {
  27232. this._pendingData.push(data);
  27233. };
  27234. /** @hidden */
  27235. Scene.prototype._removePendingData = function (data) {
  27236. var wasLoading = this.isLoading;
  27237. var index = this._pendingData.indexOf(data);
  27238. if (index !== -1) {
  27239. this._pendingData.splice(index, 1);
  27240. }
  27241. if (wasLoading && !this.isLoading) {
  27242. this.onDataLoadedObservable.notifyObservers(this);
  27243. }
  27244. };
  27245. /**
  27246. * Returns the number of items waiting to be loaded
  27247. * @returns the number of items waiting to be loaded
  27248. */
  27249. Scene.prototype.getWaitingItemsCount = function () {
  27250. return this._pendingData.length;
  27251. };
  27252. Object.defineProperty(Scene.prototype, "isLoading", {
  27253. /**
  27254. * Returns a boolean indicating if the scene is still loading data
  27255. */
  27256. get: function () {
  27257. return this._pendingData.length > 0;
  27258. },
  27259. enumerable: true,
  27260. configurable: true
  27261. });
  27262. /**
  27263. * Registers a function to be executed when the scene is ready
  27264. * @param {Function} func - the function to be executed
  27265. */
  27266. Scene.prototype.executeWhenReady = function (func) {
  27267. var _this = this;
  27268. this.onReadyObservable.add(func);
  27269. if (this._executeWhenReadyTimeoutId !== -1) {
  27270. return;
  27271. }
  27272. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27273. _this._checkIsReady();
  27274. }, 150);
  27275. };
  27276. /**
  27277. * Returns a promise that resolves when the scene is ready
  27278. * @returns A promise that resolves when the scene is ready
  27279. */
  27280. Scene.prototype.whenReadyAsync = function () {
  27281. var _this = this;
  27282. return new Promise(function (resolve) {
  27283. _this.executeWhenReady(function () {
  27284. resolve();
  27285. });
  27286. });
  27287. };
  27288. /** @hidden */
  27289. Scene.prototype._checkIsReady = function () {
  27290. var _this = this;
  27291. this._registerTransientComponents();
  27292. if (this.isReady()) {
  27293. this.onReadyObservable.notifyObservers(this);
  27294. this.onReadyObservable.clear();
  27295. this._executeWhenReadyTimeoutId = -1;
  27296. return;
  27297. }
  27298. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27299. _this._checkIsReady();
  27300. }, 150);
  27301. };
  27302. // Animations
  27303. /**
  27304. * Will start the animation sequence of a given target
  27305. * @param target defines the target
  27306. * @param from defines from which frame should animation start
  27307. * @param to defines until which frame should animation run.
  27308. * @param weight defines the weight to apply to the animation (1.0 by default)
  27309. * @param loop defines if the animation loops
  27310. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27311. * @param onAnimationEnd defines the function to be executed when the animation ends
  27312. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27313. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27314. * @returns the animatable object created for this animation
  27315. */
  27316. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27317. if (weight === void 0) { weight = 1.0; }
  27318. if (speedRatio === void 0) { speedRatio = 1.0; }
  27319. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27320. returnedAnimatable.weight = weight;
  27321. return returnedAnimatable;
  27322. };
  27323. /**
  27324. * Will start the animation sequence of a given target
  27325. * @param target defines the target
  27326. * @param from defines from which frame should animation start
  27327. * @param to defines until which frame should animation run.
  27328. * @param loop defines if the animation loops
  27329. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27330. * @param onAnimationEnd defines the function to be executed when the animation ends
  27331. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27332. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27333. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27334. * @returns the animatable object created for this animation
  27335. */
  27336. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27337. if (speedRatio === void 0) { speedRatio = 1.0; }
  27338. if (stopCurrent === void 0) { stopCurrent = true; }
  27339. if (from > to && speedRatio > 0) {
  27340. speedRatio *= -1;
  27341. }
  27342. if (stopCurrent) {
  27343. this.stopAnimation(target, undefined, targetMask);
  27344. }
  27345. if (!animatable) {
  27346. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27347. }
  27348. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27349. // Local animations
  27350. if (target.animations && shouldRunTargetAnimations) {
  27351. animatable.appendAnimations(target, target.animations);
  27352. }
  27353. // Children animations
  27354. if (target.getAnimatables) {
  27355. var animatables = target.getAnimatables();
  27356. for (var index = 0; index < animatables.length; index++) {
  27357. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27358. }
  27359. }
  27360. animatable.reset();
  27361. return animatable;
  27362. };
  27363. /**
  27364. * Begin a new animation on a given node
  27365. * @param target defines the target where the animation will take place
  27366. * @param animations defines the list of animations to start
  27367. * @param from defines the initial value
  27368. * @param to defines the final value
  27369. * @param loop defines if you want animation to loop (off by default)
  27370. * @param speedRatio defines the speed ratio to apply to all animations
  27371. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27372. * @returns the list of created animatables
  27373. */
  27374. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27375. if (speedRatio === undefined) {
  27376. speedRatio = 1.0;
  27377. }
  27378. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27379. return animatable;
  27380. };
  27381. /**
  27382. * Begin a new animation on a given node and its hierarchy
  27383. * @param target defines the root node where the animation will take place
  27384. * @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.
  27385. * @param animations defines the list of animations to start
  27386. * @param from defines the initial value
  27387. * @param to defines the final value
  27388. * @param loop defines if you want animation to loop (off by default)
  27389. * @param speedRatio defines the speed ratio to apply to all animations
  27390. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27391. * @returns the list of animatables created for all nodes
  27392. */
  27393. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27394. var children = target.getDescendants(directDescendantsOnly);
  27395. var result = [];
  27396. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27397. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27398. var child = children_1[_i];
  27399. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27400. }
  27401. return result;
  27402. };
  27403. /**
  27404. * Gets the animatable associated with a specific target
  27405. * @param target defines the target of the animatable
  27406. * @returns the required animatable if found
  27407. */
  27408. Scene.prototype.getAnimatableByTarget = function (target) {
  27409. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27410. if (this._activeAnimatables[index].target === target) {
  27411. return this._activeAnimatables[index];
  27412. }
  27413. }
  27414. return null;
  27415. };
  27416. /**
  27417. * Gets all animatables associated with a given target
  27418. * @param target defines the target to look animatables for
  27419. * @returns an array of Animatables
  27420. */
  27421. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27422. var result = [];
  27423. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27424. if (this._activeAnimatables[index].target === target) {
  27425. result.push(this._activeAnimatables[index]);
  27426. }
  27427. }
  27428. return result;
  27429. };
  27430. Object.defineProperty(Scene.prototype, "animatables", {
  27431. /**
  27432. * Gets all animatable attached to the scene
  27433. */
  27434. get: function () {
  27435. return this._activeAnimatables;
  27436. },
  27437. enumerable: true,
  27438. configurable: true
  27439. });
  27440. /**
  27441. * Will stop the animation of the given target
  27442. * @param target - the target
  27443. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27444. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  27445. */
  27446. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27447. var animatables = this.getAllAnimatablesByTarget(target);
  27448. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27449. var animatable = animatables_1[_i];
  27450. animatable.stop(animationName, targetMask);
  27451. }
  27452. };
  27453. /**
  27454. * Stops and removes all animations that have been applied to the scene
  27455. */
  27456. Scene.prototype.stopAllAnimations = function () {
  27457. if (this._activeAnimatables) {
  27458. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27459. this._activeAnimatables[i].stop();
  27460. }
  27461. this._activeAnimatables = [];
  27462. }
  27463. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27464. var group = _a[_i];
  27465. group.stop();
  27466. }
  27467. };
  27468. Scene.prototype._animate = function () {
  27469. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27470. return;
  27471. }
  27472. // Getting time
  27473. var now = BABYLON.Tools.Now;
  27474. if (!this._animationTimeLast) {
  27475. if (this._pendingData.length > 0) {
  27476. return;
  27477. }
  27478. this._animationTimeLast = now;
  27479. }
  27480. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27481. this._animationTime += deltaTime;
  27482. this._animationTimeLast = now;
  27483. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27484. this._activeAnimatables[index]._animate(this._animationTime);
  27485. }
  27486. // Late animation bindings
  27487. this._processLateAnimationBindings();
  27488. };
  27489. /** @hidden */
  27490. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27491. var target = runtimeAnimation.target;
  27492. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27493. if (!target._lateAnimationHolders) {
  27494. target._lateAnimationHolders = {};
  27495. }
  27496. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27497. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27498. totalWeight: 0,
  27499. animations: [],
  27500. originalValue: originalValue
  27501. };
  27502. }
  27503. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27504. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27505. };
  27506. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27507. var normalizer = 1.0;
  27508. var finalPosition = BABYLON.Tmp.Vector3[0];
  27509. var finalScaling = BABYLON.Tmp.Vector3[1];
  27510. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27511. var startIndex = 0;
  27512. var originalAnimation = holder.animations[0];
  27513. var originalValue = holder.originalValue;
  27514. var scale = 1;
  27515. if (holder.totalWeight < 1.0) {
  27516. // We need to mix the original value in
  27517. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27518. scale = 1.0 - holder.totalWeight;
  27519. }
  27520. else {
  27521. startIndex = 1;
  27522. // We need to normalize the weights
  27523. normalizer = holder.totalWeight;
  27524. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27525. scale = originalAnimation.weight / normalizer;
  27526. if (scale == 1) {
  27527. return originalAnimation.currentValue;
  27528. }
  27529. }
  27530. finalScaling.scaleInPlace(scale);
  27531. finalPosition.scaleInPlace(scale);
  27532. finalQuaternion.scaleInPlace(scale);
  27533. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27534. var runtimeAnimation = holder.animations[animIndex];
  27535. var scale = runtimeAnimation.weight / normalizer;
  27536. var currentPosition = BABYLON.Tmp.Vector3[2];
  27537. var currentScaling = BABYLON.Tmp.Vector3[3];
  27538. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27539. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27540. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27541. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27542. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27543. }
  27544. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27545. return originalAnimation._workValue;
  27546. };
  27547. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27548. var originalAnimation = holder.animations[0];
  27549. var originalValue = holder.originalValue;
  27550. if (holder.animations.length === 1) {
  27551. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27552. return refQuaternion;
  27553. }
  27554. var normalizer = 1.0;
  27555. var quaternions;
  27556. var weights;
  27557. if (holder.totalWeight < 1.0) {
  27558. var scale = 1.0 - holder.totalWeight;
  27559. quaternions = [];
  27560. weights = [];
  27561. quaternions.push(originalValue);
  27562. weights.push(scale);
  27563. }
  27564. else {
  27565. if (holder.animations.length === 2) { // Slerp as soon as we can
  27566. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27567. return refQuaternion;
  27568. }
  27569. quaternions = [];
  27570. weights = [];
  27571. normalizer = holder.totalWeight;
  27572. }
  27573. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27574. var runtimeAnimation = holder.animations[animIndex];
  27575. quaternions.push(runtimeAnimation.currentValue);
  27576. weights.push(runtimeAnimation.weight / normalizer);
  27577. }
  27578. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27579. var cumulativeAmount = 0;
  27580. var cumulativeQuaternion = null;
  27581. for (var index = 0; index < quaternions.length;) {
  27582. if (!cumulativeQuaternion) {
  27583. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27584. cumulativeQuaternion = refQuaternion;
  27585. cumulativeAmount = weights[index] + weights[index + 1];
  27586. index += 2;
  27587. continue;
  27588. }
  27589. cumulativeAmount += weights[index];
  27590. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27591. index++;
  27592. }
  27593. return cumulativeQuaternion;
  27594. };
  27595. Scene.prototype._processLateAnimationBindings = function () {
  27596. if (!this._registeredForLateAnimationBindings.length) {
  27597. return;
  27598. }
  27599. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27600. var target = this._registeredForLateAnimationBindings.data[index];
  27601. for (var path in target._lateAnimationHolders) {
  27602. var holder = target._lateAnimationHolders[path];
  27603. var originalAnimation = holder.animations[0];
  27604. var originalValue = holder.originalValue;
  27605. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27606. var finalValue = target[path];
  27607. if (matrixDecomposeMode) {
  27608. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27609. }
  27610. else {
  27611. var quaternionMode = originalValue.w !== undefined;
  27612. if (quaternionMode) {
  27613. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27614. }
  27615. else {
  27616. var startIndex = 0;
  27617. var normalizer = 1.0;
  27618. if (holder.totalWeight < 1.0) {
  27619. // We need to mix the original value in
  27620. if (originalValue.scale) {
  27621. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27622. }
  27623. else {
  27624. finalValue = originalValue * (1.0 - holder.totalWeight);
  27625. }
  27626. }
  27627. else {
  27628. // We need to normalize the weights
  27629. normalizer = holder.totalWeight;
  27630. var scale_1 = originalAnimation.weight / normalizer;
  27631. if (scale_1 !== 1) {
  27632. if (originalAnimation.currentValue.scale) {
  27633. finalValue = originalAnimation.currentValue.scale(scale_1);
  27634. }
  27635. else {
  27636. finalValue = originalAnimation.currentValue * scale_1;
  27637. }
  27638. }
  27639. else {
  27640. finalValue = originalAnimation.currentValue;
  27641. }
  27642. startIndex = 1;
  27643. }
  27644. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27645. var runtimeAnimation = holder.animations[animIndex];
  27646. var scale = runtimeAnimation.weight / normalizer;
  27647. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27648. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27649. }
  27650. else {
  27651. finalValue += runtimeAnimation.currentValue * scale;
  27652. }
  27653. }
  27654. }
  27655. }
  27656. target[path] = finalValue;
  27657. }
  27658. target._lateAnimationHolders = {};
  27659. }
  27660. this._registeredForLateAnimationBindings.reset();
  27661. };
  27662. // Matrix
  27663. /** @hidden */
  27664. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27665. this._useAlternateCameraConfiguration = active;
  27666. };
  27667. /**
  27668. * Gets the current view matrix
  27669. * @returns a Matrix
  27670. */
  27671. Scene.prototype.getViewMatrix = function () {
  27672. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27673. };
  27674. /**
  27675. * Gets the current projection matrix
  27676. * @returns a Matrix
  27677. */
  27678. Scene.prototype.getProjectionMatrix = function () {
  27679. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27680. };
  27681. /**
  27682. * Gets the current transform matrix
  27683. * @returns a Matrix made of View * Projection
  27684. */
  27685. Scene.prototype.getTransformMatrix = function () {
  27686. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27687. };
  27688. /**
  27689. * Sets the current transform matrix
  27690. * @param view defines the View matrix to use
  27691. * @param projection defines the Projection matrix to use
  27692. */
  27693. Scene.prototype.setTransformMatrix = function (view, projection) {
  27694. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27695. return;
  27696. }
  27697. this._viewUpdateFlag = view.updateFlag;
  27698. this._projectionUpdateFlag = projection.updateFlag;
  27699. this._viewMatrix = view;
  27700. this._projectionMatrix = projection;
  27701. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27702. // Update frustum
  27703. if (!this._frustumPlanes) {
  27704. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27705. }
  27706. else {
  27707. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27708. }
  27709. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27710. var otherCamera = this.activeCamera._alternateCamera;
  27711. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27712. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27713. }
  27714. if (this._sceneUbo.useUbo) {
  27715. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27716. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27717. this._sceneUbo.update();
  27718. }
  27719. };
  27720. /** @hidden */
  27721. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27722. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27723. return;
  27724. }
  27725. this._alternateViewUpdateFlag = view.updateFlag;
  27726. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27727. this._alternateViewMatrix = view;
  27728. this._alternateProjectionMatrix = projection;
  27729. if (!this._alternateTransformMatrix) {
  27730. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27731. }
  27732. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27733. if (!this._alternateSceneUbo) {
  27734. this._createAlternateUbo();
  27735. }
  27736. if (this._alternateSceneUbo.useUbo) {
  27737. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27738. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27739. this._alternateSceneUbo.update();
  27740. }
  27741. };
  27742. /**
  27743. * Gets the uniform buffer used to store scene data
  27744. * @returns a UniformBuffer
  27745. */
  27746. Scene.prototype.getSceneUniformBuffer = function () {
  27747. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27748. };
  27749. /**
  27750. * Gets an unique (relatively to the current scene) Id
  27751. * @returns an unique number for the scene
  27752. */
  27753. Scene.prototype.getUniqueId = function () {
  27754. var result = Scene._uniqueIdCounter;
  27755. Scene._uniqueIdCounter++;
  27756. return result;
  27757. };
  27758. /**
  27759. * Add a mesh to the list of scene's meshes
  27760. * @param newMesh defines the mesh to add
  27761. * @param recursive if all child meshes should also be added to the scene
  27762. */
  27763. Scene.prototype.addMesh = function (newMesh, recursive) {
  27764. var _this = this;
  27765. if (recursive === void 0) { recursive = false; }
  27766. this.meshes.push(newMesh);
  27767. //notify the collision coordinator
  27768. if (this.collisionCoordinator) {
  27769. this.collisionCoordinator.onMeshAdded(newMesh);
  27770. }
  27771. newMesh._resyncLightSources();
  27772. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27773. if (recursive) {
  27774. newMesh.getChildMeshes().forEach(function (m) {
  27775. _this.addMesh(m);
  27776. });
  27777. }
  27778. };
  27779. /**
  27780. * Remove a mesh for the list of scene's meshes
  27781. * @param toRemove defines the mesh to remove
  27782. * @param recursive if all child meshes should also be removed from the scene
  27783. * @returns the index where the mesh was in the mesh list
  27784. */
  27785. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27786. var _this = this;
  27787. if (recursive === void 0) { recursive = false; }
  27788. var index = this.meshes.indexOf(toRemove);
  27789. if (index !== -1) {
  27790. // Remove from the scene if mesh found
  27791. this.meshes[index] = this.meshes[this.meshes.length - 1];
  27792. this.meshes.pop();
  27793. }
  27794. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27795. if (recursive) {
  27796. toRemove.getChildMeshes().forEach(function (m) {
  27797. _this.removeMesh(m);
  27798. });
  27799. }
  27800. return index;
  27801. };
  27802. /**
  27803. * Add a transform node to the list of scene's transform nodes
  27804. * @param newTransformNode defines the transform node to add
  27805. */
  27806. Scene.prototype.addTransformNode = function (newTransformNode) {
  27807. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  27808. this.transformNodes.push(newTransformNode);
  27809. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27810. };
  27811. /**
  27812. * Remove a transform node for the list of scene's transform nodes
  27813. * @param toRemove defines the transform node to remove
  27814. * @returns the index where the transform node was in the transform node list
  27815. */
  27816. Scene.prototype.removeTransformNode = function (toRemove) {
  27817. var index = toRemove._indexInSceneTransformNodesArray;
  27818. if (index !== -1) {
  27819. if (index !== this.transformNodes.length - 1) {
  27820. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  27821. this.transformNodes[index] = lastNode;
  27822. lastNode._indexInSceneTransformNodesArray = index;
  27823. }
  27824. toRemove._indexInSceneTransformNodesArray = -1;
  27825. this.transformNodes.pop();
  27826. }
  27827. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27828. return index;
  27829. };
  27830. /**
  27831. * Remove a skeleton for the list of scene's skeletons
  27832. * @param toRemove defines the skeleton to remove
  27833. * @returns the index where the skeleton was in the skeleton list
  27834. */
  27835. Scene.prototype.removeSkeleton = function (toRemove) {
  27836. var index = this.skeletons.indexOf(toRemove);
  27837. if (index !== -1) {
  27838. // Remove from the scene if found
  27839. this.skeletons.splice(index, 1);
  27840. }
  27841. return index;
  27842. };
  27843. /**
  27844. * Remove a morph target for the list of scene's morph targets
  27845. * @param toRemove defines the morph target to remove
  27846. * @returns the index where the morph target was in the morph target list
  27847. */
  27848. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27849. var index = this.morphTargetManagers.indexOf(toRemove);
  27850. if (index !== -1) {
  27851. // Remove from the scene if found
  27852. this.morphTargetManagers.splice(index, 1);
  27853. }
  27854. return index;
  27855. };
  27856. /**
  27857. * Remove a light for the list of scene's lights
  27858. * @param toRemove defines the light to remove
  27859. * @returns the index where the light was in the light list
  27860. */
  27861. Scene.prototype.removeLight = function (toRemove) {
  27862. var index = this.lights.indexOf(toRemove);
  27863. if (index !== -1) {
  27864. // Remove from meshes
  27865. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27866. var mesh = _a[_i];
  27867. mesh._removeLightSource(toRemove);
  27868. }
  27869. // Remove from the scene if mesh found
  27870. this.lights.splice(index, 1);
  27871. this.sortLightsByPriority();
  27872. }
  27873. this.onLightRemovedObservable.notifyObservers(toRemove);
  27874. return index;
  27875. };
  27876. /**
  27877. * Remove a camera for the list of scene's cameras
  27878. * @param toRemove defines the camera to remove
  27879. * @returns the index where the camera was in the camera list
  27880. */
  27881. Scene.prototype.removeCamera = function (toRemove) {
  27882. var index = this.cameras.indexOf(toRemove);
  27883. if (index !== -1) {
  27884. // Remove from the scene if mesh found
  27885. this.cameras.splice(index, 1);
  27886. }
  27887. // Remove from activeCameras
  27888. var index2 = this.activeCameras.indexOf(toRemove);
  27889. if (index2 !== -1) {
  27890. // Remove from the scene if mesh found
  27891. this.activeCameras.splice(index2, 1);
  27892. }
  27893. // Reset the activeCamera
  27894. if (this.activeCamera === toRemove) {
  27895. if (this.cameras.length > 0) {
  27896. this.activeCamera = this.cameras[0];
  27897. }
  27898. else {
  27899. this.activeCamera = null;
  27900. }
  27901. }
  27902. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27903. return index;
  27904. };
  27905. /**
  27906. * Remove a particle system for the list of scene's particle systems
  27907. * @param toRemove defines the particle system to remove
  27908. * @returns the index where the particle system was in the particle system list
  27909. */
  27910. Scene.prototype.removeParticleSystem = function (toRemove) {
  27911. var index = this.particleSystems.indexOf(toRemove);
  27912. if (index !== -1) {
  27913. this.particleSystems.splice(index, 1);
  27914. }
  27915. return index;
  27916. };
  27917. /**
  27918. * Remove a animation for the list of scene's animations
  27919. * @param toRemove defines the animation to remove
  27920. * @returns the index where the animation was in the animation list
  27921. */
  27922. Scene.prototype.removeAnimation = function (toRemove) {
  27923. var index = this.animations.indexOf(toRemove);
  27924. if (index !== -1) {
  27925. this.animations.splice(index, 1);
  27926. }
  27927. return index;
  27928. };
  27929. /**
  27930. * Removes the given animation group from this scene.
  27931. * @param toRemove The animation group to remove
  27932. * @returns The index of the removed animation group
  27933. */
  27934. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27935. var index = this.animationGroups.indexOf(toRemove);
  27936. if (index !== -1) {
  27937. this.animationGroups.splice(index, 1);
  27938. }
  27939. return index;
  27940. };
  27941. /**
  27942. * Removes the given multi-material from this scene.
  27943. * @param toRemove The multi-material to remove
  27944. * @returns The index of the removed multi-material
  27945. */
  27946. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27947. var index = this.multiMaterials.indexOf(toRemove);
  27948. if (index !== -1) {
  27949. this.multiMaterials.splice(index, 1);
  27950. }
  27951. return index;
  27952. };
  27953. /**
  27954. * Removes the given material from this scene.
  27955. * @param toRemove The material to remove
  27956. * @returns The index of the removed material
  27957. */
  27958. Scene.prototype.removeMaterial = function (toRemove) {
  27959. var index = toRemove._indexInSceneMaterialArray;
  27960. if (index !== -1) {
  27961. if (index !== this.materials.length - 1) {
  27962. var lastMaterial = this.materials[this.materials.length - 1];
  27963. this.materials[index] = lastMaterial;
  27964. lastMaterial._indexInSceneMaterialArray = index;
  27965. }
  27966. toRemove._indexInSceneMaterialArray = -1;
  27967. this.materials.pop();
  27968. }
  27969. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27970. return index;
  27971. };
  27972. /**
  27973. * Removes the given action manager from this scene.
  27974. * @param toRemove The action manager to remove
  27975. * @returns The index of the removed action manager
  27976. */
  27977. Scene.prototype.removeActionManager = function (toRemove) {
  27978. var index = this.actionManagers.indexOf(toRemove);
  27979. if (index !== -1) {
  27980. this.actionManagers.splice(index, 1);
  27981. }
  27982. return index;
  27983. };
  27984. /**
  27985. * Removes the given texture from this scene.
  27986. * @param toRemove The texture to remove
  27987. * @returns The index of the removed texture
  27988. */
  27989. Scene.prototype.removeTexture = function (toRemove) {
  27990. var index = this.textures.indexOf(toRemove);
  27991. if (index !== -1) {
  27992. this.textures.splice(index, 1);
  27993. }
  27994. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27995. return index;
  27996. };
  27997. /**
  27998. * Adds the given light to this scene
  27999. * @param newLight The light to add
  28000. */
  28001. Scene.prototype.addLight = function (newLight) {
  28002. this.lights.push(newLight);
  28003. this.sortLightsByPriority();
  28004. // Add light to all meshes (To support if the light is removed and then readded)
  28005. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28006. var mesh = _a[_i];
  28007. if (mesh._lightSources.indexOf(newLight) === -1) {
  28008. mesh._lightSources.push(newLight);
  28009. mesh._resyncLightSources();
  28010. }
  28011. }
  28012. this.onNewLightAddedObservable.notifyObservers(newLight);
  28013. };
  28014. /**
  28015. * Sorts the list list based on light priorities
  28016. */
  28017. Scene.prototype.sortLightsByPriority = function () {
  28018. if (this.requireLightSorting) {
  28019. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  28020. }
  28021. };
  28022. /**
  28023. * Adds the given camera to this scene
  28024. * @param newCamera The camera to add
  28025. */
  28026. Scene.prototype.addCamera = function (newCamera) {
  28027. this.cameras.push(newCamera);
  28028. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  28029. };
  28030. /**
  28031. * Adds the given skeleton to this scene
  28032. * @param newSkeleton The skeleton to add
  28033. */
  28034. Scene.prototype.addSkeleton = function (newSkeleton) {
  28035. this.skeletons.push(newSkeleton);
  28036. };
  28037. /**
  28038. * Adds the given particle system to this scene
  28039. * @param newParticleSystem The particle system to add
  28040. */
  28041. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  28042. this.particleSystems.push(newParticleSystem);
  28043. };
  28044. /**
  28045. * Adds the given animation to this scene
  28046. * @param newAnimation The animation to add
  28047. */
  28048. Scene.prototype.addAnimation = function (newAnimation) {
  28049. this.animations.push(newAnimation);
  28050. };
  28051. /**
  28052. * Adds the given animation group to this scene.
  28053. * @param newAnimationGroup The animation group to add
  28054. */
  28055. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28056. this.animationGroups.push(newAnimationGroup);
  28057. };
  28058. /**
  28059. * Adds the given multi-material to this scene
  28060. * @param newMultiMaterial The multi-material to add
  28061. */
  28062. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28063. this.multiMaterials.push(newMultiMaterial);
  28064. };
  28065. /**
  28066. * Adds the given material to this scene
  28067. * @param newMaterial The material to add
  28068. */
  28069. Scene.prototype.addMaterial = function (newMaterial) {
  28070. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28071. this.materials.push(newMaterial);
  28072. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28073. };
  28074. /**
  28075. * Adds the given morph target to this scene
  28076. * @param newMorphTargetManager The morph target to add
  28077. */
  28078. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28079. this.morphTargetManagers.push(newMorphTargetManager);
  28080. };
  28081. /**
  28082. * Adds the given geometry to this scene
  28083. * @param newGeometry The geometry to add
  28084. */
  28085. Scene.prototype.addGeometry = function (newGeometry) {
  28086. if (this.geometriesById) {
  28087. this.geometriesById[newGeometry.id] = this.geometries.length;
  28088. }
  28089. this.geometries.push(newGeometry);
  28090. };
  28091. /**
  28092. * Adds the given action manager to this scene
  28093. * @param newActionManager The action manager to add
  28094. */
  28095. Scene.prototype.addActionManager = function (newActionManager) {
  28096. this.actionManagers.push(newActionManager);
  28097. };
  28098. /**
  28099. * Adds the given texture to this scene.
  28100. * @param newTexture The texture to add
  28101. */
  28102. Scene.prototype.addTexture = function (newTexture) {
  28103. this.textures.push(newTexture);
  28104. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28105. };
  28106. /**
  28107. * Switch active camera
  28108. * @param newCamera defines the new active camera
  28109. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28110. */
  28111. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28112. if (attachControl === void 0) { attachControl = true; }
  28113. var canvas = this._engine.getRenderingCanvas();
  28114. if (!canvas) {
  28115. return;
  28116. }
  28117. if (this.activeCamera) {
  28118. this.activeCamera.detachControl(canvas);
  28119. }
  28120. this.activeCamera = newCamera;
  28121. if (attachControl) {
  28122. newCamera.attachControl(canvas);
  28123. }
  28124. };
  28125. /**
  28126. * sets the active camera of the scene using its ID
  28127. * @param id defines the camera's ID
  28128. * @return the new active camera or null if none found.
  28129. */
  28130. Scene.prototype.setActiveCameraByID = function (id) {
  28131. var camera = this.getCameraByID(id);
  28132. if (camera) {
  28133. this.activeCamera = camera;
  28134. return camera;
  28135. }
  28136. return null;
  28137. };
  28138. /**
  28139. * sets the active camera of the scene using its name
  28140. * @param name defines the camera's name
  28141. * @returns the new active camera or null if none found.
  28142. */
  28143. Scene.prototype.setActiveCameraByName = function (name) {
  28144. var camera = this.getCameraByName(name);
  28145. if (camera) {
  28146. this.activeCamera = camera;
  28147. return camera;
  28148. }
  28149. return null;
  28150. };
  28151. /**
  28152. * get an animation group using its name
  28153. * @param name defines the material's name
  28154. * @return the animation group or null if none found.
  28155. */
  28156. Scene.prototype.getAnimationGroupByName = function (name) {
  28157. for (var index = 0; index < this.animationGroups.length; index++) {
  28158. if (this.animationGroups[index].name === name) {
  28159. return this.animationGroups[index];
  28160. }
  28161. }
  28162. return null;
  28163. };
  28164. /**
  28165. * get a material using its id
  28166. * @param id defines the material's ID
  28167. * @return the material or null if none found.
  28168. */
  28169. Scene.prototype.getMaterialByID = function (id) {
  28170. for (var index = 0; index < this.materials.length; index++) {
  28171. if (this.materials[index].id === id) {
  28172. return this.materials[index];
  28173. }
  28174. }
  28175. return null;
  28176. };
  28177. /**
  28178. * Gets a material using its name
  28179. * @param name defines the material's name
  28180. * @return the material or null if none found.
  28181. */
  28182. Scene.prototype.getMaterialByName = function (name) {
  28183. for (var index = 0; index < this.materials.length; index++) {
  28184. if (this.materials[index].name === name) {
  28185. return this.materials[index];
  28186. }
  28187. }
  28188. return null;
  28189. };
  28190. /**
  28191. * Gets a camera using its id
  28192. * @param id defines the id to look for
  28193. * @returns the camera or null if not found
  28194. */
  28195. Scene.prototype.getCameraByID = function (id) {
  28196. for (var index = 0; index < this.cameras.length; index++) {
  28197. if (this.cameras[index].id === id) {
  28198. return this.cameras[index];
  28199. }
  28200. }
  28201. return null;
  28202. };
  28203. /**
  28204. * Gets a camera using its unique id
  28205. * @param uniqueId defines the unique id to look for
  28206. * @returns the camera or null if not found
  28207. */
  28208. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28209. for (var index = 0; index < this.cameras.length; index++) {
  28210. if (this.cameras[index].uniqueId === uniqueId) {
  28211. return this.cameras[index];
  28212. }
  28213. }
  28214. return null;
  28215. };
  28216. /**
  28217. * Gets a camera using its name
  28218. * @param name defines the camera's name
  28219. * @return the camera or null if none found.
  28220. */
  28221. Scene.prototype.getCameraByName = function (name) {
  28222. for (var index = 0; index < this.cameras.length; index++) {
  28223. if (this.cameras[index].name === name) {
  28224. return this.cameras[index];
  28225. }
  28226. }
  28227. return null;
  28228. };
  28229. /**
  28230. * Gets a bone using its id
  28231. * @param id defines the bone's id
  28232. * @return the bone or null if not found
  28233. */
  28234. Scene.prototype.getBoneByID = function (id) {
  28235. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28236. var skeleton = this.skeletons[skeletonIndex];
  28237. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28238. if (skeleton.bones[boneIndex].id === id) {
  28239. return skeleton.bones[boneIndex];
  28240. }
  28241. }
  28242. }
  28243. return null;
  28244. };
  28245. /**
  28246. * Gets a bone using its id
  28247. * @param name defines the bone's name
  28248. * @return the bone or null if not found
  28249. */
  28250. Scene.prototype.getBoneByName = function (name) {
  28251. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28252. var skeleton = this.skeletons[skeletonIndex];
  28253. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28254. if (skeleton.bones[boneIndex].name === name) {
  28255. return skeleton.bones[boneIndex];
  28256. }
  28257. }
  28258. }
  28259. return null;
  28260. };
  28261. /**
  28262. * Gets a light node using its name
  28263. * @param name defines the the light's name
  28264. * @return the light or null if none found.
  28265. */
  28266. Scene.prototype.getLightByName = function (name) {
  28267. for (var index = 0; index < this.lights.length; index++) {
  28268. if (this.lights[index].name === name) {
  28269. return this.lights[index];
  28270. }
  28271. }
  28272. return null;
  28273. };
  28274. /**
  28275. * Gets a light node using its id
  28276. * @param id defines the light's id
  28277. * @return the light or null if none found.
  28278. */
  28279. Scene.prototype.getLightByID = function (id) {
  28280. for (var index = 0; index < this.lights.length; index++) {
  28281. if (this.lights[index].id === id) {
  28282. return this.lights[index];
  28283. }
  28284. }
  28285. return null;
  28286. };
  28287. /**
  28288. * Gets a light node using its scene-generated unique ID
  28289. * @param uniqueId defines the light's unique id
  28290. * @return the light or null if none found.
  28291. */
  28292. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28293. for (var index = 0; index < this.lights.length; index++) {
  28294. if (this.lights[index].uniqueId === uniqueId) {
  28295. return this.lights[index];
  28296. }
  28297. }
  28298. return null;
  28299. };
  28300. /**
  28301. * Gets a particle system by id
  28302. * @param id defines the particle system id
  28303. * @return the corresponding system or null if none found
  28304. */
  28305. Scene.prototype.getParticleSystemByID = function (id) {
  28306. for (var index = 0; index < this.particleSystems.length; index++) {
  28307. if (this.particleSystems[index].id === id) {
  28308. return this.particleSystems[index];
  28309. }
  28310. }
  28311. return null;
  28312. };
  28313. /**
  28314. * Gets a geometry using its ID
  28315. * @param id defines the geometry's id
  28316. * @return the geometry or null if none found.
  28317. */
  28318. Scene.prototype.getGeometryByID = function (id) {
  28319. if (this.geometriesById) {
  28320. var index_1 = this.geometriesById[id];
  28321. if (index_1 !== undefined) {
  28322. return this.geometries[index_1];
  28323. }
  28324. }
  28325. else {
  28326. for (var index = 0; index < this.geometries.length; index++) {
  28327. if (this.geometries[index].id === id) {
  28328. return this.geometries[index];
  28329. }
  28330. }
  28331. }
  28332. return null;
  28333. };
  28334. /**
  28335. * Add a new geometry to this scene
  28336. * @param geometry defines the geometry to be added to the scene.
  28337. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28338. * @return a boolean defining if the geometry was added or not
  28339. */
  28340. Scene.prototype.pushGeometry = function (geometry, force) {
  28341. if (!force && this.getGeometryByID(geometry.id)) {
  28342. return false;
  28343. }
  28344. this.addGeometry(geometry);
  28345. //notify the collision coordinator
  28346. if (this.collisionCoordinator) {
  28347. this.collisionCoordinator.onGeometryAdded(geometry);
  28348. }
  28349. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28350. return true;
  28351. };
  28352. /**
  28353. * Removes an existing geometry
  28354. * @param geometry defines the geometry to be removed from the scene
  28355. * @return a boolean defining if the geometry was removed or not
  28356. */
  28357. Scene.prototype.removeGeometry = function (geometry) {
  28358. var index;
  28359. if (this.geometriesById) {
  28360. index = this.geometriesById[geometry.id];
  28361. if (index === undefined) {
  28362. return false;
  28363. }
  28364. }
  28365. else {
  28366. index = this.geometries.indexOf(geometry);
  28367. if (index < 0) {
  28368. return false;
  28369. }
  28370. }
  28371. if (index !== this.geometries.length - 1) {
  28372. var lastGeometry = this.geometries[this.geometries.length - 1];
  28373. this.geometries[index] = lastGeometry;
  28374. if (this.geometriesById) {
  28375. this.geometriesById[lastGeometry.id] = index;
  28376. this.geometriesById[geometry.id] = undefined;
  28377. }
  28378. }
  28379. this.geometries.pop();
  28380. //notify the collision coordinator
  28381. if (this.collisionCoordinator) {
  28382. this.collisionCoordinator.onGeometryDeleted(geometry);
  28383. }
  28384. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28385. return true;
  28386. };
  28387. /**
  28388. * Gets the list of geometries attached to the scene
  28389. * @returns an array of Geometry
  28390. */
  28391. Scene.prototype.getGeometries = function () {
  28392. return this.geometries;
  28393. };
  28394. /**
  28395. * Gets the first added mesh found of a given ID
  28396. * @param id defines the id to search for
  28397. * @return the mesh found or null if not found at all
  28398. */
  28399. Scene.prototype.getMeshByID = function (id) {
  28400. for (var index = 0; index < this.meshes.length; index++) {
  28401. if (this.meshes[index].id === id) {
  28402. return this.meshes[index];
  28403. }
  28404. }
  28405. return null;
  28406. };
  28407. /**
  28408. * Gets a list of meshes using their id
  28409. * @param id defines the id to search for
  28410. * @returns a list of meshes
  28411. */
  28412. Scene.prototype.getMeshesByID = function (id) {
  28413. return this.meshes.filter(function (m) {
  28414. return m.id === id;
  28415. });
  28416. };
  28417. /**
  28418. * Gets the first added transform node found of a given ID
  28419. * @param id defines the id to search for
  28420. * @return the found transform node or null if not found at all.
  28421. */
  28422. Scene.prototype.getTransformNodeByID = function (id) {
  28423. for (var index = 0; index < this.transformNodes.length; index++) {
  28424. if (this.transformNodes[index].id === id) {
  28425. return this.transformNodes[index];
  28426. }
  28427. }
  28428. return null;
  28429. };
  28430. /**
  28431. * Gets a list of transform nodes using their id
  28432. * @param id defines the id to search for
  28433. * @returns a list of transform nodes
  28434. */
  28435. Scene.prototype.getTransformNodesByID = function (id) {
  28436. return this.transformNodes.filter(function (m) {
  28437. return m.id === id;
  28438. });
  28439. };
  28440. /**
  28441. * Gets a mesh with its auto-generated unique id
  28442. * @param uniqueId defines the unique id to search for
  28443. * @return the found mesh or null if not found at all.
  28444. */
  28445. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28446. for (var index = 0; index < this.meshes.length; index++) {
  28447. if (this.meshes[index].uniqueId === uniqueId) {
  28448. return this.meshes[index];
  28449. }
  28450. }
  28451. return null;
  28452. };
  28453. /**
  28454. * Gets a the last added mesh using a given id
  28455. * @param id defines the id to search for
  28456. * @return the found mesh or null if not found at all.
  28457. */
  28458. Scene.prototype.getLastMeshByID = function (id) {
  28459. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28460. if (this.meshes[index].id === id) {
  28461. return this.meshes[index];
  28462. }
  28463. }
  28464. return null;
  28465. };
  28466. /**
  28467. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28468. * @param id defines the id to search for
  28469. * @return the found node or null if not found at all
  28470. */
  28471. Scene.prototype.getLastEntryByID = function (id) {
  28472. var index;
  28473. for (index = this.meshes.length - 1; index >= 0; index--) {
  28474. if (this.meshes[index].id === id) {
  28475. return this.meshes[index];
  28476. }
  28477. }
  28478. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28479. if (this.transformNodes[index].id === id) {
  28480. return this.transformNodes[index];
  28481. }
  28482. }
  28483. for (index = this.cameras.length - 1; index >= 0; index--) {
  28484. if (this.cameras[index].id === id) {
  28485. return this.cameras[index];
  28486. }
  28487. }
  28488. for (index = this.lights.length - 1; index >= 0; index--) {
  28489. if (this.lights[index].id === id) {
  28490. return this.lights[index];
  28491. }
  28492. }
  28493. return null;
  28494. };
  28495. /**
  28496. * Gets a node (Mesh, Camera, Light) using a given id
  28497. * @param id defines the id to search for
  28498. * @return the found node or null if not found at all
  28499. */
  28500. Scene.prototype.getNodeByID = function (id) {
  28501. var mesh = this.getMeshByID(id);
  28502. if (mesh) {
  28503. return mesh;
  28504. }
  28505. var light = this.getLightByID(id);
  28506. if (light) {
  28507. return light;
  28508. }
  28509. var camera = this.getCameraByID(id);
  28510. if (camera) {
  28511. return camera;
  28512. }
  28513. var bone = this.getBoneByID(id);
  28514. return bone;
  28515. };
  28516. /**
  28517. * Gets a node (Mesh, Camera, Light) using a given name
  28518. * @param name defines the name to search for
  28519. * @return the found node or null if not found at all.
  28520. */
  28521. Scene.prototype.getNodeByName = function (name) {
  28522. var mesh = this.getMeshByName(name);
  28523. if (mesh) {
  28524. return mesh;
  28525. }
  28526. var light = this.getLightByName(name);
  28527. if (light) {
  28528. return light;
  28529. }
  28530. var camera = this.getCameraByName(name);
  28531. if (camera) {
  28532. return camera;
  28533. }
  28534. var bone = this.getBoneByName(name);
  28535. return bone;
  28536. };
  28537. /**
  28538. * Gets a mesh using a given name
  28539. * @param name defines the name to search for
  28540. * @return the found mesh or null if not found at all.
  28541. */
  28542. Scene.prototype.getMeshByName = function (name) {
  28543. for (var index = 0; index < this.meshes.length; index++) {
  28544. if (this.meshes[index].name === name) {
  28545. return this.meshes[index];
  28546. }
  28547. }
  28548. return null;
  28549. };
  28550. /**
  28551. * Gets a transform node using a given name
  28552. * @param name defines the name to search for
  28553. * @return the found transform node or null if not found at all.
  28554. */
  28555. Scene.prototype.getTransformNodeByName = function (name) {
  28556. for (var index = 0; index < this.transformNodes.length; index++) {
  28557. if (this.transformNodes[index].name === name) {
  28558. return this.transformNodes[index];
  28559. }
  28560. }
  28561. return null;
  28562. };
  28563. /**
  28564. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28565. * @param id defines the id to search for
  28566. * @return the found skeleton or null if not found at all.
  28567. */
  28568. Scene.prototype.getLastSkeletonByID = function (id) {
  28569. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28570. if (this.skeletons[index].id === id) {
  28571. return this.skeletons[index];
  28572. }
  28573. }
  28574. return null;
  28575. };
  28576. /**
  28577. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28578. * @param id defines the id to search for
  28579. * @return the found skeleton or null if not found at all.
  28580. */
  28581. Scene.prototype.getSkeletonById = function (id) {
  28582. for (var index = 0; index < this.skeletons.length; index++) {
  28583. if (this.skeletons[index].id === id) {
  28584. return this.skeletons[index];
  28585. }
  28586. }
  28587. return null;
  28588. };
  28589. /**
  28590. * Gets a skeleton using a given name
  28591. * @param name defines the name to search for
  28592. * @return the found skeleton or null if not found at all.
  28593. */
  28594. Scene.prototype.getSkeletonByName = function (name) {
  28595. for (var index = 0; index < this.skeletons.length; index++) {
  28596. if (this.skeletons[index].name === name) {
  28597. return this.skeletons[index];
  28598. }
  28599. }
  28600. return null;
  28601. };
  28602. /**
  28603. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28604. * @param id defines the id to search for
  28605. * @return the found morph target manager or null if not found at all.
  28606. */
  28607. Scene.prototype.getMorphTargetManagerById = function (id) {
  28608. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28609. if (this.morphTargetManagers[index].uniqueId === id) {
  28610. return this.morphTargetManagers[index];
  28611. }
  28612. }
  28613. return null;
  28614. };
  28615. /**
  28616. * Gets a boolean indicating if the given mesh is active
  28617. * @param mesh defines the mesh to look for
  28618. * @returns true if the mesh is in the active list
  28619. */
  28620. Scene.prototype.isActiveMesh = function (mesh) {
  28621. return (this._activeMeshes.indexOf(mesh) !== -1);
  28622. };
  28623. Object.defineProperty(Scene.prototype, "uid", {
  28624. /**
  28625. * Return a unique id as a string which can serve as an identifier for the scene
  28626. */
  28627. get: function () {
  28628. if (!this._uid) {
  28629. this._uid = BABYLON.Tools.RandomId();
  28630. }
  28631. return this._uid;
  28632. },
  28633. enumerable: true,
  28634. configurable: true
  28635. });
  28636. /**
  28637. * Add an externaly attached data from its key.
  28638. * This method call will fail and return false, if such key already exists.
  28639. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28640. * @param key the unique key that identifies the data
  28641. * @param data the data object to associate to the key for this Engine instance
  28642. * @return true if no such key were already present and the data was added successfully, false otherwise
  28643. */
  28644. Scene.prototype.addExternalData = function (key, data) {
  28645. if (!this._externalData) {
  28646. this._externalData = new BABYLON.StringDictionary();
  28647. }
  28648. return this._externalData.add(key, data);
  28649. };
  28650. /**
  28651. * Get an externaly attached data from its key
  28652. * @param key the unique key that identifies the data
  28653. * @return the associated data, if present (can be null), or undefined if not present
  28654. */
  28655. Scene.prototype.getExternalData = function (key) {
  28656. if (!this._externalData) {
  28657. return null;
  28658. }
  28659. return this._externalData.get(key);
  28660. };
  28661. /**
  28662. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28663. * @param key the unique key that identifies the data
  28664. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28665. * @return the associated data, can be null if the factory returned null.
  28666. */
  28667. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28668. if (!this._externalData) {
  28669. this._externalData = new BABYLON.StringDictionary();
  28670. }
  28671. return this._externalData.getOrAddWithFactory(key, factory);
  28672. };
  28673. /**
  28674. * Remove an externaly attached data from the Engine instance
  28675. * @param key the unique key that identifies the data
  28676. * @return true if the data was successfully removed, false if it doesn't exist
  28677. */
  28678. Scene.prototype.removeExternalData = function (key) {
  28679. return this._externalData.remove(key);
  28680. };
  28681. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28682. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28683. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28684. var step = _a[_i];
  28685. step.action(mesh, subMesh);
  28686. }
  28687. var material = subMesh.getMaterial();
  28688. if (material !== null && material !== undefined) {
  28689. // Render targets
  28690. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28691. if (this._processedMaterials.indexOf(material) === -1) {
  28692. this._processedMaterials.push(material);
  28693. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28694. }
  28695. }
  28696. // Dispatch
  28697. this._activeIndices.addCount(subMesh.indexCount, false);
  28698. this._renderingManager.dispatch(subMesh, mesh, material);
  28699. }
  28700. }
  28701. };
  28702. /**
  28703. * Clear the processed materials smart array preventing retention point in material dispose.
  28704. */
  28705. Scene.prototype.freeProcessedMaterials = function () {
  28706. this._processedMaterials.dispose();
  28707. };
  28708. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  28709. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  28710. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  28711. * when disposing several meshes in a row or a hierarchy of meshes.
  28712. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  28713. */
  28714. get: function () {
  28715. return this._preventFreeActiveMeshesAndRenderingGroups;
  28716. },
  28717. set: function (value) {
  28718. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  28719. return;
  28720. }
  28721. if (value) {
  28722. this.freeActiveMeshes();
  28723. this.freeRenderingGroups();
  28724. }
  28725. this._preventFreeActiveMeshesAndRenderingGroups = value;
  28726. },
  28727. enumerable: true,
  28728. configurable: true
  28729. });
  28730. /**
  28731. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28732. */
  28733. Scene.prototype.freeActiveMeshes = function () {
  28734. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28735. return;
  28736. }
  28737. this._activeMeshes.dispose();
  28738. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28739. this.activeCamera._activeMeshes.dispose();
  28740. }
  28741. if (this.activeCameras) {
  28742. for (var i = 0; i < this.activeCameras.length; i++) {
  28743. var activeCamera = this.activeCameras[i];
  28744. if (activeCamera && activeCamera._activeMeshes) {
  28745. activeCamera._activeMeshes.dispose();
  28746. }
  28747. }
  28748. }
  28749. };
  28750. /**
  28751. * Clear the info related to rendering groups preventing retention points during dispose.
  28752. */
  28753. Scene.prototype.freeRenderingGroups = function () {
  28754. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28755. return;
  28756. }
  28757. if (this._renderingManager) {
  28758. this._renderingManager.freeRenderingGroups();
  28759. }
  28760. if (this.textures) {
  28761. for (var i = 0; i < this.textures.length; i++) {
  28762. var texture = this.textures[i];
  28763. if (texture && texture.renderList) {
  28764. texture.freeRenderingGroups();
  28765. }
  28766. }
  28767. }
  28768. };
  28769. /** @hidden */
  28770. Scene.prototype._isInIntermediateRendering = function () {
  28771. return this._intermediateRendering;
  28772. };
  28773. /**
  28774. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28775. * @returns the current scene
  28776. */
  28777. Scene.prototype.freezeActiveMeshes = function () {
  28778. if (!this.activeCamera) {
  28779. return this;
  28780. }
  28781. if (!this._frustumPlanes) {
  28782. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28783. }
  28784. this._evaluateActiveMeshes();
  28785. this._activeMeshesFrozen = true;
  28786. return this;
  28787. };
  28788. /**
  28789. * Use this function to restart evaluating active meshes on every frame
  28790. * @returns the current scene
  28791. */
  28792. Scene.prototype.unfreezeActiveMeshes = function () {
  28793. this._activeMeshesFrozen = false;
  28794. return this;
  28795. };
  28796. Scene.prototype._evaluateActiveMeshes = function () {
  28797. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28798. return;
  28799. }
  28800. if (!this.activeCamera) {
  28801. return;
  28802. }
  28803. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28804. this.activeCamera._activeMeshes.reset();
  28805. this._activeMeshes.reset();
  28806. this._renderingManager.reset();
  28807. this._processedMaterials.reset();
  28808. this._activeParticleSystems.reset();
  28809. this._activeSkeletons.reset();
  28810. this._softwareSkinnedMeshes.reset();
  28811. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28812. var step = _a[_i];
  28813. step.action();
  28814. }
  28815. // Determine mesh candidates
  28816. var meshes = this.getActiveMeshCandidates();
  28817. // Check each mesh
  28818. var len = meshes.length;
  28819. for (var i = 0; i < len; i++) {
  28820. var mesh = meshes.data[i];
  28821. if (mesh.isBlocked) {
  28822. continue;
  28823. }
  28824. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28825. if (!mesh.isReady() || !mesh.isEnabled()) {
  28826. continue;
  28827. }
  28828. mesh.computeWorldMatrix();
  28829. // Intersections
  28830. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28831. this._meshesForIntersections.pushNoDuplicate(mesh);
  28832. }
  28833. // Switch to current LOD
  28834. var meshLOD = mesh.getLOD(this.activeCamera);
  28835. if (meshLOD === undefined || meshLOD === null) {
  28836. continue;
  28837. }
  28838. mesh._preActivate();
  28839. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  28840. this._activeMeshes.push(mesh);
  28841. this.activeCamera._activeMeshes.push(mesh);
  28842. mesh._activate(this._renderId);
  28843. if (meshLOD !== mesh) {
  28844. meshLOD._activate(this._renderId);
  28845. }
  28846. this._activeMesh(mesh, meshLOD);
  28847. }
  28848. }
  28849. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28850. // Particle systems
  28851. if (this.particlesEnabled) {
  28852. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28853. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28854. var particleSystem = this.particleSystems[particleIndex];
  28855. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28856. continue;
  28857. }
  28858. var emitter = particleSystem.emitter;
  28859. if (!emitter.position || emitter.isEnabled()) {
  28860. this._activeParticleSystems.push(particleSystem);
  28861. particleSystem.animate();
  28862. this._renderingManager.dispatchParticles(particleSystem);
  28863. }
  28864. }
  28865. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28866. }
  28867. };
  28868. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28869. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28870. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28871. mesh.skeleton.prepare();
  28872. }
  28873. if (!mesh.computeBonesUsingShaders) {
  28874. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28875. }
  28876. }
  28877. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28878. var step = _a[_i];
  28879. step.action(sourceMesh, mesh);
  28880. }
  28881. if (mesh !== undefined && mesh !== null
  28882. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28883. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28884. var len = subMeshes.length;
  28885. for (var i = 0; i < len; i++) {
  28886. var subMesh = subMeshes.data[i];
  28887. this._evaluateSubMesh(subMesh, mesh);
  28888. }
  28889. }
  28890. };
  28891. /**
  28892. * Update the transform matrix to update from the current active camera
  28893. * @param force defines a boolean used to force the update even if cache is up to date
  28894. */
  28895. Scene.prototype.updateTransformMatrix = function (force) {
  28896. if (!this.activeCamera) {
  28897. return;
  28898. }
  28899. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28900. };
  28901. /**
  28902. * 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)
  28903. * @param alternateCamera defines the camera to use
  28904. */
  28905. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28906. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28907. };
  28908. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28909. if (camera && camera._skipRendering) {
  28910. return;
  28911. }
  28912. var engine = this._engine;
  28913. this.activeCamera = camera;
  28914. if (!this.activeCamera) {
  28915. throw new Error("Active camera not set");
  28916. }
  28917. // Viewport
  28918. engine.setViewport(this.activeCamera.viewport);
  28919. // Camera
  28920. this.resetCachedMaterial();
  28921. this._renderId++;
  28922. this.updateTransformMatrix();
  28923. if (camera._alternateCamera) {
  28924. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28925. this._alternateRendering = true;
  28926. }
  28927. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28928. // Meshes
  28929. this._evaluateActiveMeshes();
  28930. // Software skinning
  28931. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28932. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28933. mesh.applySkeleton(mesh.skeleton);
  28934. }
  28935. // Render targets
  28936. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28937. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28938. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28939. }
  28940. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28941. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28942. }
  28943. // Collects render targets from external components.
  28944. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28945. var step = _a[_i];
  28946. step.action(this._renderTargets);
  28947. }
  28948. if (this.renderTargetsEnabled) {
  28949. this._intermediateRendering = true;
  28950. if (this._renderTargets.length > 0) {
  28951. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28952. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28953. var renderTarget = this._renderTargets.data[renderIndex];
  28954. if (renderTarget._shouldRender()) {
  28955. this._renderId++;
  28956. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28957. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28958. }
  28959. }
  28960. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28961. this._renderId++;
  28962. }
  28963. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28964. var step = _c[_b];
  28965. step.action(this.activeCamera);
  28966. }
  28967. this._intermediateRendering = false;
  28968. if (this.activeCamera.outputRenderTarget) {
  28969. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  28970. if (internalTexture) {
  28971. engine.bindFramebuffer(internalTexture);
  28972. }
  28973. else {
  28974. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  28975. }
  28976. }
  28977. else {
  28978. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28979. }
  28980. }
  28981. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28982. // Prepare Frame
  28983. if (this.postProcessManager) {
  28984. this.postProcessManager._prepareFrame();
  28985. }
  28986. // Before Camera Draw
  28987. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28988. var step = _e[_d];
  28989. step.action(this.activeCamera);
  28990. }
  28991. // Render
  28992. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28993. this._renderingManager.render(null, null, true, true);
  28994. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28995. // After Camera Draw
  28996. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28997. var step = _g[_f];
  28998. step.action(this.activeCamera);
  28999. }
  29000. // Finalize frame
  29001. if (this.postProcessManager) {
  29002. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  29003. }
  29004. // Reset some special arrays
  29005. this._renderTargets.reset();
  29006. this._alternateRendering = false;
  29007. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  29008. };
  29009. Scene.prototype._processSubCameras = function (camera) {
  29010. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  29011. this._renderForCamera(camera);
  29012. return;
  29013. }
  29014. // rig cameras
  29015. for (var index = 0; index < camera._rigCameras.length; index++) {
  29016. this._renderForCamera(camera._rigCameras[index], camera);
  29017. }
  29018. this.activeCamera = camera;
  29019. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29020. };
  29021. Scene.prototype._checkIntersections = function () {
  29022. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  29023. var sourceMesh = this._meshesForIntersections.data[index];
  29024. if (!sourceMesh.actionManager) {
  29025. continue;
  29026. }
  29027. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  29028. var action = sourceMesh.actionManager.actions[actionIndex];
  29029. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29030. var parameters = action.getTriggerParameter();
  29031. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  29032. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  29033. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  29034. if (areIntersecting && currentIntersectionInProgress === -1) {
  29035. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  29036. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29037. sourceMesh._intersectionsInProgress.push(otherMesh);
  29038. }
  29039. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29040. sourceMesh._intersectionsInProgress.push(otherMesh);
  29041. }
  29042. }
  29043. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  29044. //They intersected, and now they don't.
  29045. //is this trigger an exit trigger? execute an event.
  29046. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29047. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29048. }
  29049. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29050. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29051. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29052. return otherMesh === parameterMesh;
  29053. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29054. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29055. }
  29056. }
  29057. }
  29058. }
  29059. }
  29060. };
  29061. /** @hidden */
  29062. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29063. // Do nothing. Code will be replaced if physics engine component is referenced
  29064. };
  29065. /**
  29066. * Render the scene
  29067. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29068. */
  29069. Scene.prototype.render = function (updateCameras) {
  29070. if (updateCameras === void 0) { updateCameras = true; }
  29071. if (this.isDisposed) {
  29072. return;
  29073. }
  29074. this._frameId++;
  29075. // Register components that have been associated lately to the scene.
  29076. this._registerTransientComponents();
  29077. this._activeParticles.fetchNewFrame();
  29078. this._totalVertices.fetchNewFrame();
  29079. this._activeIndices.fetchNewFrame();
  29080. this._activeBones.fetchNewFrame();
  29081. this._meshesForIntersections.reset();
  29082. this.resetCachedMaterial();
  29083. this.onBeforeAnimationsObservable.notifyObservers(this);
  29084. // Actions
  29085. if (this.actionManager) {
  29086. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29087. }
  29088. if (this._engine.isDeterministicLockStep()) {
  29089. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29090. var defaultFPS = (60.0 / 1000.0);
  29091. var defaultFrameTime = this.getDeterministicFrameTime();
  29092. var stepsTaken = 0;
  29093. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29094. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29095. internalSteps = Math.min(internalSteps, maxSubSteps);
  29096. do {
  29097. this.onBeforeStepObservable.notifyObservers(this);
  29098. // Animations
  29099. this._animationRatio = defaultFrameTime * defaultFPS;
  29100. this._animate();
  29101. this.onAfterAnimationsObservable.notifyObservers(this);
  29102. // Physics
  29103. this._advancePhysicsEngineStep(defaultFrameTime);
  29104. this.onAfterStepObservable.notifyObservers(this);
  29105. this._currentStepId++;
  29106. stepsTaken++;
  29107. deltaTime -= defaultFrameTime;
  29108. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29109. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29110. }
  29111. else {
  29112. // Animations
  29113. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29114. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29115. this._animate();
  29116. this.onAfterAnimationsObservable.notifyObservers(this);
  29117. // Physics
  29118. this._advancePhysicsEngineStep(deltaTime);
  29119. }
  29120. // Before camera update steps
  29121. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29122. var step = _a[_i];
  29123. step.action();
  29124. }
  29125. // Update Cameras
  29126. if (updateCameras) {
  29127. if (this.activeCameras.length > 0) {
  29128. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29129. var camera = this.activeCameras[cameraIndex];
  29130. camera.update();
  29131. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29132. // rig cameras
  29133. for (var index = 0; index < camera._rigCameras.length; index++) {
  29134. camera._rigCameras[index].update();
  29135. }
  29136. }
  29137. }
  29138. }
  29139. else if (this.activeCamera) {
  29140. this.activeCamera.update();
  29141. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29142. // rig cameras
  29143. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29144. this.activeCamera._rigCameras[index].update();
  29145. }
  29146. }
  29147. }
  29148. }
  29149. // Before render
  29150. this.onBeforeRenderObservable.notifyObservers(this);
  29151. // Customs render targets
  29152. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29153. var engine = this.getEngine();
  29154. var currentActiveCamera = this.activeCamera;
  29155. if (this.renderTargetsEnabled) {
  29156. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29157. this._intermediateRendering = true;
  29158. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29159. var renderTarget = this.customRenderTargets[customIndex];
  29160. if (renderTarget._shouldRender()) {
  29161. this._renderId++;
  29162. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29163. if (!this.activeCamera) {
  29164. throw new Error("Active camera not set");
  29165. }
  29166. // Viewport
  29167. engine.setViewport(this.activeCamera.viewport);
  29168. // Camera
  29169. this.updateTransformMatrix();
  29170. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29171. }
  29172. }
  29173. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29174. this._intermediateRendering = false;
  29175. this._renderId++;
  29176. }
  29177. // Restore back buffer
  29178. if (this.customRenderTargets.length > 0) {
  29179. engine.restoreDefaultFramebuffer();
  29180. }
  29181. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29182. this.activeCamera = currentActiveCamera;
  29183. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29184. var step = _c[_b];
  29185. step.action();
  29186. }
  29187. // Clear
  29188. if (this.autoClearDepthAndStencil || this.autoClear) {
  29189. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29190. }
  29191. // Collects render targets from external components.
  29192. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29193. var step = _e[_d];
  29194. step.action(this._renderTargets);
  29195. }
  29196. // Multi-cameras?
  29197. if (this.activeCameras.length > 0) {
  29198. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29199. if (cameraIndex > 0) {
  29200. this._engine.clear(null, false, true, true);
  29201. }
  29202. this._processSubCameras(this.activeCameras[cameraIndex]);
  29203. }
  29204. }
  29205. else {
  29206. if (!this.activeCamera) {
  29207. throw new Error("No camera defined");
  29208. }
  29209. this._processSubCameras(this.activeCamera);
  29210. }
  29211. // Intersection checks
  29212. this._checkIntersections();
  29213. // Executes the after render stage actions.
  29214. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29215. var step = _g[_f];
  29216. step.action();
  29217. }
  29218. // After render
  29219. if (this.afterRender) {
  29220. this.afterRender();
  29221. }
  29222. this.onAfterRenderObservable.notifyObservers(this);
  29223. // Cleaning
  29224. if (this._toBeDisposed.length) {
  29225. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29226. var data = this._toBeDisposed[index];
  29227. if (data) {
  29228. data.dispose();
  29229. }
  29230. }
  29231. this._toBeDisposed = [];
  29232. }
  29233. if (this.dumpNextRenderTargets) {
  29234. this.dumpNextRenderTargets = false;
  29235. }
  29236. this._activeBones.addCount(0, true);
  29237. this._activeIndices.addCount(0, true);
  29238. this._activeParticles.addCount(0, true);
  29239. };
  29240. /**
  29241. * Freeze all materials
  29242. * A frozen material will not be updatable but should be faster to render
  29243. */
  29244. Scene.prototype.freezeMaterials = function () {
  29245. for (var i = 0; i < this.materials.length; i++) {
  29246. this.materials[i].freeze();
  29247. }
  29248. };
  29249. /**
  29250. * Unfreeze all materials
  29251. * A frozen material will not be updatable but should be faster to render
  29252. */
  29253. Scene.prototype.unfreezeMaterials = function () {
  29254. for (var i = 0; i < this.materials.length; i++) {
  29255. this.materials[i].unfreeze();
  29256. }
  29257. };
  29258. /**
  29259. * Releases all held ressources
  29260. */
  29261. Scene.prototype.dispose = function () {
  29262. this.beforeRender = null;
  29263. this.afterRender = null;
  29264. this.skeletons = [];
  29265. this.morphTargetManagers = [];
  29266. this._transientComponents = [];
  29267. this._isReadyForMeshStage.clear();
  29268. this._beforeEvaluateActiveMeshStage.clear();
  29269. this._evaluateSubMeshStage.clear();
  29270. this._activeMeshStage.clear();
  29271. this._cameraDrawRenderTargetStage.clear();
  29272. this._beforeCameraDrawStage.clear();
  29273. this._beforeRenderingGroupDrawStage.clear();
  29274. this._beforeRenderingMeshStage.clear();
  29275. this._afterRenderingMeshStage.clear();
  29276. this._afterRenderingGroupDrawStage.clear();
  29277. this._afterCameraDrawStage.clear();
  29278. this._afterRenderStage.clear();
  29279. this._beforeCameraUpdateStage.clear();
  29280. this._beforeClearStage.clear();
  29281. this._gatherRenderTargetsStage.clear();
  29282. this._gatherActiveCameraRenderTargetsStage.clear();
  29283. this._pointerMoveStage.clear();
  29284. this._pointerDownStage.clear();
  29285. this._pointerUpStage.clear();
  29286. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29287. var component = _a[_i];
  29288. component.dispose();
  29289. }
  29290. this.importedMeshesFiles = new Array();
  29291. this.stopAllAnimations();
  29292. this.resetCachedMaterial();
  29293. // Smart arrays
  29294. if (this.activeCamera) {
  29295. this.activeCamera._activeMeshes.dispose();
  29296. this.activeCamera = null;
  29297. }
  29298. this._activeMeshes.dispose();
  29299. this._renderingManager.dispose();
  29300. this._processedMaterials.dispose();
  29301. this._activeParticleSystems.dispose();
  29302. this._activeSkeletons.dispose();
  29303. this._softwareSkinnedMeshes.dispose();
  29304. this._renderTargets.dispose();
  29305. this._registeredForLateAnimationBindings.dispose();
  29306. this._meshesForIntersections.dispose();
  29307. this._toBeDisposed = [];
  29308. // Abort active requests
  29309. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29310. var request = _c[_b];
  29311. request.abort();
  29312. }
  29313. // Events
  29314. this.onDisposeObservable.notifyObservers(this);
  29315. this.onDisposeObservable.clear();
  29316. this.onBeforeRenderObservable.clear();
  29317. this.onAfterRenderObservable.clear();
  29318. this.onBeforeRenderTargetsRenderObservable.clear();
  29319. this.onAfterRenderTargetsRenderObservable.clear();
  29320. this.onAfterStepObservable.clear();
  29321. this.onBeforeStepObservable.clear();
  29322. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29323. this.onAfterActiveMeshesEvaluationObservable.clear();
  29324. this.onBeforeParticlesRenderingObservable.clear();
  29325. this.onAfterParticlesRenderingObservable.clear();
  29326. this.onBeforeDrawPhaseObservable.clear();
  29327. this.onAfterDrawPhaseObservable.clear();
  29328. this.onBeforeAnimationsObservable.clear();
  29329. this.onAfterAnimationsObservable.clear();
  29330. this.onDataLoadedObservable.clear();
  29331. this.onBeforeRenderingGroupObservable.clear();
  29332. this.onAfterRenderingGroupObservable.clear();
  29333. this.onMeshImportedObservable.clear();
  29334. this.onBeforeCameraRenderObservable.clear();
  29335. this.onAfterCameraRenderObservable.clear();
  29336. this.onReadyObservable.clear();
  29337. this.onNewCameraAddedObservable.clear();
  29338. this.onCameraRemovedObservable.clear();
  29339. this.onNewLightAddedObservable.clear();
  29340. this.onLightRemovedObservable.clear();
  29341. this.onNewGeometryAddedObservable.clear();
  29342. this.onGeometryRemovedObservable.clear();
  29343. this.onNewTransformNodeAddedObservable.clear();
  29344. this.onTransformNodeRemovedObservable.clear();
  29345. this.onNewMeshAddedObservable.clear();
  29346. this.onMeshRemovedObservable.clear();
  29347. this.onNewMaterialAddedObservable.clear();
  29348. this.onMaterialRemovedObservable.clear();
  29349. this.onNewTextureAddedObservable.clear();
  29350. this.onTextureRemovedObservable.clear();
  29351. this.onPrePointerObservable.clear();
  29352. this.onPointerObservable.clear();
  29353. this.onPreKeyboardObservable.clear();
  29354. this.onKeyboardObservable.clear();
  29355. this.onActiveCameraChanged.clear();
  29356. this.detachControl();
  29357. // Detach cameras
  29358. var canvas = this._engine.getRenderingCanvas();
  29359. if (canvas) {
  29360. var index;
  29361. for (index = 0; index < this.cameras.length; index++) {
  29362. this.cameras[index].detachControl(canvas);
  29363. }
  29364. }
  29365. // Release animation groups
  29366. while (this.animationGroups.length) {
  29367. this.animationGroups[0].dispose();
  29368. }
  29369. // Release lights
  29370. while (this.lights.length) {
  29371. this.lights[0].dispose();
  29372. }
  29373. // Release meshes
  29374. while (this.meshes.length) {
  29375. this.meshes[0].dispose(true);
  29376. }
  29377. while (this.transformNodes.length) {
  29378. this.removeTransformNode(this.transformNodes[0]);
  29379. }
  29380. // Release cameras
  29381. while (this.cameras.length) {
  29382. this.cameras[0].dispose();
  29383. }
  29384. // Release materials
  29385. if (this.defaultMaterial) {
  29386. this.defaultMaterial.dispose();
  29387. }
  29388. while (this.multiMaterials.length) {
  29389. this.multiMaterials[0].dispose();
  29390. }
  29391. while (this.materials.length) {
  29392. this.materials[0].dispose();
  29393. }
  29394. // Release particles
  29395. while (this.particleSystems.length) {
  29396. this.particleSystems[0].dispose();
  29397. }
  29398. // Release postProcesses
  29399. while (this.postProcesses.length) {
  29400. this.postProcesses[0].dispose();
  29401. }
  29402. // Release textures
  29403. while (this.textures.length) {
  29404. this.textures[0].dispose();
  29405. }
  29406. // Release UBO
  29407. this._sceneUbo.dispose();
  29408. if (this._alternateSceneUbo) {
  29409. this._alternateSceneUbo.dispose();
  29410. }
  29411. // Post-processes
  29412. this.postProcessManager.dispose();
  29413. // Remove from engine
  29414. index = this._engine.scenes.indexOf(this);
  29415. if (index > -1) {
  29416. this._engine.scenes.splice(index, 1);
  29417. }
  29418. this._engine.wipeCaches(true);
  29419. this._isDisposed = true;
  29420. };
  29421. Object.defineProperty(Scene.prototype, "isDisposed", {
  29422. /**
  29423. * Gets if the scene is already disposed
  29424. */
  29425. get: function () {
  29426. return this._isDisposed;
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. /**
  29432. * Call this function to reduce memory footprint of the scene.
  29433. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29434. */
  29435. Scene.prototype.clearCachedVertexData = function () {
  29436. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29437. var mesh = this.meshes[meshIndex];
  29438. var geometry = mesh.geometry;
  29439. if (geometry) {
  29440. geometry._indices = [];
  29441. for (var vbName in geometry._vertexBuffers) {
  29442. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29443. continue;
  29444. }
  29445. geometry._vertexBuffers[vbName]._buffer._data = null;
  29446. }
  29447. }
  29448. }
  29449. };
  29450. /**
  29451. * This function will remove the local cached buffer data from texture.
  29452. * It will save memory but will prevent the texture from being rebuilt
  29453. */
  29454. Scene.prototype.cleanCachedTextureBuffer = function () {
  29455. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29456. var baseTexture = _a[_i];
  29457. var buffer = baseTexture._buffer;
  29458. if (buffer) {
  29459. baseTexture._buffer = null;
  29460. }
  29461. }
  29462. };
  29463. /**
  29464. * Get the world extend vectors with an optional filter
  29465. *
  29466. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29467. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29468. */
  29469. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29470. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29471. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29472. filterPredicate = filterPredicate || (function () { return true; });
  29473. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29474. mesh.computeWorldMatrix(true);
  29475. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29476. return;
  29477. }
  29478. var boundingInfo = mesh.getBoundingInfo();
  29479. var minBox = boundingInfo.boundingBox.minimumWorld;
  29480. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29481. BABYLON.Tools.CheckExtends(minBox, min, max);
  29482. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29483. });
  29484. return {
  29485. min: min,
  29486. max: max
  29487. };
  29488. };
  29489. // Picking
  29490. /**
  29491. * Creates a ray that can be used to pick in the scene
  29492. * @param x defines the x coordinate of the origin (on-screen)
  29493. * @param y defines the y coordinate of the origin (on-screen)
  29494. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29495. * @param camera defines the camera to use for the picking
  29496. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29497. * @returns a Ray
  29498. */
  29499. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29500. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29501. var result = BABYLON.Ray.Zero();
  29502. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29503. return result;
  29504. };
  29505. /**
  29506. * Creates a ray that can be used to pick in the scene
  29507. * @param x defines the x coordinate of the origin (on-screen)
  29508. * @param y defines the y coordinate of the origin (on-screen)
  29509. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29510. * @param result defines the ray where to store the picking ray
  29511. * @param camera defines the camera to use for the picking
  29512. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29513. * @returns the current scene
  29514. */
  29515. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29516. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29517. var engine = this._engine;
  29518. if (!camera) {
  29519. if (!this.activeCamera) {
  29520. throw new Error("Active camera not set");
  29521. }
  29522. camera = this.activeCamera;
  29523. }
  29524. var cameraViewport = camera.viewport;
  29525. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29526. // Moving coordinates to local viewport world
  29527. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29528. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29529. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.IdentityReadOnly, cameraViewSpace ? BABYLON.Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix());
  29530. return this;
  29531. };
  29532. /**
  29533. * Creates a ray that can be used to pick in the scene
  29534. * @param x defines the x coordinate of the origin (on-screen)
  29535. * @param y defines the y coordinate of the origin (on-screen)
  29536. * @param camera defines the camera to use for the picking
  29537. * @returns a Ray
  29538. */
  29539. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29540. var result = BABYLON.Ray.Zero();
  29541. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29542. return result;
  29543. };
  29544. /**
  29545. * Creates a ray that can be used to pick in the scene
  29546. * @param x defines the x coordinate of the origin (on-screen)
  29547. * @param y defines the y coordinate of the origin (on-screen)
  29548. * @param result defines the ray where to store the picking ray
  29549. * @param camera defines the camera to use for the picking
  29550. * @returns the current scene
  29551. */
  29552. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29553. if (!BABYLON.PickingInfo) {
  29554. return this;
  29555. }
  29556. var engine = this._engine;
  29557. if (!camera) {
  29558. if (!this.activeCamera) {
  29559. throw new Error("Active camera not set");
  29560. }
  29561. camera = this.activeCamera;
  29562. }
  29563. var cameraViewport = camera.viewport;
  29564. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29565. var identity = BABYLON.Matrix.Identity();
  29566. // Moving coordinates to local viewport world
  29567. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29568. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29569. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29570. return this;
  29571. };
  29572. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29573. if (!BABYLON.PickingInfo) {
  29574. return null;
  29575. }
  29576. var pickingInfo = null;
  29577. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29578. var mesh = this.meshes[meshIndex];
  29579. if (predicate) {
  29580. if (!predicate(mesh)) {
  29581. continue;
  29582. }
  29583. }
  29584. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29585. continue;
  29586. }
  29587. var world = mesh.getWorldMatrix();
  29588. var ray = rayFunction(world);
  29589. var result = mesh.intersects(ray, fastCheck);
  29590. if (!result || !result.hit) {
  29591. continue;
  29592. }
  29593. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29594. continue;
  29595. }
  29596. pickingInfo = result;
  29597. if (fastCheck) {
  29598. break;
  29599. }
  29600. }
  29601. return pickingInfo || new BABYLON.PickingInfo();
  29602. };
  29603. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29604. if (!BABYLON.PickingInfo) {
  29605. return null;
  29606. }
  29607. var pickingInfos = new Array();
  29608. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29609. var mesh = this.meshes[meshIndex];
  29610. if (predicate) {
  29611. if (!predicate(mesh)) {
  29612. continue;
  29613. }
  29614. }
  29615. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29616. continue;
  29617. }
  29618. var world = mesh.getWorldMatrix();
  29619. var ray = rayFunction(world);
  29620. var result = mesh.intersects(ray, false);
  29621. if (!result || !result.hit) {
  29622. continue;
  29623. }
  29624. pickingInfos.push(result);
  29625. }
  29626. return pickingInfos;
  29627. };
  29628. /** Launch a ray to try to pick a mesh in the scene
  29629. * @param x position on screen
  29630. * @param y position on screen
  29631. * @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
  29632. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29633. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29634. * @returns a PickingInfo
  29635. */
  29636. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29637. var _this = this;
  29638. if (!BABYLON.PickingInfo) {
  29639. return null;
  29640. }
  29641. var result = this._internalPick(function (world) {
  29642. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29643. return _this._tempPickingRay;
  29644. }, predicate, fastCheck);
  29645. if (result) {
  29646. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29647. }
  29648. return result;
  29649. };
  29650. /** Use the given ray to pick a mesh in the scene
  29651. * @param ray The ray to use to pick meshes
  29652. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  29653. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29654. * @returns a PickingInfo
  29655. */
  29656. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29657. var _this = this;
  29658. var result = this._internalPick(function (world) {
  29659. if (!_this._pickWithRayInverseMatrix) {
  29660. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29661. }
  29662. world.invertToRef(_this._pickWithRayInverseMatrix);
  29663. if (!_this._cachedRayForTransform) {
  29664. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29665. }
  29666. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29667. return _this._cachedRayForTransform;
  29668. }, predicate, fastCheck);
  29669. if (result) {
  29670. result.ray = ray;
  29671. }
  29672. return result;
  29673. };
  29674. /**
  29675. * Launch a ray to try to pick a mesh in the scene
  29676. * @param x X position on screen
  29677. * @param y Y position on screen
  29678. * @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
  29679. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29680. * @returns an array of PickingInfo
  29681. */
  29682. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29683. var _this = this;
  29684. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29685. };
  29686. /**
  29687. * Launch a ray to try to pick a mesh in the scene
  29688. * @param ray Ray to use
  29689. * @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
  29690. * @returns an array of PickingInfo
  29691. */
  29692. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29693. var _this = this;
  29694. return this._internalMultiPick(function (world) {
  29695. if (!_this._pickWithRayInverseMatrix) {
  29696. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29697. }
  29698. world.invertToRef(_this._pickWithRayInverseMatrix);
  29699. if (!_this._cachedRayForTransform) {
  29700. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29701. }
  29702. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29703. return _this._cachedRayForTransform;
  29704. }, predicate);
  29705. };
  29706. /**
  29707. * Force the value of meshUnderPointer
  29708. * @param mesh defines the mesh to use
  29709. */
  29710. Scene.prototype.setPointerOverMesh = function (mesh) {
  29711. if (this._pointerOverMesh === mesh) {
  29712. return;
  29713. }
  29714. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29715. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29716. }
  29717. this._pointerOverMesh = mesh;
  29718. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29719. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29720. }
  29721. };
  29722. /**
  29723. * Gets the mesh under the pointer
  29724. * @returns a Mesh or null if no mesh is under the pointer
  29725. */
  29726. Scene.prototype.getPointerOverMesh = function () {
  29727. return this._pointerOverMesh;
  29728. };
  29729. // Misc.
  29730. /** @hidden */
  29731. Scene.prototype._rebuildGeometries = function () {
  29732. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29733. var geometry = _a[_i];
  29734. geometry._rebuild();
  29735. }
  29736. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29737. var mesh = _c[_b];
  29738. mesh._rebuild();
  29739. }
  29740. if (this.postProcessManager) {
  29741. this.postProcessManager._rebuild();
  29742. }
  29743. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29744. var component = _e[_d];
  29745. component.rebuild();
  29746. }
  29747. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29748. var system = _g[_f];
  29749. system.rebuild();
  29750. }
  29751. };
  29752. /** @hidden */
  29753. Scene.prototype._rebuildTextures = function () {
  29754. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29755. var texture = _a[_i];
  29756. texture._rebuild();
  29757. }
  29758. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29759. };
  29760. // Tags
  29761. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29762. if (tagsQuery === undefined) {
  29763. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29764. return list;
  29765. }
  29766. var listByTags = [];
  29767. forEach = forEach || (function (item) { return; });
  29768. for (var i in list) {
  29769. var item = list[i];
  29770. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29771. listByTags.push(item);
  29772. forEach(item);
  29773. }
  29774. }
  29775. return listByTags;
  29776. };
  29777. /**
  29778. * Get a list of meshes by tags
  29779. * @param tagsQuery defines the tags query to use
  29780. * @param forEach defines a predicate used to filter results
  29781. * @returns an array of Mesh
  29782. */
  29783. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29784. return this._getByTags(this.meshes, tagsQuery, forEach);
  29785. };
  29786. /**
  29787. * Get a list of cameras by tags
  29788. * @param tagsQuery defines the tags query to use
  29789. * @param forEach defines a predicate used to filter results
  29790. * @returns an array of Camera
  29791. */
  29792. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29793. return this._getByTags(this.cameras, tagsQuery, forEach);
  29794. };
  29795. /**
  29796. * Get a list of lights by tags
  29797. * @param tagsQuery defines the tags query to use
  29798. * @param forEach defines a predicate used to filter results
  29799. * @returns an array of Light
  29800. */
  29801. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29802. return this._getByTags(this.lights, tagsQuery, forEach);
  29803. };
  29804. /**
  29805. * Get a list of materials by tags
  29806. * @param tagsQuery defines the tags query to use
  29807. * @param forEach defines a predicate used to filter results
  29808. * @returns an array of Material
  29809. */
  29810. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29811. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29812. };
  29813. /**
  29814. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29815. * This allowed control for front to back rendering or reversly depending of the special needs.
  29816. *
  29817. * @param renderingGroupId The rendering group id corresponding to its index
  29818. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29819. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29820. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29821. */
  29822. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29823. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29824. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29825. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29826. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29827. };
  29828. /**
  29829. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29830. *
  29831. * @param renderingGroupId The rendering group id corresponding to its index
  29832. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29833. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29834. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29835. */
  29836. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29837. if (depth === void 0) { depth = true; }
  29838. if (stencil === void 0) { stencil = true; }
  29839. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29840. };
  29841. /**
  29842. * Gets the current auto clear configuration for one rendering group of the rendering
  29843. * manager.
  29844. * @param index the rendering group index to get the information for
  29845. * @returns The auto clear setup for the requested rendering group
  29846. */
  29847. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29848. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29849. };
  29850. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29851. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29852. get: function () {
  29853. return this._blockMaterialDirtyMechanism;
  29854. },
  29855. set: function (value) {
  29856. if (this._blockMaterialDirtyMechanism === value) {
  29857. return;
  29858. }
  29859. this._blockMaterialDirtyMechanism = value;
  29860. if (!value) { // Do a complete update
  29861. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29862. }
  29863. },
  29864. enumerable: true,
  29865. configurable: true
  29866. });
  29867. /**
  29868. * Will flag all materials as dirty to trigger new shader compilation
  29869. * @param flag defines the flag used to specify which material part must be marked as dirty
  29870. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29871. */
  29872. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29873. if (this._blockMaterialDirtyMechanism) {
  29874. return;
  29875. }
  29876. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29877. var material = _a[_i];
  29878. if (predicate && !predicate(material)) {
  29879. continue;
  29880. }
  29881. material.markAsDirty(flag);
  29882. }
  29883. };
  29884. /** @hidden */
  29885. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  29886. var _this = this;
  29887. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  29888. this._activeRequests.push(request);
  29889. request.onCompleteObservable.add(function (request) {
  29890. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29891. });
  29892. return request;
  29893. };
  29894. /** @hidden */
  29895. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  29896. var _this = this;
  29897. return new Promise(function (resolve, reject) {
  29898. _this._loadFile(url, function (data) {
  29899. resolve(data);
  29900. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  29901. reject(exception);
  29902. });
  29903. });
  29904. };
  29905. // Statics
  29906. Scene._uniqueIdCounter = 0;
  29907. /** The fog is deactivated */
  29908. Scene.FOGMODE_NONE = 0;
  29909. /** The fog density is following an exponential function */
  29910. Scene.FOGMODE_EXP = 1;
  29911. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29912. Scene.FOGMODE_EXP2 = 2;
  29913. /** The fog density is following a linear function. */
  29914. Scene.FOGMODE_LINEAR = 3;
  29915. /**
  29916. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29917. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29918. */
  29919. Scene.MinDeltaTime = 1.0;
  29920. /**
  29921. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29922. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29923. */
  29924. Scene.MaxDeltaTime = 1000.0;
  29925. /** The distance in pixel that you have to move to prevent some events */
  29926. Scene.DragMovementThreshold = 10; // in pixels
  29927. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29928. Scene.LongPressDelay = 500; // in milliseconds
  29929. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29930. Scene.DoubleClickDelay = 300; // in milliseconds
  29931. /** If you need to check double click without raising a single click at first click, enable this flag */
  29932. Scene.ExclusiveDoubleClickMode = false;
  29933. return Scene;
  29934. }(BABYLON.AbstractScene));
  29935. BABYLON.Scene = Scene;
  29936. })(BABYLON || (BABYLON = {}));
  29937. //# sourceMappingURL=babylon.scene.js.map
  29938. var BABYLON;
  29939. (function (BABYLON) {
  29940. /**
  29941. * Set of assets to keep when moving a scene into an asset container.
  29942. */
  29943. var KeepAssets = /** @class */ (function (_super) {
  29944. __extends(KeepAssets, _super);
  29945. function KeepAssets() {
  29946. return _super !== null && _super.apply(this, arguments) || this;
  29947. }
  29948. return KeepAssets;
  29949. }(BABYLON.AbstractScene));
  29950. BABYLON.KeepAssets = KeepAssets;
  29951. /**
  29952. * Container with a set of assets that can be added or removed from a scene.
  29953. */
  29954. var AssetContainer = /** @class */ (function (_super) {
  29955. __extends(AssetContainer, _super);
  29956. /**
  29957. * Instantiates an AssetContainer.
  29958. * @param scene The scene the AssetContainer belongs to.
  29959. */
  29960. function AssetContainer(scene) {
  29961. var _this = _super.call(this) || this;
  29962. _this.scene = scene;
  29963. _this["sounds"] = [];
  29964. _this["effectLayers"] = [];
  29965. _this["layers"] = [];
  29966. _this["lensFlareSystems"] = [];
  29967. _this["proceduralTextures"] = [];
  29968. return _this;
  29969. }
  29970. /**
  29971. * Adds all the assets from the container to the scene.
  29972. */
  29973. AssetContainer.prototype.addAllToScene = function () {
  29974. var _this = this;
  29975. this.cameras.forEach(function (o) {
  29976. _this.scene.addCamera(o);
  29977. });
  29978. this.lights.forEach(function (o) {
  29979. _this.scene.addLight(o);
  29980. });
  29981. this.meshes.forEach(function (o) {
  29982. _this.scene.addMesh(o);
  29983. });
  29984. this.skeletons.forEach(function (o) {
  29985. _this.scene.addSkeleton(o);
  29986. });
  29987. this.animations.forEach(function (o) {
  29988. _this.scene.addAnimation(o);
  29989. });
  29990. this.animationGroups.forEach(function (o) {
  29991. _this.scene.addAnimationGroup(o);
  29992. });
  29993. this.multiMaterials.forEach(function (o) {
  29994. _this.scene.addMultiMaterial(o);
  29995. });
  29996. this.materials.forEach(function (o) {
  29997. _this.scene.addMaterial(o);
  29998. });
  29999. this.morphTargetManagers.forEach(function (o) {
  30000. _this.scene.addMorphTargetManager(o);
  30001. });
  30002. this.geometries.forEach(function (o) {
  30003. _this.scene.addGeometry(o);
  30004. });
  30005. this.transformNodes.forEach(function (o) {
  30006. _this.scene.addTransformNode(o);
  30007. });
  30008. this.actionManagers.forEach(function (o) {
  30009. _this.scene.addActionManager(o);
  30010. });
  30011. this.textures.forEach(function (o) {
  30012. _this.scene.addTexture(o);
  30013. });
  30014. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30015. var component = _a[_i];
  30016. component.addFromContainer(this);
  30017. }
  30018. };
  30019. /**
  30020. * Removes all the assets in the container from the scene
  30021. */
  30022. AssetContainer.prototype.removeAllFromScene = function () {
  30023. var _this = this;
  30024. this.cameras.forEach(function (o) {
  30025. _this.scene.removeCamera(o);
  30026. });
  30027. this.lights.forEach(function (o) {
  30028. _this.scene.removeLight(o);
  30029. });
  30030. this.meshes.forEach(function (o) {
  30031. _this.scene.removeMesh(o);
  30032. });
  30033. this.skeletons.forEach(function (o) {
  30034. _this.scene.removeSkeleton(o);
  30035. });
  30036. this.animations.forEach(function (o) {
  30037. _this.scene.removeAnimation(o);
  30038. });
  30039. this.animationGroups.forEach(function (o) {
  30040. _this.scene.removeAnimationGroup(o);
  30041. });
  30042. this.multiMaterials.forEach(function (o) {
  30043. _this.scene.removeMultiMaterial(o);
  30044. });
  30045. this.materials.forEach(function (o) {
  30046. _this.scene.removeMaterial(o);
  30047. });
  30048. this.morphTargetManagers.forEach(function (o) {
  30049. _this.scene.removeMorphTargetManager(o);
  30050. });
  30051. this.geometries.forEach(function (o) {
  30052. _this.scene.removeGeometry(o);
  30053. });
  30054. this.transformNodes.forEach(function (o) {
  30055. _this.scene.removeTransformNode(o);
  30056. });
  30057. this.actionManagers.forEach(function (o) {
  30058. _this.scene.removeActionManager(o);
  30059. });
  30060. this.textures.forEach(function (o) {
  30061. _this.scene.removeTexture(o);
  30062. });
  30063. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30064. var component = _a[_i];
  30065. component.removeFromContainer(this);
  30066. }
  30067. };
  30068. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30069. if (!sourceAssets) {
  30070. return;
  30071. }
  30072. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30073. var asset = sourceAssets_1[_i];
  30074. var move = true;
  30075. if (keepAssets) {
  30076. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30077. var keepAsset = keepAssets_1[_a];
  30078. if (asset === keepAsset) {
  30079. move = false;
  30080. break;
  30081. }
  30082. }
  30083. }
  30084. if (move) {
  30085. targetAssets.push(asset);
  30086. }
  30087. }
  30088. };
  30089. /**
  30090. * Removes all the assets contained in the scene and adds them to the container.
  30091. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30092. */
  30093. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30094. if (keepAssets === undefined) {
  30095. keepAssets = new KeepAssets();
  30096. }
  30097. for (var key in this) {
  30098. if (this.hasOwnProperty(key)) {
  30099. this[key] = this[key] || [];
  30100. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30101. }
  30102. }
  30103. this.removeAllFromScene();
  30104. };
  30105. /**
  30106. * 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.
  30107. * @returns the root mesh
  30108. */
  30109. AssetContainer.prototype.createRootMesh = function () {
  30110. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30111. this.meshes.forEach(function (m) {
  30112. if (!m.parent) {
  30113. rootMesh.addChild(m);
  30114. }
  30115. });
  30116. this.meshes.unshift(rootMesh);
  30117. return rootMesh;
  30118. };
  30119. return AssetContainer;
  30120. }(BABYLON.AbstractScene));
  30121. BABYLON.AssetContainer = AssetContainer;
  30122. })(BABYLON || (BABYLON = {}));
  30123. //# sourceMappingURL=babylon.assetContainer.js.map
  30124. var BABYLON;
  30125. (function (BABYLON) {
  30126. /**
  30127. * Class used to store data that will be store in GPU memory
  30128. */
  30129. var Buffer = /** @class */ (function () {
  30130. /**
  30131. * Constructor
  30132. * @param engine the engine
  30133. * @param data the data to use for this buffer
  30134. * @param updatable whether the data is updatable
  30135. * @param stride the stride (optional)
  30136. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30137. * @param instanced whether the buffer is instanced (optional)
  30138. * @param useBytes set to true if the stride in in bytes (optional)
  30139. */
  30140. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30141. if (stride === void 0) { stride = 0; }
  30142. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30143. if (instanced === void 0) { instanced = false; }
  30144. if (useBytes === void 0) { useBytes = false; }
  30145. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30146. this._engine = engine.getScene().getEngine();
  30147. }
  30148. else {
  30149. this._engine = engine;
  30150. }
  30151. this._updatable = updatable;
  30152. this._instanced = instanced;
  30153. this._data = data;
  30154. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30155. if (!postponeInternalCreation) { // by default
  30156. this.create();
  30157. }
  30158. }
  30159. /**
  30160. * Create a new VertexBuffer based on the current buffer
  30161. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30162. * @param offset defines offset in the buffer (0 by default)
  30163. * @param size defines the size in floats of attributes (position is 3 for instance)
  30164. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30165. * @param instanced defines if the vertex buffer contains indexed data
  30166. * @param useBytes defines if the offset and stride are in bytes
  30167. * @returns the new vertex buffer
  30168. */
  30169. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30170. if (useBytes === void 0) { useBytes = false; }
  30171. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30172. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30173. // a lot of these parameters are ignored as they are overriden by the buffer
  30174. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30175. };
  30176. // Properties
  30177. /**
  30178. * Gets a boolean indicating if the Buffer is updatable?
  30179. * @returns true if the buffer is updatable
  30180. */
  30181. Buffer.prototype.isUpdatable = function () {
  30182. return this._updatable;
  30183. };
  30184. /**
  30185. * Gets current buffer's data
  30186. * @returns a DataArray or null
  30187. */
  30188. Buffer.prototype.getData = function () {
  30189. return this._data;
  30190. };
  30191. /**
  30192. * Gets underlying native buffer
  30193. * @returns underlying native buffer
  30194. */
  30195. Buffer.prototype.getBuffer = function () {
  30196. return this._buffer;
  30197. };
  30198. /**
  30199. * Gets the stride in float32 units (i.e. byte stride / 4).
  30200. * May not be an integer if the byte stride is not divisible by 4.
  30201. * DEPRECATED. Use byteStride instead.
  30202. * @returns the stride in float32 units
  30203. */
  30204. Buffer.prototype.getStrideSize = function () {
  30205. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30206. };
  30207. // Methods
  30208. /**
  30209. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30210. * @param data defines the data to store
  30211. */
  30212. Buffer.prototype.create = function (data) {
  30213. if (data === void 0) { data = null; }
  30214. if (!data && this._buffer) {
  30215. return; // nothing to do
  30216. }
  30217. data = data || this._data;
  30218. if (!data) {
  30219. return;
  30220. }
  30221. if (!this._buffer) { // create buffer
  30222. if (this._updatable) {
  30223. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30224. this._data = data;
  30225. }
  30226. else {
  30227. this._buffer = this._engine.createVertexBuffer(data);
  30228. }
  30229. }
  30230. else if (this._updatable) { // update buffer
  30231. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30232. this._data = data;
  30233. }
  30234. };
  30235. /** @hidden */
  30236. Buffer.prototype._rebuild = function () {
  30237. this._buffer = null;
  30238. this.create(this._data);
  30239. };
  30240. /**
  30241. * Update current buffer data
  30242. * @param data defines the data to store
  30243. */
  30244. Buffer.prototype.update = function (data) {
  30245. this.create(data);
  30246. };
  30247. /**
  30248. * Updates the data directly.
  30249. * @param data the new data
  30250. * @param offset the new offset
  30251. * @param vertexCount the vertex count (optional)
  30252. * @param useBytes set to true if the offset is in bytes
  30253. */
  30254. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30255. if (useBytes === void 0) { useBytes = false; }
  30256. if (!this._buffer) {
  30257. return;
  30258. }
  30259. if (this._updatable) { // update buffer
  30260. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30261. this._data = null;
  30262. }
  30263. };
  30264. /**
  30265. * Release all resources
  30266. */
  30267. Buffer.prototype.dispose = function () {
  30268. if (!this._buffer) {
  30269. return;
  30270. }
  30271. if (this._engine._releaseBuffer(this._buffer)) {
  30272. this._buffer = null;
  30273. }
  30274. };
  30275. return Buffer;
  30276. }());
  30277. BABYLON.Buffer = Buffer;
  30278. })(BABYLON || (BABYLON = {}));
  30279. //# sourceMappingURL=babylon.buffer.js.map
  30280. var BABYLON;
  30281. (function (BABYLON) {
  30282. /**
  30283. * Specialized buffer used to store vertex data
  30284. */
  30285. var VertexBuffer = /** @class */ (function () {
  30286. /**
  30287. * Constructor
  30288. * @param engine the engine
  30289. * @param data the data to use for this vertex buffer
  30290. * @param kind the vertex buffer kind
  30291. * @param updatable whether the data is updatable
  30292. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30293. * @param stride the stride (optional)
  30294. * @param instanced whether the buffer is instanced (optional)
  30295. * @param offset the offset of the data (optional)
  30296. * @param size the number of components (optional)
  30297. * @param type the type of the component (optional)
  30298. * @param normalized whether the data contains normalized data (optional)
  30299. * @param useBytes set to true if stride and offset are in bytes (optional)
  30300. */
  30301. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30302. if (normalized === void 0) { normalized = false; }
  30303. if (useBytes === void 0) { useBytes = false; }
  30304. if (data instanceof BABYLON.Buffer) {
  30305. this._buffer = data;
  30306. this._ownsBuffer = false;
  30307. }
  30308. else {
  30309. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30310. this._ownsBuffer = true;
  30311. }
  30312. this._kind = kind;
  30313. if (type == undefined) {
  30314. var data_1 = this.getData();
  30315. this.type = VertexBuffer.FLOAT;
  30316. if (data_1 instanceof Int8Array) {
  30317. this.type = VertexBuffer.BYTE;
  30318. }
  30319. else if (data_1 instanceof Uint8Array) {
  30320. this.type = VertexBuffer.UNSIGNED_BYTE;
  30321. }
  30322. else if (data_1 instanceof Int16Array) {
  30323. this.type = VertexBuffer.SHORT;
  30324. }
  30325. else if (data_1 instanceof Uint16Array) {
  30326. this.type = VertexBuffer.UNSIGNED_SHORT;
  30327. }
  30328. else if (data_1 instanceof Int32Array) {
  30329. this.type = VertexBuffer.INT;
  30330. }
  30331. else if (data_1 instanceof Uint32Array) {
  30332. this.type = VertexBuffer.UNSIGNED_INT;
  30333. }
  30334. }
  30335. else {
  30336. this.type = type;
  30337. }
  30338. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30339. if (useBytes) {
  30340. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30341. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30342. this.byteOffset = offset || 0;
  30343. }
  30344. else {
  30345. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30346. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30347. this.byteOffset = (offset || 0) * typeByteLength;
  30348. }
  30349. this.normalized = normalized;
  30350. this._instanced = instanced !== undefined ? instanced : false;
  30351. this._instanceDivisor = instanced ? 1 : 0;
  30352. }
  30353. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30354. /**
  30355. * Gets or sets the instance divisor when in instanced mode
  30356. */
  30357. get: function () {
  30358. return this._instanceDivisor;
  30359. },
  30360. set: function (value) {
  30361. this._instanceDivisor = value;
  30362. if (value == 0) {
  30363. this._instanced = false;
  30364. }
  30365. else {
  30366. this._instanced = true;
  30367. }
  30368. },
  30369. enumerable: true,
  30370. configurable: true
  30371. });
  30372. /** @hidden */
  30373. VertexBuffer.prototype._rebuild = function () {
  30374. if (!this._buffer) {
  30375. return;
  30376. }
  30377. this._buffer._rebuild();
  30378. };
  30379. /**
  30380. * Returns the kind of the VertexBuffer (string)
  30381. * @returns a string
  30382. */
  30383. VertexBuffer.prototype.getKind = function () {
  30384. return this._kind;
  30385. };
  30386. // Properties
  30387. /**
  30388. * Gets a boolean indicating if the VertexBuffer is updatable?
  30389. * @returns true if the buffer is updatable
  30390. */
  30391. VertexBuffer.prototype.isUpdatable = function () {
  30392. return this._buffer.isUpdatable();
  30393. };
  30394. /**
  30395. * Gets current buffer's data
  30396. * @returns a DataArray or null
  30397. */
  30398. VertexBuffer.prototype.getData = function () {
  30399. return this._buffer.getData();
  30400. };
  30401. /**
  30402. * Gets underlying native buffer
  30403. * @returns underlying native buffer
  30404. */
  30405. VertexBuffer.prototype.getBuffer = function () {
  30406. return this._buffer.getBuffer();
  30407. };
  30408. /**
  30409. * Gets the stride in float32 units (i.e. byte stride / 4).
  30410. * May not be an integer if the byte stride is not divisible by 4.
  30411. * DEPRECATED. Use byteStride instead.
  30412. * @returns the stride in float32 units
  30413. */
  30414. VertexBuffer.prototype.getStrideSize = function () {
  30415. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30416. };
  30417. /**
  30418. * Returns the offset as a multiple of the type byte length.
  30419. * DEPRECATED. Use byteOffset instead.
  30420. * @returns the offset in bytes
  30421. */
  30422. VertexBuffer.prototype.getOffset = function () {
  30423. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30424. };
  30425. /**
  30426. * Returns the number of components per vertex attribute (integer)
  30427. * @returns the size in float
  30428. */
  30429. VertexBuffer.prototype.getSize = function () {
  30430. return this._size;
  30431. };
  30432. /**
  30433. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30434. * @returns true if this buffer is instanced
  30435. */
  30436. VertexBuffer.prototype.getIsInstanced = function () {
  30437. return this._instanced;
  30438. };
  30439. /**
  30440. * Returns the instancing divisor, zero for non-instanced (integer).
  30441. * @returns a number
  30442. */
  30443. VertexBuffer.prototype.getInstanceDivisor = function () {
  30444. return this._instanceDivisor;
  30445. };
  30446. // Methods
  30447. /**
  30448. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30449. * @param data defines the data to store
  30450. */
  30451. VertexBuffer.prototype.create = function (data) {
  30452. this._buffer.create(data);
  30453. };
  30454. /**
  30455. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30456. * This function will create a new buffer if the current one is not updatable
  30457. * @param data defines the data to store
  30458. */
  30459. VertexBuffer.prototype.update = function (data) {
  30460. this._buffer.update(data);
  30461. };
  30462. /**
  30463. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30464. * Returns the directly updated WebGLBuffer.
  30465. * @param data the new data
  30466. * @param offset the new offset
  30467. * @param useBytes set to true if the offset is in bytes
  30468. */
  30469. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30470. if (useBytes === void 0) { useBytes = false; }
  30471. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30472. };
  30473. /**
  30474. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30475. */
  30476. VertexBuffer.prototype.dispose = function () {
  30477. if (this._ownsBuffer) {
  30478. this._buffer.dispose();
  30479. }
  30480. };
  30481. /**
  30482. * Enumerates each value of this vertex buffer as numbers.
  30483. * @param count the number of values to enumerate
  30484. * @param callback the callback function called for each value
  30485. */
  30486. VertexBuffer.prototype.forEach = function (count, callback) {
  30487. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30488. };
  30489. /**
  30490. * Deduces the stride given a kind.
  30491. * @param kind The kind string to deduce
  30492. * @returns The deduced stride
  30493. */
  30494. VertexBuffer.DeduceStride = function (kind) {
  30495. switch (kind) {
  30496. case VertexBuffer.UVKind:
  30497. case VertexBuffer.UV2Kind:
  30498. case VertexBuffer.UV3Kind:
  30499. case VertexBuffer.UV4Kind:
  30500. case VertexBuffer.UV5Kind:
  30501. case VertexBuffer.UV6Kind:
  30502. return 2;
  30503. case VertexBuffer.NormalKind:
  30504. case VertexBuffer.PositionKind:
  30505. return 3;
  30506. case VertexBuffer.ColorKind:
  30507. case VertexBuffer.MatricesIndicesKind:
  30508. case VertexBuffer.MatricesIndicesExtraKind:
  30509. case VertexBuffer.MatricesWeightsKind:
  30510. case VertexBuffer.MatricesWeightsExtraKind:
  30511. case VertexBuffer.TangentKind:
  30512. return 4;
  30513. default:
  30514. throw new Error("Invalid kind '" + kind + "'");
  30515. }
  30516. };
  30517. /**
  30518. * Gets the byte length of the given type.
  30519. * @param type the type
  30520. * @returns the number of bytes
  30521. */
  30522. VertexBuffer.GetTypeByteLength = function (type) {
  30523. switch (type) {
  30524. case VertexBuffer.BYTE:
  30525. case VertexBuffer.UNSIGNED_BYTE:
  30526. return 1;
  30527. case VertexBuffer.SHORT:
  30528. case VertexBuffer.UNSIGNED_SHORT:
  30529. return 2;
  30530. case VertexBuffer.INT:
  30531. case VertexBuffer.FLOAT:
  30532. return 4;
  30533. default:
  30534. throw new Error("Invalid type '" + type + "'");
  30535. }
  30536. };
  30537. /**
  30538. * Enumerates each value of the given parameters as numbers.
  30539. * @param data the data to enumerate
  30540. * @param byteOffset the byte offset of the data
  30541. * @param byteStride the byte stride of the data
  30542. * @param componentCount the number of components per element
  30543. * @param componentType the type of the component
  30544. * @param count the total number of components
  30545. * @param normalized whether the data is normalized
  30546. * @param callback the callback function called for each value
  30547. */
  30548. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30549. if (data instanceof Array) {
  30550. var offset = byteOffset / 4;
  30551. var stride = byteStride / 4;
  30552. for (var index = 0; index < count; index += componentCount) {
  30553. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30554. callback(data[offset + componentIndex], index + componentIndex);
  30555. }
  30556. offset += stride;
  30557. }
  30558. }
  30559. else {
  30560. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30561. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30562. for (var index = 0; index < count; index += componentCount) {
  30563. var componentByteOffset = byteOffset;
  30564. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30565. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30566. callback(value, index + componentIndex);
  30567. componentByteOffset += componentByteLength;
  30568. }
  30569. byteOffset += byteStride;
  30570. }
  30571. }
  30572. };
  30573. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30574. switch (type) {
  30575. case VertexBuffer.BYTE: {
  30576. var value = dataView.getInt8(byteOffset);
  30577. if (normalized) {
  30578. value = Math.max(value / 127, -1);
  30579. }
  30580. return value;
  30581. }
  30582. case VertexBuffer.UNSIGNED_BYTE: {
  30583. var value = dataView.getUint8(byteOffset);
  30584. if (normalized) {
  30585. value = value / 255;
  30586. }
  30587. return value;
  30588. }
  30589. case VertexBuffer.SHORT: {
  30590. var value = dataView.getInt16(byteOffset, true);
  30591. if (normalized) {
  30592. value = Math.max(value / 16383, -1);
  30593. }
  30594. return value;
  30595. }
  30596. case VertexBuffer.UNSIGNED_SHORT: {
  30597. var value = dataView.getUint16(byteOffset, true);
  30598. if (normalized) {
  30599. value = value / 65535;
  30600. }
  30601. return value;
  30602. }
  30603. case VertexBuffer.FLOAT: {
  30604. return dataView.getFloat32(byteOffset, true);
  30605. }
  30606. default: {
  30607. throw new Error("Invalid component type " + type);
  30608. }
  30609. }
  30610. };
  30611. /**
  30612. * The byte type.
  30613. */
  30614. VertexBuffer.BYTE = 5120;
  30615. /**
  30616. * The unsigned byte type.
  30617. */
  30618. VertexBuffer.UNSIGNED_BYTE = 5121;
  30619. /**
  30620. * The short type.
  30621. */
  30622. VertexBuffer.SHORT = 5122;
  30623. /**
  30624. * The unsigned short type.
  30625. */
  30626. VertexBuffer.UNSIGNED_SHORT = 5123;
  30627. /**
  30628. * The integer type.
  30629. */
  30630. VertexBuffer.INT = 5124;
  30631. /**
  30632. * The unsigned integer type.
  30633. */
  30634. VertexBuffer.UNSIGNED_INT = 5125;
  30635. /**
  30636. * The float type.
  30637. */
  30638. VertexBuffer.FLOAT = 5126;
  30639. // Enums
  30640. /**
  30641. * Positions
  30642. */
  30643. VertexBuffer.PositionKind = "position";
  30644. /**
  30645. * Normals
  30646. */
  30647. VertexBuffer.NormalKind = "normal";
  30648. /**
  30649. * Tangents
  30650. */
  30651. VertexBuffer.TangentKind = "tangent";
  30652. /**
  30653. * Texture coordinates
  30654. */
  30655. VertexBuffer.UVKind = "uv";
  30656. /**
  30657. * Texture coordinates 2
  30658. */
  30659. VertexBuffer.UV2Kind = "uv2";
  30660. /**
  30661. * Texture coordinates 3
  30662. */
  30663. VertexBuffer.UV3Kind = "uv3";
  30664. /**
  30665. * Texture coordinates 4
  30666. */
  30667. VertexBuffer.UV4Kind = "uv4";
  30668. /**
  30669. * Texture coordinates 5
  30670. */
  30671. VertexBuffer.UV5Kind = "uv5";
  30672. /**
  30673. * Texture coordinates 6
  30674. */
  30675. VertexBuffer.UV6Kind = "uv6";
  30676. /**
  30677. * Colors
  30678. */
  30679. VertexBuffer.ColorKind = "color";
  30680. /**
  30681. * Matrix indices (for bones)
  30682. */
  30683. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30684. /**
  30685. * Matrix weights (for bones)
  30686. */
  30687. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30688. /**
  30689. * Additional matrix indices (for bones)
  30690. */
  30691. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30692. /**
  30693. * Additional matrix weights (for bones)
  30694. */
  30695. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30696. return VertexBuffer;
  30697. }());
  30698. BABYLON.VertexBuffer = VertexBuffer;
  30699. })(BABYLON || (BABYLON = {}));
  30700. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30701. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30702. var BABYLON;
  30703. (function (BABYLON) {
  30704. /**
  30705. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30706. */
  30707. var DummyInternalTextureTracker = /** @class */ (function () {
  30708. function DummyInternalTextureTracker() {
  30709. /**
  30710. * Gets or set the previous tracker in the list
  30711. */
  30712. this.previous = null;
  30713. /**
  30714. * Gets or set the next tracker in the list
  30715. */
  30716. this.next = null;
  30717. }
  30718. return DummyInternalTextureTracker;
  30719. }());
  30720. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30721. })(BABYLON || (BABYLON = {}));
  30722. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30723. var BABYLON;
  30724. (function (BABYLON) {
  30725. /**
  30726. * Class used to store data associated with WebGL texture data for the engine
  30727. * This class should not be used directly
  30728. */
  30729. var InternalTexture = /** @class */ (function () {
  30730. /**
  30731. * Creates a new InternalTexture
  30732. * @param engine defines the engine to use
  30733. * @param dataSource defines the type of data that will be used
  30734. * @param delayAllocation if the texture allocation should be delayed (default: false)
  30735. */
  30736. function InternalTexture(engine, dataSource, delayAllocation) {
  30737. if (delayAllocation === void 0) { delayAllocation = false; }
  30738. /**
  30739. * Observable called when the texture is loaded
  30740. */
  30741. this.onLoadedObservable = new BABYLON.Observable();
  30742. /**
  30743. * Gets or set the previous tracker in the list
  30744. */
  30745. this.previous = null;
  30746. /**
  30747. * Gets or set the next tracker in the list
  30748. */
  30749. this.next = null;
  30750. // Private
  30751. /** @hidden */
  30752. this._initialSlot = -1;
  30753. /** @hidden */
  30754. this._designatedSlot = -1;
  30755. /** @hidden */
  30756. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30757. /** @hidden */
  30758. this._comparisonFunction = 0;
  30759. /** @hidden */
  30760. this._sphericalPolynomial = null;
  30761. /** @hidden */
  30762. this._lodGenerationScale = 0;
  30763. /** @hidden */
  30764. this._lodGenerationOffset = 0;
  30765. /** @hidden */
  30766. this._isRGBD = false;
  30767. /** @hidden */
  30768. this._references = 1;
  30769. this._engine = engine;
  30770. this._dataSource = dataSource;
  30771. if (!delayAllocation) {
  30772. this._webGLTexture = engine._createTexture();
  30773. }
  30774. }
  30775. /**
  30776. * Gets the Engine the texture belongs to.
  30777. * @returns The babylon engine
  30778. */
  30779. InternalTexture.prototype.getEngine = function () {
  30780. return this._engine;
  30781. };
  30782. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30783. /**
  30784. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30785. */
  30786. get: function () {
  30787. return this._dataSource;
  30788. },
  30789. enumerable: true,
  30790. configurable: true
  30791. });
  30792. /**
  30793. * Increments the number of references (ie. the number of Texture that point to it)
  30794. */
  30795. InternalTexture.prototype.incrementReferences = function () {
  30796. this._references++;
  30797. };
  30798. /**
  30799. * Change the size of the texture (not the size of the content)
  30800. * @param width defines the new width
  30801. * @param height defines the new height
  30802. * @param depth defines the new depth (1 by default)
  30803. */
  30804. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30805. if (depth === void 0) { depth = 1; }
  30806. this.width = width;
  30807. this.height = height;
  30808. this.depth = depth;
  30809. this.baseWidth = width;
  30810. this.baseHeight = height;
  30811. this.baseDepth = depth;
  30812. this._size = width * height * depth;
  30813. };
  30814. /** @hidden */
  30815. InternalTexture.prototype._rebuild = function () {
  30816. var _this = this;
  30817. var proxy;
  30818. this.isReady = false;
  30819. this._cachedCoordinatesMode = null;
  30820. this._cachedWrapU = null;
  30821. this._cachedWrapV = null;
  30822. this._cachedAnisotropicFilteringLevel = null;
  30823. switch (this._dataSource) {
  30824. case InternalTexture.DATASOURCE_TEMP:
  30825. return;
  30826. case InternalTexture.DATASOURCE_URL:
  30827. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30828. _this.isReady = true;
  30829. }, null, this._buffer, undefined, this.format);
  30830. proxy._swapAndDie(this);
  30831. return;
  30832. case InternalTexture.DATASOURCE_RAW:
  30833. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30834. proxy._swapAndDie(this);
  30835. this.isReady = true;
  30836. return;
  30837. case InternalTexture.DATASOURCE_RAW3D:
  30838. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30839. proxy._swapAndDie(this);
  30840. this.isReady = true;
  30841. return;
  30842. case InternalTexture.DATASOURCE_DYNAMIC:
  30843. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30844. proxy._swapAndDie(this);
  30845. // The engine will make sure to update content so no need to flag it as isReady = true
  30846. return;
  30847. case InternalTexture.DATASOURCE_RENDERTARGET:
  30848. var options = new BABYLON.RenderTargetCreationOptions();
  30849. options.generateDepthBuffer = this._generateDepthBuffer;
  30850. options.generateMipMaps = this.generateMipMaps;
  30851. options.generateStencilBuffer = this._generateStencilBuffer;
  30852. options.samplingMode = this.samplingMode;
  30853. options.type = this.type;
  30854. if (this.isCube) {
  30855. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30856. }
  30857. else {
  30858. var size = {
  30859. width: this.width,
  30860. height: this.height
  30861. };
  30862. proxy = this._engine.createRenderTargetTexture(size, options);
  30863. }
  30864. proxy._swapAndDie(this);
  30865. this.isReady = true;
  30866. return;
  30867. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30868. var depthTextureOptions = {
  30869. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30870. comparisonFunction: this._comparisonFunction,
  30871. generateStencil: this._generateStencilBuffer,
  30872. isCube: this.isCube
  30873. };
  30874. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30875. proxy._swapAndDie(this);
  30876. this.isReady = true;
  30877. return;
  30878. case InternalTexture.DATASOURCE_CUBE:
  30879. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30880. _this.isReady = true;
  30881. }, null, this.format, this._extension);
  30882. proxy._swapAndDie(this);
  30883. return;
  30884. case InternalTexture.DATASOURCE_CUBERAW:
  30885. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30886. proxy._swapAndDie(this);
  30887. this.isReady = true;
  30888. return;
  30889. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30890. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30891. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30892. _this.isReady = true;
  30893. });
  30894. proxy._swapAndDie(this);
  30895. return;
  30896. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30897. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30898. if (proxy) {
  30899. proxy._swapAndDie(_this);
  30900. }
  30901. _this.isReady = true;
  30902. }, null, this.format, this._extension);
  30903. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30904. return;
  30905. }
  30906. };
  30907. /** @hidden */
  30908. InternalTexture.prototype._swapAndDie = function (target) {
  30909. target._webGLTexture = this._webGLTexture;
  30910. if (this._framebuffer) {
  30911. target._framebuffer = this._framebuffer;
  30912. }
  30913. if (this._depthStencilBuffer) {
  30914. target._depthStencilBuffer = this._depthStencilBuffer;
  30915. }
  30916. if (this._lodTextureHigh) {
  30917. if (target._lodTextureHigh) {
  30918. target._lodTextureHigh.dispose();
  30919. }
  30920. target._lodTextureHigh = this._lodTextureHigh;
  30921. }
  30922. if (this._lodTextureMid) {
  30923. if (target._lodTextureMid) {
  30924. target._lodTextureMid.dispose();
  30925. }
  30926. target._lodTextureMid = this._lodTextureMid;
  30927. }
  30928. if (this._lodTextureLow) {
  30929. if (target._lodTextureLow) {
  30930. target._lodTextureLow.dispose();
  30931. }
  30932. target._lodTextureLow = this._lodTextureLow;
  30933. }
  30934. var cache = this._engine.getLoadedTexturesCache();
  30935. var index = cache.indexOf(this);
  30936. if (index !== -1) {
  30937. cache.splice(index, 1);
  30938. }
  30939. };
  30940. /**
  30941. * Dispose the current allocated resources
  30942. */
  30943. InternalTexture.prototype.dispose = function () {
  30944. if (!this._webGLTexture) {
  30945. return;
  30946. }
  30947. this._references--;
  30948. if (this._references === 0) {
  30949. this._engine._releaseTexture(this);
  30950. this._webGLTexture = null;
  30951. this.previous = null;
  30952. this.next = null;
  30953. }
  30954. };
  30955. /**
  30956. * The source of the texture data is unknown
  30957. */
  30958. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30959. /**
  30960. * Texture data comes from an URL
  30961. */
  30962. InternalTexture.DATASOURCE_URL = 1;
  30963. /**
  30964. * Texture data is only used for temporary storage
  30965. */
  30966. InternalTexture.DATASOURCE_TEMP = 2;
  30967. /**
  30968. * Texture data comes from raw data (ArrayBuffer)
  30969. */
  30970. InternalTexture.DATASOURCE_RAW = 3;
  30971. /**
  30972. * Texture content is dynamic (video or dynamic texture)
  30973. */
  30974. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30975. /**
  30976. * Texture content is generated by rendering to it
  30977. */
  30978. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30979. /**
  30980. * Texture content is part of a multi render target process
  30981. */
  30982. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30983. /**
  30984. * Texture data comes from a cube data file
  30985. */
  30986. InternalTexture.DATASOURCE_CUBE = 7;
  30987. /**
  30988. * Texture data comes from a raw cube data
  30989. */
  30990. InternalTexture.DATASOURCE_CUBERAW = 8;
  30991. /**
  30992. * Texture data come from a prefiltered cube data file
  30993. */
  30994. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30995. /**
  30996. * Texture content is raw 3D data
  30997. */
  30998. InternalTexture.DATASOURCE_RAW3D = 10;
  30999. /**
  31000. * Texture content is a depth texture
  31001. */
  31002. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  31003. /**
  31004. * Texture data comes from a raw cube data encoded with RGBD
  31005. */
  31006. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  31007. return InternalTexture;
  31008. }());
  31009. BABYLON.InternalTexture = InternalTexture;
  31010. })(BABYLON || (BABYLON = {}));
  31011. //# sourceMappingURL=babylon.internalTexture.js.map
  31012. var BABYLON;
  31013. (function (BABYLON) {
  31014. /**
  31015. * Base class of all the textures in babylon.
  31016. * It groups all the common properties the materials, post process, lights... might need
  31017. * in order to make a correct use of the texture.
  31018. */
  31019. var BaseTexture = /** @class */ (function () {
  31020. /**
  31021. * Instantiates a new BaseTexture.
  31022. * Base class of all the textures in babylon.
  31023. * It groups all the common properties the materials, post process, lights... might need
  31024. * in order to make a correct use of the texture.
  31025. * @param scene Define the scene the texture blongs to
  31026. */
  31027. function BaseTexture(scene) {
  31028. this._hasAlpha = false;
  31029. /**
  31030. * Defines if the alpha value should be determined via the rgb values.
  31031. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  31032. */
  31033. this.getAlphaFromRGB = false;
  31034. /**
  31035. * Intensity or strength of the texture.
  31036. * It is commonly used by materials to fine tune the intensity of the texture
  31037. */
  31038. this.level = 1;
  31039. /**
  31040. * Define the UV chanel to use starting from 0 and defaulting to 0.
  31041. * This is part of the texture as textures usually maps to one uv set.
  31042. */
  31043. this.coordinatesIndex = 0;
  31044. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  31045. /**
  31046. * | Value | Type | Description |
  31047. * | ----- | ------------------ | ----------- |
  31048. * | 0 | CLAMP_ADDRESSMODE | |
  31049. * | 1 | WRAP_ADDRESSMODE | |
  31050. * | 2 | MIRROR_ADDRESSMODE | |
  31051. */
  31052. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31053. /**
  31054. * | Value | Type | Description |
  31055. * | ----- | ------------------ | ----------- |
  31056. * | 0 | CLAMP_ADDRESSMODE | |
  31057. * | 1 | WRAP_ADDRESSMODE | |
  31058. * | 2 | MIRROR_ADDRESSMODE | |
  31059. */
  31060. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31061. /**
  31062. * | Value | Type | Description |
  31063. * | ----- | ------------------ | ----------- |
  31064. * | 0 | CLAMP_ADDRESSMODE | |
  31065. * | 1 | WRAP_ADDRESSMODE | |
  31066. * | 2 | MIRROR_ADDRESSMODE | |
  31067. */
  31068. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31069. /**
  31070. * With compliant hardware and browser (supporting anisotropic filtering)
  31071. * this defines the level of anisotropic filtering in the texture.
  31072. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31073. */
  31074. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31075. /**
  31076. * Define if the texture is a cube texture or if false a 2d texture.
  31077. */
  31078. this.isCube = false;
  31079. /**
  31080. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31081. */
  31082. this.is3D = false;
  31083. /**
  31084. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31085. * HDR texture are usually stored in linear space.
  31086. * This only impacts the PBR and Background materials
  31087. */
  31088. this.gammaSpace = true;
  31089. /**
  31090. * Is Z inverted in the texture (useful in a cube texture).
  31091. */
  31092. this.invertZ = false;
  31093. /**
  31094. * @hidden
  31095. */
  31096. this.lodLevelInAlpha = false;
  31097. /**
  31098. * Define if the texture is a render target.
  31099. */
  31100. this.isRenderTarget = false;
  31101. /**
  31102. * Define the list of animation attached to the texture.
  31103. */
  31104. this.animations = new Array();
  31105. /**
  31106. * An event triggered when the texture is disposed.
  31107. */
  31108. this.onDisposeObservable = new BABYLON.Observable();
  31109. /**
  31110. * Define the current state of the loading sequence when in delayed load mode.
  31111. */
  31112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31113. this._cachedSize = BABYLON.Size.Zero();
  31114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31115. if (this._scene) {
  31116. this._scene.textures.push(this);
  31117. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  31118. }
  31119. this._uid = null;
  31120. }
  31121. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31122. get: function () {
  31123. return this._hasAlpha;
  31124. },
  31125. /**
  31126. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31127. */
  31128. set: function (value) {
  31129. if (this._hasAlpha === value) {
  31130. return;
  31131. }
  31132. this._hasAlpha = value;
  31133. if (this._scene) {
  31134. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31135. }
  31136. },
  31137. enumerable: true,
  31138. configurable: true
  31139. });
  31140. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31141. get: function () {
  31142. return this._coordinatesMode;
  31143. },
  31144. /**
  31145. * How a texture is mapped.
  31146. *
  31147. * | Value | Type | Description |
  31148. * | ----- | ----------------------------------- | ----------- |
  31149. * | 0 | EXPLICIT_MODE | |
  31150. * | 1 | SPHERICAL_MODE | |
  31151. * | 2 | PLANAR_MODE | |
  31152. * | 3 | CUBIC_MODE | |
  31153. * | 4 | PROJECTION_MODE | |
  31154. * | 5 | SKYBOX_MODE | |
  31155. * | 6 | INVCUBIC_MODE | |
  31156. * | 7 | EQUIRECTANGULAR_MODE | |
  31157. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31158. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31159. */
  31160. set: function (value) {
  31161. if (this._coordinatesMode === value) {
  31162. return;
  31163. }
  31164. this._coordinatesMode = value;
  31165. if (this._scene) {
  31166. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31167. }
  31168. },
  31169. enumerable: true,
  31170. configurable: true
  31171. });
  31172. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31173. /**
  31174. * Gets whether or not the texture contains RGBD data.
  31175. */
  31176. get: function () {
  31177. return this._texture != null && this._texture._isRGBD;
  31178. },
  31179. enumerable: true,
  31180. configurable: true
  31181. });
  31182. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31183. /**
  31184. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31185. */
  31186. get: function () {
  31187. if (this._texture) {
  31188. return this._texture._lodGenerationOffset;
  31189. }
  31190. return 0.0;
  31191. },
  31192. set: function (value) {
  31193. if (this._texture) {
  31194. this._texture._lodGenerationOffset = value;
  31195. }
  31196. },
  31197. enumerable: true,
  31198. configurable: true
  31199. });
  31200. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31201. /**
  31202. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31203. */
  31204. get: function () {
  31205. if (this._texture) {
  31206. return this._texture._lodGenerationScale;
  31207. }
  31208. return 0.0;
  31209. },
  31210. set: function (value) {
  31211. if (this._texture) {
  31212. this._texture._lodGenerationScale = value;
  31213. }
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(BaseTexture.prototype, "uid", {
  31219. /**
  31220. * Define the unique id of the texture in the scene.
  31221. */
  31222. get: function () {
  31223. if (!this._uid) {
  31224. this._uid = BABYLON.Tools.RandomId();
  31225. }
  31226. return this._uid;
  31227. },
  31228. enumerable: true,
  31229. configurable: true
  31230. });
  31231. /**
  31232. * Return a string representation of the texture.
  31233. * @returns the texture as a string
  31234. */
  31235. BaseTexture.prototype.toString = function () {
  31236. return this.name;
  31237. };
  31238. /**
  31239. * Get the class name of the texture.
  31240. * @returns "BaseTexture"
  31241. */
  31242. BaseTexture.prototype.getClassName = function () {
  31243. return "BaseTexture";
  31244. };
  31245. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31246. /**
  31247. * Callback triggered when the texture has been disposed.
  31248. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31249. */
  31250. set: function (callback) {
  31251. if (this._onDisposeObserver) {
  31252. this.onDisposeObservable.remove(this._onDisposeObserver);
  31253. }
  31254. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31255. },
  31256. enumerable: true,
  31257. configurable: true
  31258. });
  31259. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31260. /**
  31261. * Define if the texture is preventinga material to render or not.
  31262. * If not and the texture is not ready, the engine will use a default black texture instead.
  31263. */
  31264. get: function () {
  31265. return true;
  31266. },
  31267. enumerable: true,
  31268. configurable: true
  31269. });
  31270. /**
  31271. * Get the scene the texture belongs to.
  31272. * @returns the scene or null if undefined
  31273. */
  31274. BaseTexture.prototype.getScene = function () {
  31275. return this._scene;
  31276. };
  31277. /**
  31278. * Get the texture transform matrix used to offset tile the texture for istance.
  31279. * @returns the transformation matrix
  31280. */
  31281. BaseTexture.prototype.getTextureMatrix = function () {
  31282. return BABYLON.Matrix.IdentityReadOnly;
  31283. };
  31284. /**
  31285. * Get the texture reflection matrix used to rotate/transform the reflection.
  31286. * @returns the reflection matrix
  31287. */
  31288. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31289. return BABYLON.Matrix.IdentityReadOnly;
  31290. };
  31291. /**
  31292. * Get the underlying lower level texture from Babylon.
  31293. * @returns the insternal texture
  31294. */
  31295. BaseTexture.prototype.getInternalTexture = function () {
  31296. return this._texture;
  31297. };
  31298. /**
  31299. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31300. * @returns true if ready or not blocking
  31301. */
  31302. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31303. return !this.isBlocking || this.isReady();
  31304. };
  31305. /**
  31306. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31307. * @returns true if fully ready
  31308. */
  31309. BaseTexture.prototype.isReady = function () {
  31310. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31311. this.delayLoad();
  31312. return false;
  31313. }
  31314. if (this._texture) {
  31315. return this._texture.isReady;
  31316. }
  31317. return false;
  31318. };
  31319. /**
  31320. * Get the size of the texture.
  31321. * @returns the texture size.
  31322. */
  31323. BaseTexture.prototype.getSize = function () {
  31324. if (this._texture) {
  31325. if (this._texture.width) {
  31326. this._cachedSize.width = this._texture.width;
  31327. this._cachedSize.height = this._texture.height;
  31328. return this._cachedSize;
  31329. }
  31330. if (this._texture._size) {
  31331. this._cachedSize.width = this._texture._size;
  31332. this._cachedSize.height = this._texture._size;
  31333. return this._cachedSize;
  31334. }
  31335. }
  31336. return this._cachedSize;
  31337. };
  31338. /**
  31339. * Get the base size of the texture.
  31340. * It can be different from the size if the texture has been resized for POT for instance
  31341. * @returns the base size
  31342. */
  31343. BaseTexture.prototype.getBaseSize = function () {
  31344. if (!this.isReady() || !this._texture) {
  31345. return BABYLON.Size.Zero();
  31346. }
  31347. if (this._texture._size) {
  31348. return new BABYLON.Size(this._texture._size, this._texture._size);
  31349. }
  31350. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31351. };
  31352. /**
  31353. * Scales the texture if is `canRescale()`
  31354. * @param ratio the resize factor we want to use to rescale
  31355. */
  31356. BaseTexture.prototype.scale = function (ratio) {
  31357. };
  31358. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31359. /**
  31360. * Get if the texture can rescale.
  31361. */
  31362. get: function () {
  31363. return false;
  31364. },
  31365. enumerable: true,
  31366. configurable: true
  31367. });
  31368. /** @hidden */
  31369. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31370. if (!this._scene) {
  31371. return null;
  31372. }
  31373. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31374. for (var index = 0; index < texturesCache.length; index++) {
  31375. var texturesCacheEntry = texturesCache[index];
  31376. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31377. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31378. texturesCacheEntry.incrementReferences();
  31379. return texturesCacheEntry;
  31380. }
  31381. }
  31382. }
  31383. return null;
  31384. };
  31385. /** @hidden */
  31386. BaseTexture.prototype._rebuild = function () {
  31387. };
  31388. /**
  31389. * Triggers the load sequence in delayed load mode.
  31390. */
  31391. BaseTexture.prototype.delayLoad = function () {
  31392. };
  31393. /**
  31394. * Clones the texture.
  31395. * @returns the cloned texture
  31396. */
  31397. BaseTexture.prototype.clone = function () {
  31398. return null;
  31399. };
  31400. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31401. /**
  31402. * Get the texture underlying type (INT, FLOAT...)
  31403. */
  31404. get: function () {
  31405. if (!this._texture) {
  31406. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31407. }
  31408. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31409. },
  31410. enumerable: true,
  31411. configurable: true
  31412. });
  31413. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31414. /**
  31415. * Get the texture underlying format (RGB, RGBA...)
  31416. */
  31417. get: function () {
  31418. if (!this._texture) {
  31419. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31420. }
  31421. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31422. },
  31423. enumerable: true,
  31424. configurable: true
  31425. });
  31426. /**
  31427. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31428. * This will returns an RGBA array buffer containing either in values (0-255) or
  31429. * float values (0-1) depending of the underlying buffer type.
  31430. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31431. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31432. * @param buffer defines a user defined buffer to fill with data (can be null)
  31433. * @returns The Array buffer containing the pixels data.
  31434. */
  31435. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31436. if (faceIndex === void 0) { faceIndex = 0; }
  31437. if (level === void 0) { level = 0; }
  31438. if (buffer === void 0) { buffer = null; }
  31439. if (!this._texture) {
  31440. return null;
  31441. }
  31442. var size = this.getSize();
  31443. var width = size.width;
  31444. var height = size.height;
  31445. var scene = this.getScene();
  31446. if (!scene) {
  31447. return null;
  31448. }
  31449. var engine = scene.getEngine();
  31450. if (level != 0) {
  31451. width = width / Math.pow(2, level);
  31452. height = height / Math.pow(2, level);
  31453. width = Math.round(width);
  31454. height = Math.round(height);
  31455. }
  31456. if (this._texture.isCube) {
  31457. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31458. }
  31459. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31460. };
  31461. /**
  31462. * Release and destroy the underlying lower level texture aka internalTexture.
  31463. */
  31464. BaseTexture.prototype.releaseInternalTexture = function () {
  31465. if (this._texture) {
  31466. this._texture.dispose();
  31467. this._texture = null;
  31468. }
  31469. };
  31470. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31471. /**
  31472. * Get the polynomial representation of the texture data.
  31473. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31474. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31475. */
  31476. get: function () {
  31477. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31478. return null;
  31479. }
  31480. if (!this._texture._sphericalPolynomial) {
  31481. this._texture._sphericalPolynomial =
  31482. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31483. }
  31484. return this._texture._sphericalPolynomial;
  31485. },
  31486. set: function (value) {
  31487. if (this._texture) {
  31488. this._texture._sphericalPolynomial = value;
  31489. }
  31490. },
  31491. enumerable: true,
  31492. configurable: true
  31493. });
  31494. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31495. /** @hidden */
  31496. get: function () {
  31497. if (this._texture) {
  31498. return this._texture._lodTextureHigh;
  31499. }
  31500. return null;
  31501. },
  31502. enumerable: true,
  31503. configurable: true
  31504. });
  31505. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31506. /** @hidden */
  31507. get: function () {
  31508. if (this._texture) {
  31509. return this._texture._lodTextureMid;
  31510. }
  31511. return null;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31517. /** @hidden */
  31518. get: function () {
  31519. if (this._texture) {
  31520. return this._texture._lodTextureLow;
  31521. }
  31522. return null;
  31523. },
  31524. enumerable: true,
  31525. configurable: true
  31526. });
  31527. /**
  31528. * Dispose the texture and release its associated resources.
  31529. */
  31530. BaseTexture.prototype.dispose = function () {
  31531. if (!this._scene) {
  31532. return;
  31533. }
  31534. // Animations
  31535. this._scene.stopAnimation(this);
  31536. // Remove from scene
  31537. this._scene._removePendingData(this);
  31538. var index = this._scene.textures.indexOf(this);
  31539. if (index >= 0) {
  31540. this._scene.textures.splice(index, 1);
  31541. }
  31542. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31543. if (this._texture === undefined) {
  31544. return;
  31545. }
  31546. // Release
  31547. this.releaseInternalTexture();
  31548. // Callback
  31549. this.onDisposeObservable.notifyObservers(this);
  31550. this.onDisposeObservable.clear();
  31551. };
  31552. /**
  31553. * Serialize the texture into a JSON representation that can be parsed later on.
  31554. * @returns the JSON representation of the texture
  31555. */
  31556. BaseTexture.prototype.serialize = function () {
  31557. if (!this.name) {
  31558. return null;
  31559. }
  31560. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31561. // Animations
  31562. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31563. return serializationObject;
  31564. };
  31565. /**
  31566. * Helper function to be called back once a list of texture contains only ready textures.
  31567. * @param textures Define the list of textures to wait for
  31568. * @param callback Define the callback triggered once the entire list will be ready
  31569. */
  31570. BaseTexture.WhenAllReady = function (textures, callback) {
  31571. var numRemaining = textures.length;
  31572. if (numRemaining === 0) {
  31573. callback();
  31574. return;
  31575. }
  31576. var _loop_1 = function () {
  31577. texture = textures[i];
  31578. if (texture.isReady()) {
  31579. if (--numRemaining === 0) {
  31580. callback();
  31581. }
  31582. }
  31583. else {
  31584. onLoadObservable = texture.onLoadObservable;
  31585. var onLoadCallback_1 = function () {
  31586. onLoadObservable.removeCallback(onLoadCallback_1);
  31587. if (--numRemaining === 0) {
  31588. callback();
  31589. }
  31590. };
  31591. onLoadObservable.add(onLoadCallback_1);
  31592. }
  31593. };
  31594. var texture, onLoadObservable;
  31595. for (var i = 0; i < textures.length; i++) {
  31596. _loop_1();
  31597. }
  31598. };
  31599. /**
  31600. * Default anisotropic filtering level for the application.
  31601. * It is set to 4 as a good tradeoff between perf and quality.
  31602. */
  31603. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31604. __decorate([
  31605. BABYLON.serialize()
  31606. ], BaseTexture.prototype, "name", void 0);
  31607. __decorate([
  31608. BABYLON.serialize("hasAlpha")
  31609. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31610. __decorate([
  31611. BABYLON.serialize()
  31612. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31613. __decorate([
  31614. BABYLON.serialize()
  31615. ], BaseTexture.prototype, "level", void 0);
  31616. __decorate([
  31617. BABYLON.serialize()
  31618. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31619. __decorate([
  31620. BABYLON.serialize("coordinatesMode")
  31621. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31622. __decorate([
  31623. BABYLON.serialize()
  31624. ], BaseTexture.prototype, "wrapU", void 0);
  31625. __decorate([
  31626. BABYLON.serialize()
  31627. ], BaseTexture.prototype, "wrapV", void 0);
  31628. __decorate([
  31629. BABYLON.serialize()
  31630. ], BaseTexture.prototype, "wrapR", void 0);
  31631. __decorate([
  31632. BABYLON.serialize()
  31633. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31634. __decorate([
  31635. BABYLON.serialize()
  31636. ], BaseTexture.prototype, "isCube", void 0);
  31637. __decorate([
  31638. BABYLON.serialize()
  31639. ], BaseTexture.prototype, "is3D", void 0);
  31640. __decorate([
  31641. BABYLON.serialize()
  31642. ], BaseTexture.prototype, "gammaSpace", void 0);
  31643. __decorate([
  31644. BABYLON.serialize()
  31645. ], BaseTexture.prototype, "invertZ", void 0);
  31646. __decorate([
  31647. BABYLON.serialize()
  31648. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31649. __decorate([
  31650. BABYLON.serialize()
  31651. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31652. __decorate([
  31653. BABYLON.serialize()
  31654. ], BaseTexture.prototype, "lodGenerationScale", null);
  31655. __decorate([
  31656. BABYLON.serialize()
  31657. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31658. return BaseTexture;
  31659. }());
  31660. BABYLON.BaseTexture = BaseTexture;
  31661. })(BABYLON || (BABYLON = {}));
  31662. //# sourceMappingURL=babylon.baseTexture.js.map
  31663. var BABYLON;
  31664. (function (BABYLON) {
  31665. /**
  31666. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31667. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31668. */
  31669. var Texture = /** @class */ (function (_super) {
  31670. __extends(Texture, _super);
  31671. /**
  31672. * Instantiates a new texture.
  31673. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31674. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31675. * @param url define the url of the picture to load as a texture
  31676. * @param scene define the scene the texture will belong to
  31677. * @param noMipmap define if the texture will require mip maps or not
  31678. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31679. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31680. * @param onLoad define a callback triggered when the texture has been loaded
  31681. * @param onError define a callback triggered when an error occurred during the loading session
  31682. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31683. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31684. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31685. */
  31686. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31687. if (noMipmap === void 0) { noMipmap = false; }
  31688. if (invertY === void 0) { invertY = true; }
  31689. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31690. if (onLoad === void 0) { onLoad = null; }
  31691. if (onError === void 0) { onError = null; }
  31692. if (buffer === void 0) { buffer = null; }
  31693. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31694. var _this = _super.call(this, scene) || this;
  31695. /**
  31696. * Define an offset on the texture to offset the u coordinates of the UVs
  31697. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31698. */
  31699. _this.uOffset = 0;
  31700. /**
  31701. * Define an offset on the texture to offset the v coordinates of the UVs
  31702. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31703. */
  31704. _this.vOffset = 0;
  31705. /**
  31706. * Define an offset on the texture to scale the u coordinates of the UVs
  31707. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31708. */
  31709. _this.uScale = 1.0;
  31710. /**
  31711. * Define an offset on the texture to scale the v coordinates of the UVs
  31712. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31713. */
  31714. _this.vScale = 1.0;
  31715. /**
  31716. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31717. * @see http://doc.babylonjs.com/how_to/more_materials
  31718. */
  31719. _this.uAng = 0;
  31720. /**
  31721. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31722. * @see http://doc.babylonjs.com/how_to/more_materials
  31723. */
  31724. _this.vAng = 0;
  31725. /**
  31726. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31727. * @see http://doc.babylonjs.com/how_to/more_materials
  31728. */
  31729. _this.wAng = 0;
  31730. /**
  31731. * Defines the center of rotation (U)
  31732. */
  31733. _this.uRotationCenter = 0.5;
  31734. /**
  31735. * Defines the center of rotation (V)
  31736. */
  31737. _this.vRotationCenter = 0.5;
  31738. /**
  31739. * Defines the center of rotation (W)
  31740. */
  31741. _this.wRotationCenter = 0.5;
  31742. /**
  31743. * Observable triggered once the texture has been loaded.
  31744. */
  31745. _this.onLoadObservable = new BABYLON.Observable();
  31746. _this._isBlocking = true;
  31747. _this.name = url || "";
  31748. _this.url = url;
  31749. _this._noMipmap = noMipmap;
  31750. _this._invertY = invertY;
  31751. _this._samplingMode = samplingMode;
  31752. _this._buffer = buffer;
  31753. _this._deleteBuffer = deleteBuffer;
  31754. if (format) {
  31755. _this._format = format;
  31756. }
  31757. scene = _this.getScene();
  31758. if (!scene) {
  31759. return _this;
  31760. }
  31761. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31762. var load = function () {
  31763. if (_this.onLoadObservable.hasObservers()) {
  31764. _this.onLoadObservable.notifyObservers(_this);
  31765. }
  31766. if (onLoad) {
  31767. onLoad();
  31768. }
  31769. if (!_this.isBlocking && scene) {
  31770. scene.resetCachedMaterial();
  31771. }
  31772. };
  31773. if (!_this.url) {
  31774. _this._delayedOnLoad = load;
  31775. _this._delayedOnError = onError;
  31776. return _this;
  31777. }
  31778. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31779. if (!_this._texture) {
  31780. if (!scene.useDelayedTextureLoading) {
  31781. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31782. if (deleteBuffer) {
  31783. delete _this._buffer;
  31784. }
  31785. }
  31786. else {
  31787. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31788. _this._delayedOnLoad = load;
  31789. _this._delayedOnError = onError;
  31790. }
  31791. }
  31792. else {
  31793. if (_this._texture.isReady) {
  31794. BABYLON.Tools.SetImmediate(function () { return load(); });
  31795. }
  31796. else {
  31797. _this._texture.onLoadedObservable.add(load);
  31798. }
  31799. }
  31800. return _this;
  31801. }
  31802. Object.defineProperty(Texture.prototype, "noMipmap", {
  31803. /**
  31804. * Are mip maps generated for this texture or not.
  31805. */
  31806. get: function () {
  31807. return this._noMipmap;
  31808. },
  31809. enumerable: true,
  31810. configurable: true
  31811. });
  31812. Object.defineProperty(Texture.prototype, "isBlocking", {
  31813. get: function () {
  31814. return this._isBlocking;
  31815. },
  31816. /**
  31817. * Is the texture preventing material to render while loading.
  31818. * If false, a default texture will be used instead of the loading one during the preparation step.
  31819. */
  31820. set: function (value) {
  31821. this._isBlocking = value;
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. Object.defineProperty(Texture.prototype, "samplingMode", {
  31827. /**
  31828. * Get the current sampling mode associated with the texture.
  31829. */
  31830. get: function () {
  31831. return this._samplingMode;
  31832. },
  31833. enumerable: true,
  31834. configurable: true
  31835. });
  31836. /**
  31837. * Update the url (and optional buffer) of this texture if url was null during construction.
  31838. * @param url the url of the texture
  31839. * @param buffer the buffer of the texture (defaults to null)
  31840. */
  31841. Texture.prototype.updateURL = function (url, buffer) {
  31842. if (buffer === void 0) { buffer = null; }
  31843. if (this.url) {
  31844. throw new Error("URL is already set");
  31845. }
  31846. this.url = url;
  31847. this._buffer = buffer;
  31848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31849. this.delayLoad();
  31850. };
  31851. /**
  31852. * Finish the loading sequence of a texture flagged as delayed load.
  31853. * @hidden
  31854. */
  31855. Texture.prototype.delayLoad = function () {
  31856. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31857. return;
  31858. }
  31859. var scene = this.getScene();
  31860. if (!scene) {
  31861. return;
  31862. }
  31863. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31864. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31865. if (!this._texture) {
  31866. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31867. if (this._deleteBuffer) {
  31868. delete this._buffer;
  31869. }
  31870. }
  31871. else {
  31872. if (this._delayedOnLoad) {
  31873. if (this._texture.isReady) {
  31874. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31875. }
  31876. else {
  31877. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31878. }
  31879. }
  31880. }
  31881. this._delayedOnLoad = null;
  31882. this._delayedOnError = null;
  31883. };
  31884. /**
  31885. * Update the sampling mode of the texture.
  31886. * Default is Trilinear mode.
  31887. *
  31888. * | Value | Type | Description |
  31889. * | ----- | ------------------ | ----------- |
  31890. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31891. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31892. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31893. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31894. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31895. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31896. * | 7 | NEAREST_LINEAR | |
  31897. * | 8 | NEAREST_NEAREST | |
  31898. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31899. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31900. * | 11 | LINEAR_LINEAR | |
  31901. * | 12 | LINEAR_NEAREST | |
  31902. *
  31903. * > _mag_: magnification filter (close to the viewer)
  31904. * > _min_: minification filter (far from the viewer)
  31905. * > _mip_: filter used between mip map levels
  31906. *@param samplingMode Define the new sampling mode of the texture
  31907. */
  31908. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31909. if (!this._texture) {
  31910. return;
  31911. }
  31912. var scene = this.getScene();
  31913. if (!scene) {
  31914. return;
  31915. }
  31916. this._samplingMode = samplingMode;
  31917. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31918. };
  31919. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31920. x *= this.uScale;
  31921. y *= this.vScale;
  31922. x -= this.uRotationCenter * this.uScale;
  31923. y -= this.vRotationCenter * this.vScale;
  31924. z -= this.wRotationCenter;
  31925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31926. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31927. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31928. t.z += this.wRotationCenter;
  31929. };
  31930. /**
  31931. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31932. * @returns the transform matrix of the texture.
  31933. */
  31934. Texture.prototype.getTextureMatrix = function () {
  31935. var _this = this;
  31936. if (this.uOffset === this._cachedUOffset &&
  31937. this.vOffset === this._cachedVOffset &&
  31938. this.uScale === this._cachedUScale &&
  31939. this.vScale === this._cachedVScale &&
  31940. this.uAng === this._cachedUAng &&
  31941. this.vAng === this._cachedVAng &&
  31942. this.wAng === this._cachedWAng) {
  31943. return this._cachedTextureMatrix;
  31944. }
  31945. this._cachedUOffset = this.uOffset;
  31946. this._cachedVOffset = this.vOffset;
  31947. this._cachedUScale = this.uScale;
  31948. this._cachedVScale = this.vScale;
  31949. this._cachedUAng = this.uAng;
  31950. this._cachedVAng = this.vAng;
  31951. this._cachedWAng = this.wAng;
  31952. if (!this._cachedTextureMatrix) {
  31953. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31954. this._rowGenerationMatrix = new BABYLON.Matrix();
  31955. this._t0 = BABYLON.Vector3.Zero();
  31956. this._t1 = BABYLON.Vector3.Zero();
  31957. this._t2 = BABYLON.Vector3.Zero();
  31958. }
  31959. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31960. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31961. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31962. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31963. this._t1.subtractInPlace(this._t0);
  31964. this._t2.subtractInPlace(this._t0);
  31965. BABYLON.Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);
  31966. var scene = this.getScene();
  31967. if (!scene) {
  31968. return this._cachedTextureMatrix;
  31969. }
  31970. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31971. return mat.hasTexture(_this);
  31972. });
  31973. return this._cachedTextureMatrix;
  31974. };
  31975. /**
  31976. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31977. * @returns The reflection texture transform
  31978. */
  31979. Texture.prototype.getReflectionTextureMatrix = function () {
  31980. var _this = this;
  31981. var scene = this.getScene();
  31982. if (!scene) {
  31983. return this._cachedTextureMatrix;
  31984. }
  31985. if (this.uOffset === this._cachedUOffset &&
  31986. this.vOffset === this._cachedVOffset &&
  31987. this.uScale === this._cachedUScale &&
  31988. this.vScale === this._cachedVScale &&
  31989. this.coordinatesMode === this._cachedCoordinatesMode) {
  31990. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31991. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31992. return this._cachedTextureMatrix;
  31993. }
  31994. }
  31995. else {
  31996. return this._cachedTextureMatrix;
  31997. }
  31998. }
  31999. if (!this._cachedTextureMatrix) {
  32000. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32001. }
  32002. if (!this._projectionModeMatrix) {
  32003. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  32004. }
  32005. this._cachedUOffset = this.uOffset;
  32006. this._cachedVOffset = this.vOffset;
  32007. this._cachedUScale = this.uScale;
  32008. this._cachedVScale = this.vScale;
  32009. this._cachedCoordinatesMode = this.coordinatesMode;
  32010. switch (this.coordinatesMode) {
  32011. case Texture.PLANAR_MODE:
  32012. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32013. this._cachedTextureMatrix[0] = this.uScale;
  32014. this._cachedTextureMatrix[5] = this.vScale;
  32015. this._cachedTextureMatrix[12] = this.uOffset;
  32016. this._cachedTextureMatrix[13] = this.vOffset;
  32017. break;
  32018. case Texture.PROJECTION_MODE:
  32019. BABYLON.Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);
  32020. var projectionMatrix = scene.getProjectionMatrix();
  32021. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  32022. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  32023. break;
  32024. default:
  32025. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32026. break;
  32027. }
  32028. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32029. return (mat.getActiveTextures().indexOf(_this) !== -1);
  32030. });
  32031. return this._cachedTextureMatrix;
  32032. };
  32033. /**
  32034. * Clones the texture.
  32035. * @returns the cloned texture
  32036. */
  32037. Texture.prototype.clone = function () {
  32038. var _this = this;
  32039. return BABYLON.SerializationHelper.Clone(function () {
  32040. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  32041. }, this);
  32042. };
  32043. /**
  32044. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  32045. * @returns The JSON representation of the texture
  32046. */
  32047. Texture.prototype.serialize = function () {
  32048. var serializationObject = _super.prototype.serialize.call(this);
  32049. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32050. serializationObject.base64String = this._buffer;
  32051. serializationObject.name = serializationObject.name.replace("data:", "");
  32052. }
  32053. serializationObject.invertY = this._invertY;
  32054. serializationObject.samplingMode = this.samplingMode;
  32055. return serializationObject;
  32056. };
  32057. /**
  32058. * Get the current class name of the texture usefull for serialization or dynamic coding.
  32059. * @returns "Texture"
  32060. */
  32061. Texture.prototype.getClassName = function () {
  32062. return "Texture";
  32063. };
  32064. /**
  32065. * Dispose the texture and release its associated resources.
  32066. */
  32067. Texture.prototype.dispose = function () {
  32068. _super.prototype.dispose.call(this);
  32069. this.onLoadObservable.clear();
  32070. this._delayedOnLoad = null;
  32071. this._delayedOnError = null;
  32072. };
  32073. /**
  32074. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32075. * @param parsedTexture Define the JSON representation of the texture
  32076. * @param scene Define the scene the parsed texture should be instantiated in
  32077. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32078. * @returns The parsed texture if successful
  32079. */
  32080. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32081. if (parsedTexture.customType) {
  32082. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32083. // Update Sampling Mode
  32084. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32085. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32086. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32087. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32088. }
  32089. }
  32090. return parsedCustomTexture;
  32091. }
  32092. if (parsedTexture.isCube) {
  32093. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32094. }
  32095. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32096. return null;
  32097. }
  32098. var texture = BABYLON.SerializationHelper.Parse(function () {
  32099. var generateMipMaps = true;
  32100. if (parsedTexture.noMipmap) {
  32101. generateMipMaps = false;
  32102. }
  32103. if (parsedTexture.mirrorPlane) {
  32104. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32105. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32106. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32107. return mirrorTexture;
  32108. }
  32109. else if (parsedTexture.isRenderTarget) {
  32110. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32111. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32112. return renderTargetTexture;
  32113. }
  32114. else {
  32115. var texture;
  32116. if (parsedTexture.base64String) {
  32117. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32118. }
  32119. else {
  32120. var url = rootUrl + parsedTexture.name;
  32121. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32122. url = parsedTexture.url;
  32123. }
  32124. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32125. }
  32126. return texture;
  32127. }
  32128. }, parsedTexture, scene);
  32129. // Update Sampling Mode
  32130. if (parsedTexture.samplingMode) {
  32131. var sampling = parsedTexture.samplingMode;
  32132. if (texture._samplingMode !== sampling) {
  32133. texture.updateSamplingMode(sampling);
  32134. }
  32135. }
  32136. // Animations
  32137. if (parsedTexture.animations) {
  32138. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32139. var parsedAnimation = parsedTexture.animations[animationIndex];
  32140. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32141. }
  32142. }
  32143. return texture;
  32144. };
  32145. /**
  32146. * Creates a texture from its base 64 representation.
  32147. * @param data Define the base64 payload without the data: prefix
  32148. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32149. * @param scene Define the scene the texture should belong to
  32150. * @param noMipmap Forces the texture to not create mip map information if true
  32151. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32152. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32153. * @param onLoad define a callback triggered when the texture has been loaded
  32154. * @param onError define a callback triggered when an error occurred during the loading session
  32155. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32156. * @returns the created texture
  32157. */
  32158. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32159. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32160. if (onLoad === void 0) { onLoad = null; }
  32161. if (onError === void 0) { onError = null; }
  32162. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32163. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32164. };
  32165. /**
  32166. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32167. * @param data Define the base64 payload without the data: prefix
  32168. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32169. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32170. * @param scene Define the scene the texture should belong to
  32171. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32172. * @param noMipmap Forces the texture to not create mip map information if true
  32173. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32174. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32175. * @param onLoad define a callback triggered when the texture has been loaded
  32176. * @param onError define a callback triggered when an error occurred during the loading session
  32177. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32178. * @returns the created texture
  32179. */
  32180. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32181. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32182. if (noMipmap === void 0) { noMipmap = false; }
  32183. if (invertY === void 0) { invertY = true; }
  32184. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32185. if (onLoad === void 0) { onLoad = null; }
  32186. if (onError === void 0) { onError = null; }
  32187. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32188. if (name.substr(0, 5) !== "data:") {
  32189. name = "data:" + name;
  32190. }
  32191. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32192. };
  32193. /** nearest is mag = nearest and min = nearest and mip = linear */
  32194. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32195. /** nearest is mag = nearest and min = nearest and mip = linear */
  32196. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32197. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32198. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32199. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32200. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32201. /** Trilinear is mag = linear and min = linear and mip = linear */
  32202. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32203. /** Trilinear is mag = linear and min = linear and mip = linear */
  32204. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32205. /** mag = nearest and min = nearest and mip = nearest */
  32206. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32207. /** mag = nearest and min = linear and mip = nearest */
  32208. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32209. /** mag = nearest and min = linear and mip = linear */
  32210. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32211. /** mag = nearest and min = linear and mip = none */
  32212. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32213. /** mag = nearest and min = nearest and mip = none */
  32214. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32215. /** mag = linear and min = nearest and mip = nearest */
  32216. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32217. /** mag = linear and min = nearest and mip = linear */
  32218. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32219. /** mag = linear and min = linear and mip = none */
  32220. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32221. /** mag = linear and min = nearest and mip = none */
  32222. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32223. /** Explicit coordinates mode */
  32224. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32225. /** Spherical coordinates mode */
  32226. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32227. /** Planar coordinates mode */
  32228. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32229. /** Cubic coordinates mode */
  32230. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32231. /** Projection coordinates mode */
  32232. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32233. /** Inverse Cubic coordinates mode */
  32234. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32235. /** Inverse Cubic coordinates mode */
  32236. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32237. /** Equirectangular coordinates mode */
  32238. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32239. /** Equirectangular Fixed coordinates mode */
  32240. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32241. /** Equirectangular Fixed Mirrored coordinates mode */
  32242. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32243. /** Texture is not repeating outside of 0..1 UVs */
  32244. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32245. /** Texture is repeating outside of 0..1 UVs */
  32246. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32247. /** Texture is repeating and mirrored */
  32248. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32249. /**
  32250. * 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
  32251. */
  32252. Texture.UseSerializedUrlIfAny = false;
  32253. __decorate([
  32254. BABYLON.serialize()
  32255. ], Texture.prototype, "url", void 0);
  32256. __decorate([
  32257. BABYLON.serialize()
  32258. ], Texture.prototype, "uOffset", void 0);
  32259. __decorate([
  32260. BABYLON.serialize()
  32261. ], Texture.prototype, "vOffset", void 0);
  32262. __decorate([
  32263. BABYLON.serialize()
  32264. ], Texture.prototype, "uScale", void 0);
  32265. __decorate([
  32266. BABYLON.serialize()
  32267. ], Texture.prototype, "vScale", void 0);
  32268. __decorate([
  32269. BABYLON.serialize()
  32270. ], Texture.prototype, "uAng", void 0);
  32271. __decorate([
  32272. BABYLON.serialize()
  32273. ], Texture.prototype, "vAng", void 0);
  32274. __decorate([
  32275. BABYLON.serialize()
  32276. ], Texture.prototype, "wAng", void 0);
  32277. __decorate([
  32278. BABYLON.serialize()
  32279. ], Texture.prototype, "uRotationCenter", void 0);
  32280. __decorate([
  32281. BABYLON.serialize()
  32282. ], Texture.prototype, "vRotationCenter", void 0);
  32283. __decorate([
  32284. BABYLON.serialize()
  32285. ], Texture.prototype, "wRotationCenter", void 0);
  32286. __decorate([
  32287. BABYLON.serialize()
  32288. ], Texture.prototype, "isBlocking", null);
  32289. return Texture;
  32290. }(BABYLON.BaseTexture));
  32291. BABYLON.Texture = Texture;
  32292. })(BABYLON || (BABYLON = {}));
  32293. //# sourceMappingURL=babylon.texture.js.map
  32294. var BABYLON;
  32295. (function (BABYLON) {
  32296. /**
  32297. * @hidden
  32298. **/
  32299. var _CreationDataStorage = /** @class */ (function () {
  32300. function _CreationDataStorage() {
  32301. }
  32302. return _CreationDataStorage;
  32303. }());
  32304. BABYLON._CreationDataStorage = _CreationDataStorage;
  32305. /**
  32306. * @hidden
  32307. **/
  32308. var _InstanceDataStorage = /** @class */ (function () {
  32309. function _InstanceDataStorage() {
  32310. this.visibleInstances = {};
  32311. this.renderIdForInstances = new Array();
  32312. this.batchCache = new _InstancesBatch();
  32313. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32314. }
  32315. return _InstanceDataStorage;
  32316. }());
  32317. /**
  32318. * @hidden
  32319. **/
  32320. var _InstancesBatch = /** @class */ (function () {
  32321. function _InstancesBatch() {
  32322. this.mustReturn = false;
  32323. this.visibleInstances = new Array();
  32324. this.renderSelf = new Array();
  32325. }
  32326. return _InstancesBatch;
  32327. }());
  32328. BABYLON._InstancesBatch = _InstancesBatch;
  32329. /**
  32330. * Class used to represent renderable models
  32331. */
  32332. var Mesh = /** @class */ (function (_super) {
  32333. __extends(Mesh, _super);
  32334. /**
  32335. * @constructor
  32336. * @param name The value used by scene.getMeshByName() to do a lookup.
  32337. * @param scene The scene to add this mesh to.
  32338. * @param parent The parent of this mesh, if it has one
  32339. * @param source An optional Mesh from which geometry is shared, cloned.
  32340. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32341. * When false, achieved by calling a clone(), also passing False.
  32342. * This will make creation of children, recursive.
  32343. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32344. */
  32345. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32346. if (scene === void 0) { scene = null; }
  32347. if (parent === void 0) { parent = null; }
  32348. if (source === void 0) { source = null; }
  32349. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32350. var _this = _super.call(this, name, scene) || this;
  32351. // Members
  32352. /**
  32353. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32354. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32355. */
  32356. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32357. /**
  32358. * Gets the list of instances created from this mesh
  32359. * it is not supposed to be modified manually.
  32360. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  32361. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32362. */
  32363. _this.instances = new Array();
  32364. _this._LODLevels = new Array();
  32365. /** @hidden */
  32366. _this._instanceDataStorage = new _InstanceDataStorage();
  32367. // Use by builder only to know what orientation were the mesh build in.
  32368. /** @hidden */
  32369. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32370. /**
  32371. * Use this property to change the original side orientation defined at construction time
  32372. */
  32373. _this.overrideMaterialSideOrientation = null;
  32374. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32375. // Will be used to save a source mesh reference, If any
  32376. _this._source = null;
  32377. scene = _this.getScene();
  32378. if (source) {
  32379. // Geometry
  32380. if (source._geometry) {
  32381. source._geometry.applyToMesh(_this);
  32382. }
  32383. // Deep copy
  32384. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32385. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32386. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32387. ], ["_poseMatrix"]);
  32388. // Source mesh
  32389. _this._source = source;
  32390. if (scene.useClonedMeshhMap) {
  32391. if (!source.meshMap) {
  32392. source.meshMap = {};
  32393. }
  32394. source.meshMap[_this.uniqueId] = _this;
  32395. }
  32396. // Construction Params
  32397. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32398. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32399. _this._creationDataStorage = source._creationDataStorage;
  32400. // Animation ranges
  32401. if (_this._source._ranges) {
  32402. var ranges = _this._source._ranges;
  32403. for (var name in ranges) {
  32404. if (!ranges.hasOwnProperty(name)) {
  32405. continue;
  32406. }
  32407. if (!ranges[name]) {
  32408. continue;
  32409. }
  32410. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32411. }
  32412. }
  32413. // Metadata
  32414. if (source.metadata && source.metadata.clone) {
  32415. _this.metadata = source.metadata.clone();
  32416. }
  32417. else {
  32418. _this.metadata = source.metadata;
  32419. }
  32420. // Tags
  32421. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32422. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32423. }
  32424. // Parent
  32425. _this.parent = source.parent;
  32426. // Pivot
  32427. _this.setPivotMatrix(source.getPivotMatrix());
  32428. _this.id = name + "." + source.id;
  32429. // Material
  32430. _this.material = source.material;
  32431. var index;
  32432. if (!doNotCloneChildren) {
  32433. // Children
  32434. var directDescendants = source.getDescendants(true);
  32435. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32436. var child = directDescendants[index_1];
  32437. if (child.clone) {
  32438. child.clone(name + "." + child.name, _this);
  32439. }
  32440. }
  32441. }
  32442. // Physics clone
  32443. var physicsEngine = _this.getScene().getPhysicsEngine();
  32444. if (clonePhysicsImpostor && physicsEngine) {
  32445. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32446. if (impostor) {
  32447. _this.physicsImpostor = impostor.clone(_this);
  32448. }
  32449. }
  32450. // Particles
  32451. for (index = 0; index < scene.particleSystems.length; index++) {
  32452. var system = scene.particleSystems[index];
  32453. if (system.emitter === source) {
  32454. system.clone(system.name, _this);
  32455. }
  32456. }
  32457. _this.refreshBoundingInfo();
  32458. _this.computeWorldMatrix(true);
  32459. }
  32460. // Parent
  32461. if (parent !== null) {
  32462. _this.parent = parent;
  32463. }
  32464. return _this;
  32465. }
  32466. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32467. /**
  32468. * An event triggered before rendering the mesh
  32469. */
  32470. get: function () {
  32471. if (!this._onBeforeRenderObservable) {
  32472. this._onBeforeRenderObservable = new BABYLON.Observable();
  32473. }
  32474. return this._onBeforeRenderObservable;
  32475. },
  32476. enumerable: true,
  32477. configurable: true
  32478. });
  32479. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32480. /**
  32481. * An event triggered after rendering the mesh
  32482. */
  32483. get: function () {
  32484. if (!this._onAfterRenderObservable) {
  32485. this._onAfterRenderObservable = new BABYLON.Observable();
  32486. }
  32487. return this._onAfterRenderObservable;
  32488. },
  32489. enumerable: true,
  32490. configurable: true
  32491. });
  32492. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32493. /**
  32494. * An event triggered before drawing the mesh
  32495. */
  32496. get: function () {
  32497. if (!this._onBeforeDrawObservable) {
  32498. this._onBeforeDrawObservable = new BABYLON.Observable();
  32499. }
  32500. return this._onBeforeDrawObservable;
  32501. },
  32502. enumerable: true,
  32503. configurable: true
  32504. });
  32505. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32506. /**
  32507. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32508. */
  32509. set: function (callback) {
  32510. if (this._onBeforeDrawObserver) {
  32511. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32512. }
  32513. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32514. },
  32515. enumerable: true,
  32516. configurable: true
  32517. });
  32518. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32519. /**
  32520. * Gets or sets the morph target manager
  32521. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32522. */
  32523. get: function () {
  32524. return this._morphTargetManager;
  32525. },
  32526. set: function (value) {
  32527. if (this._morphTargetManager === value) {
  32528. return;
  32529. }
  32530. this._morphTargetManager = value;
  32531. this._syncGeometryWithMorphTargetManager();
  32532. },
  32533. enumerable: true,
  32534. configurable: true
  32535. });
  32536. Object.defineProperty(Mesh.prototype, "source", {
  32537. /**
  32538. * Gets the source mesh (the one used to clone this one from)
  32539. */
  32540. get: function () {
  32541. return this._source;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32547. /**
  32548. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32549. */
  32550. get: function () {
  32551. return this._unIndexed;
  32552. },
  32553. set: function (value) {
  32554. if (this._unIndexed !== value) {
  32555. this._unIndexed = value;
  32556. this._markSubMeshesAsAttributesDirty();
  32557. }
  32558. },
  32559. enumerable: true,
  32560. configurable: true
  32561. });
  32562. // Methods
  32563. /**
  32564. * Gets the class name
  32565. * @returns the string "Mesh".
  32566. */
  32567. Mesh.prototype.getClassName = function () {
  32568. return "Mesh";
  32569. };
  32570. /**
  32571. * Returns a description of this mesh
  32572. * @param fullDetails define if full details about this mesh must be used
  32573. * @returns a descriptive string representing this mesh
  32574. */
  32575. Mesh.prototype.toString = function (fullDetails) {
  32576. var ret = _super.prototype.toString.call(this, fullDetails);
  32577. ret += ", n vertices: " + this.getTotalVertices();
  32578. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32579. if (this.animations) {
  32580. for (var i = 0; i < this.animations.length; i++) {
  32581. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32582. }
  32583. }
  32584. if (fullDetails) {
  32585. if (this._geometry) {
  32586. var ib = this.getIndices();
  32587. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32588. if (vb && ib) {
  32589. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32590. }
  32591. }
  32592. else {
  32593. ret += ", flat shading: UNKNOWN";
  32594. }
  32595. }
  32596. return ret;
  32597. };
  32598. /** @hidden */
  32599. Mesh.prototype._unBindEffect = function () {
  32600. _super.prototype._unBindEffect.call(this);
  32601. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32602. var instance = _a[_i];
  32603. instance._unBindEffect();
  32604. }
  32605. };
  32606. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32607. /**
  32608. * Gets a boolean indicating if this mesh has LOD
  32609. */
  32610. get: function () {
  32611. return this._LODLevels.length > 0;
  32612. },
  32613. enumerable: true,
  32614. configurable: true
  32615. });
  32616. /**
  32617. * Gets the list of MeshLODLevel associated with the current mesh
  32618. * @returns an array of MeshLODLevel
  32619. */
  32620. Mesh.prototype.getLODLevels = function () {
  32621. return this._LODLevels;
  32622. };
  32623. Mesh.prototype._sortLODLevels = function () {
  32624. this._LODLevels.sort(function (a, b) {
  32625. if (a.distance < b.distance) {
  32626. return 1;
  32627. }
  32628. if (a.distance > b.distance) {
  32629. return -1;
  32630. }
  32631. return 0;
  32632. });
  32633. };
  32634. /**
  32635. * Add a mesh as LOD level triggered at the given distance.
  32636. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32637. * @param distance The distance from the center of the object to show this level
  32638. * @param mesh The mesh to be added as LOD level (can be null)
  32639. * @return This mesh (for chaining)
  32640. */
  32641. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32642. if (mesh && mesh._masterMesh) {
  32643. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32644. return this;
  32645. }
  32646. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32647. this._LODLevels.push(level);
  32648. if (mesh) {
  32649. mesh._masterMesh = this;
  32650. }
  32651. this._sortLODLevels();
  32652. return this;
  32653. };
  32654. /**
  32655. * Returns the LOD level mesh at the passed distance or null if not found.
  32656. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32657. * @param distance The distance from the center of the object to show this level
  32658. * @returns a Mesh or `null`
  32659. */
  32660. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32661. for (var index = 0; index < this._LODLevels.length; index++) {
  32662. var level = this._LODLevels[index];
  32663. if (level.distance === distance) {
  32664. return level.mesh;
  32665. }
  32666. }
  32667. return null;
  32668. };
  32669. /**
  32670. * Remove a mesh from the LOD array
  32671. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32672. * @param mesh defines the mesh to be removed
  32673. * @return This mesh (for chaining)
  32674. */
  32675. Mesh.prototype.removeLODLevel = function (mesh) {
  32676. for (var index = 0; index < this._LODLevels.length; index++) {
  32677. if (this._LODLevels[index].mesh === mesh) {
  32678. this._LODLevels.splice(index, 1);
  32679. if (mesh) {
  32680. mesh._masterMesh = null;
  32681. }
  32682. }
  32683. }
  32684. this._sortLODLevels();
  32685. return this;
  32686. };
  32687. /**
  32688. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32689. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32690. * @param camera defines the camera to use to compute distance
  32691. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32692. * @return This mesh (for chaining)
  32693. */
  32694. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32695. if (!this._LODLevels || this._LODLevels.length === 0) {
  32696. return this;
  32697. }
  32698. var bSphere;
  32699. if (boundingSphere) {
  32700. bSphere = boundingSphere;
  32701. }
  32702. else {
  32703. var boundingInfo = this.getBoundingInfo();
  32704. bSphere = boundingInfo.boundingSphere;
  32705. }
  32706. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32707. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32708. if (this.onLODLevelSelection) {
  32709. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32710. }
  32711. return this;
  32712. }
  32713. for (var index = 0; index < this._LODLevels.length; index++) {
  32714. var level = this._LODLevels[index];
  32715. if (level.distance < distanceToCamera) {
  32716. if (level.mesh) {
  32717. level.mesh._preActivate();
  32718. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32719. }
  32720. if (this.onLODLevelSelection) {
  32721. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32722. }
  32723. return level.mesh;
  32724. }
  32725. }
  32726. if (this.onLODLevelSelection) {
  32727. this.onLODLevelSelection(distanceToCamera, this, this);
  32728. }
  32729. return this;
  32730. };
  32731. Object.defineProperty(Mesh.prototype, "geometry", {
  32732. /**
  32733. * Gets the mesh internal Geometry object
  32734. */
  32735. get: function () {
  32736. return this._geometry;
  32737. },
  32738. enumerable: true,
  32739. configurable: true
  32740. });
  32741. /**
  32742. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32743. * @returns the total number of vertices
  32744. */
  32745. Mesh.prototype.getTotalVertices = function () {
  32746. if (this._geometry === null || this._geometry === undefined) {
  32747. return 0;
  32748. }
  32749. return this._geometry.getTotalVertices();
  32750. };
  32751. /**
  32752. * Returns the content of an associated vertex buffer
  32753. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32754. * - BABYLON.VertexBuffer.PositionKind
  32755. * - BABYLON.VertexBuffer.UVKind
  32756. * - BABYLON.VertexBuffer.UV2Kind
  32757. * - BABYLON.VertexBuffer.UV3Kind
  32758. * - BABYLON.VertexBuffer.UV4Kind
  32759. * - BABYLON.VertexBuffer.UV5Kind
  32760. * - BABYLON.VertexBuffer.UV6Kind
  32761. * - BABYLON.VertexBuffer.ColorKind
  32762. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32763. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32764. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32765. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32766. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32767. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32768. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32769. */
  32770. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32771. if (!this._geometry) {
  32772. return null;
  32773. }
  32774. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32775. };
  32776. /**
  32777. * Returns the mesh VertexBuffer object from the requested `kind`
  32778. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32779. * - BABYLON.VertexBuffer.PositionKind
  32780. * - BABYLON.VertexBuffer.UVKind
  32781. * - BABYLON.VertexBuffer.UV2Kind
  32782. * - BABYLON.VertexBuffer.UV3Kind
  32783. * - BABYLON.VertexBuffer.UV4Kind
  32784. * - BABYLON.VertexBuffer.UV5Kind
  32785. * - BABYLON.VertexBuffer.UV6Kind
  32786. * - BABYLON.VertexBuffer.ColorKind
  32787. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32788. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32789. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32790. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32791. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32792. */
  32793. Mesh.prototype.getVertexBuffer = function (kind) {
  32794. if (!this._geometry) {
  32795. return null;
  32796. }
  32797. return this._geometry.getVertexBuffer(kind);
  32798. };
  32799. /**
  32800. * Tests if a specific vertex buffer is associated with this mesh
  32801. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32802. * - BABYLON.VertexBuffer.PositionKind
  32803. * - BABYLON.VertexBuffer.UVKind
  32804. * - BABYLON.VertexBuffer.UV2Kind
  32805. * - BABYLON.VertexBuffer.UV3Kind
  32806. * - BABYLON.VertexBuffer.UV4Kind
  32807. * - BABYLON.VertexBuffer.UV5Kind
  32808. * - BABYLON.VertexBuffer.UV6Kind
  32809. * - BABYLON.VertexBuffer.ColorKind
  32810. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32811. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32812. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32813. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32814. * @returns a boolean
  32815. */
  32816. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32817. if (!this._geometry) {
  32818. if (this._delayInfo) {
  32819. return this._delayInfo.indexOf(kind) !== -1;
  32820. }
  32821. return false;
  32822. }
  32823. return this._geometry.isVerticesDataPresent(kind);
  32824. };
  32825. /**
  32826. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32827. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32828. * - BABYLON.VertexBuffer.PositionKind
  32829. * - BABYLON.VertexBuffer.UVKind
  32830. * - BABYLON.VertexBuffer.UV2Kind
  32831. * - BABYLON.VertexBuffer.UV3Kind
  32832. * - BABYLON.VertexBuffer.UV4Kind
  32833. * - BABYLON.VertexBuffer.UV5Kind
  32834. * - BABYLON.VertexBuffer.UV6Kind
  32835. * - BABYLON.VertexBuffer.ColorKind
  32836. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32837. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32838. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32839. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32840. * @returns a boolean
  32841. */
  32842. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32843. if (!this._geometry) {
  32844. if (this._delayInfo) {
  32845. return this._delayInfo.indexOf(kind) !== -1;
  32846. }
  32847. return false;
  32848. }
  32849. return this._geometry.isVertexBufferUpdatable(kind);
  32850. };
  32851. /**
  32852. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32853. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32854. * - BABYLON.VertexBuffer.PositionKind
  32855. * - BABYLON.VertexBuffer.UVKind
  32856. * - BABYLON.VertexBuffer.UV2Kind
  32857. * - BABYLON.VertexBuffer.UV3Kind
  32858. * - BABYLON.VertexBuffer.UV4Kind
  32859. * - BABYLON.VertexBuffer.UV5Kind
  32860. * - BABYLON.VertexBuffer.UV6Kind
  32861. * - BABYLON.VertexBuffer.ColorKind
  32862. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32863. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32864. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32865. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32866. * @returns an array of strings
  32867. */
  32868. Mesh.prototype.getVerticesDataKinds = function () {
  32869. if (!this._geometry) {
  32870. var result = new Array();
  32871. if (this._delayInfo) {
  32872. this._delayInfo.forEach(function (kind, index, array) {
  32873. result.push(kind);
  32874. });
  32875. }
  32876. return result;
  32877. }
  32878. return this._geometry.getVerticesDataKinds();
  32879. };
  32880. /**
  32881. * Returns a positive integer : the total number of indices in this mesh geometry.
  32882. * @returns the numner of indices or zero if the mesh has no geometry.
  32883. */
  32884. Mesh.prototype.getTotalIndices = function () {
  32885. if (!this._geometry) {
  32886. return 0;
  32887. }
  32888. return this._geometry.getTotalIndices();
  32889. };
  32890. /**
  32891. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32892. * @param copyWhenShared If 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.
  32893. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32894. * @returns the indices array or an empty array if the mesh has no geometry
  32895. */
  32896. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32897. if (!this._geometry) {
  32898. return [];
  32899. }
  32900. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32901. };
  32902. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32903. get: function () {
  32904. return this._masterMesh !== null && this._masterMesh !== undefined;
  32905. },
  32906. enumerable: true,
  32907. configurable: true
  32908. });
  32909. /**
  32910. * Determine if the current mesh is ready to be rendered
  32911. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32912. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32913. * @returns true if all associated assets are ready (material, textures, shaders)
  32914. */
  32915. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32916. if (completeCheck === void 0) { completeCheck = false; }
  32917. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32918. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32919. return false;
  32920. }
  32921. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32922. return false;
  32923. }
  32924. if (!this.subMeshes || this.subMeshes.length === 0) {
  32925. return true;
  32926. }
  32927. if (!completeCheck) {
  32928. return true;
  32929. }
  32930. var engine = this.getEngine();
  32931. var scene = this.getScene();
  32932. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32933. this.computeWorldMatrix();
  32934. var mat = this.material || scene.defaultMaterial;
  32935. if (mat) {
  32936. if (mat._storeEffectOnSubMeshes) {
  32937. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32938. var subMesh = _a[_i];
  32939. var effectiveMaterial = subMesh.getMaterial();
  32940. if (effectiveMaterial) {
  32941. if (effectiveMaterial._storeEffectOnSubMeshes) {
  32942. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32943. return false;
  32944. }
  32945. }
  32946. else {
  32947. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32948. return false;
  32949. }
  32950. }
  32951. }
  32952. }
  32953. }
  32954. else {
  32955. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32956. return false;
  32957. }
  32958. }
  32959. }
  32960. // Shadows
  32961. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32962. var light = _c[_b];
  32963. var generator = light.getShadowGenerator();
  32964. if (generator) {
  32965. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32966. var subMesh = _e[_d];
  32967. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32968. return false;
  32969. }
  32970. }
  32971. }
  32972. }
  32973. // LOD
  32974. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32975. var lod = _g[_f];
  32976. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32977. return false;
  32978. }
  32979. }
  32980. return true;
  32981. };
  32982. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32983. /**
  32984. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32985. */
  32986. get: function () {
  32987. return this._areNormalsFrozen;
  32988. },
  32989. enumerable: true,
  32990. configurable: true
  32991. });
  32992. /**
  32993. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32994. * @returns the current mesh
  32995. */
  32996. Mesh.prototype.freezeNormals = function () {
  32997. this._areNormalsFrozen = true;
  32998. return this;
  32999. };
  33000. /**
  33001. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  33002. * @returns the current mesh
  33003. */
  33004. Mesh.prototype.unfreezeNormals = function () {
  33005. this._areNormalsFrozen = false;
  33006. return this;
  33007. };
  33008. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  33009. /**
  33010. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  33011. */
  33012. set: function (count) {
  33013. this._instanceDataStorage.overridenInstanceCount = count;
  33014. },
  33015. enumerable: true,
  33016. configurable: true
  33017. });
  33018. // Methods
  33019. /** @hidden */
  33020. Mesh.prototype._preActivate = function () {
  33021. var sceneRenderId = this.getScene().getRenderId();
  33022. if (this._preActivateId === sceneRenderId) {
  33023. return this;
  33024. }
  33025. this._preActivateId = sceneRenderId;
  33026. this._instanceDataStorage.visibleInstances = null;
  33027. return this;
  33028. };
  33029. /** @hidden */
  33030. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  33031. if (this._instanceDataStorage.visibleInstances) {
  33032. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  33033. }
  33034. return this;
  33035. };
  33036. /** @hidden */
  33037. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  33038. if (!this._instanceDataStorage.visibleInstances) {
  33039. this._instanceDataStorage.visibleInstances = {
  33040. defaultRenderId: renderId,
  33041. selfDefaultRenderId: this._renderId
  33042. };
  33043. }
  33044. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  33045. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  33046. }
  33047. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  33048. return this;
  33049. };
  33050. /**
  33051. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33052. * This means the mesh underlying bounding box and sphere are recomputed.
  33053. * @returns the current mesh
  33054. */
  33055. Mesh.prototype.refreshBoundingInfo = function () {
  33056. return this._refreshBoundingInfo(false);
  33057. };
  33058. /** @hidden */
  33059. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  33060. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33061. return this;
  33062. }
  33063. var data = this._getPositionData(applySkeleton);
  33064. if (data) {
  33065. var bias = this.geometry ? this.geometry.boundingBias : null;
  33066. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  33067. if (this._boundingInfo) {
  33068. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  33069. }
  33070. else {
  33071. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33072. }
  33073. }
  33074. if (this.subMeshes) {
  33075. for (var index = 0; index < this.subMeshes.length; index++) {
  33076. this.subMeshes[index].refreshBoundingInfo();
  33077. }
  33078. }
  33079. this._updateBoundingInfo();
  33080. return this;
  33081. };
  33082. Mesh.prototype._getPositionData = function (applySkeleton) {
  33083. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33084. if (data && applySkeleton && this.skeleton) {
  33085. data = BABYLON.Tools.Slice(data);
  33086. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33087. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33088. if (matricesWeightsData && matricesIndicesData) {
  33089. var needExtras = this.numBoneInfluencers > 4;
  33090. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33091. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33092. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  33093. var tempVector = BABYLON.Tmp.Vector3[0];
  33094. var finalMatrix = BABYLON.Tmp.Matrix[0];
  33095. var tempMatrix = BABYLON.Tmp.Matrix[1];
  33096. var matWeightIdx = 0;
  33097. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  33098. finalMatrix.reset();
  33099. var inf;
  33100. var weight;
  33101. for (inf = 0; inf < 4; inf++) {
  33102. weight = matricesWeightsData[matWeightIdx + inf];
  33103. if (weight > 0) {
  33104. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33105. finalMatrix.addToSelf(tempMatrix);
  33106. }
  33107. }
  33108. if (needExtras) {
  33109. for (inf = 0; inf < 4; inf++) {
  33110. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33111. if (weight > 0) {
  33112. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33113. finalMatrix.addToSelf(tempMatrix);
  33114. }
  33115. }
  33116. }
  33117. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  33118. tempVector.toArray(data, index);
  33119. }
  33120. }
  33121. }
  33122. return data;
  33123. };
  33124. /** @hidden */
  33125. Mesh.prototype._createGlobalSubMesh = function (force) {
  33126. var totalVertices = this.getTotalVertices();
  33127. if (!totalVertices || !this.getIndices()) {
  33128. return null;
  33129. }
  33130. // Check if we need to recreate the submeshes
  33131. if (this.subMeshes && this.subMeshes.length > 0) {
  33132. var ib = this.getIndices();
  33133. if (!ib) {
  33134. return null;
  33135. }
  33136. var totalIndices = ib.length;
  33137. var needToRecreate = false;
  33138. if (force) {
  33139. needToRecreate = true;
  33140. }
  33141. else {
  33142. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33143. var submesh = _a[_i];
  33144. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33145. needToRecreate = true;
  33146. break;
  33147. }
  33148. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33149. needToRecreate = true;
  33150. break;
  33151. }
  33152. }
  33153. }
  33154. if (!needToRecreate) {
  33155. return this.subMeshes[0];
  33156. }
  33157. }
  33158. this.releaseSubMeshes();
  33159. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33160. };
  33161. /**
  33162. * This function will subdivide the mesh into multiple submeshes
  33163. * @param count defines the expected number of submeshes
  33164. */
  33165. Mesh.prototype.subdivide = function (count) {
  33166. if (count < 1) {
  33167. return;
  33168. }
  33169. var totalIndices = this.getTotalIndices();
  33170. var subdivisionSize = (totalIndices / count) | 0;
  33171. var offset = 0;
  33172. // Ensure that subdivisionSize is a multiple of 3
  33173. while (subdivisionSize % 3 !== 0) {
  33174. subdivisionSize++;
  33175. }
  33176. this.releaseSubMeshes();
  33177. for (var index = 0; index < count; index++) {
  33178. if (offset >= totalIndices) {
  33179. break;
  33180. }
  33181. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33182. offset += subdivisionSize;
  33183. }
  33184. this.synchronizeInstances();
  33185. };
  33186. /**
  33187. * Copy a FloatArray into a specific associated vertex buffer
  33188. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33189. * - BABYLON.VertexBuffer.PositionKind
  33190. * - BABYLON.VertexBuffer.UVKind
  33191. * - BABYLON.VertexBuffer.UV2Kind
  33192. * - BABYLON.VertexBuffer.UV3Kind
  33193. * - BABYLON.VertexBuffer.UV4Kind
  33194. * - BABYLON.VertexBuffer.UV5Kind
  33195. * - BABYLON.VertexBuffer.UV6Kind
  33196. * - BABYLON.VertexBuffer.ColorKind
  33197. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33198. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33199. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33200. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33201. * @param data defines the data source
  33202. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33203. * @param stride defines the data stride size (can be null)
  33204. * @returns the current mesh
  33205. */
  33206. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33207. if (updatable === void 0) { updatable = false; }
  33208. if (!this._geometry) {
  33209. var vertexData = new BABYLON.VertexData();
  33210. vertexData.set(data, kind);
  33211. var scene = this.getScene();
  33212. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33213. }
  33214. else {
  33215. this._geometry.setVerticesData(kind, data, updatable, stride);
  33216. }
  33217. return this;
  33218. };
  33219. /**
  33220. * Flags an associated vertex buffer as updatable
  33221. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33222. * - BABYLON.VertexBuffer.PositionKind
  33223. * - BABYLON.VertexBuffer.UVKind
  33224. * - BABYLON.VertexBuffer.UV2Kind
  33225. * - BABYLON.VertexBuffer.UV3Kind
  33226. * - BABYLON.VertexBuffer.UV4Kind
  33227. * - BABYLON.VertexBuffer.UV5Kind
  33228. * - BABYLON.VertexBuffer.UV6Kind
  33229. * - BABYLON.VertexBuffer.ColorKind
  33230. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33231. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33232. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33233. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33234. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33235. */
  33236. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33237. if (updatable === void 0) { updatable = true; }
  33238. var vb = this.getVertexBuffer(kind);
  33239. if (!vb || vb.isUpdatable() === updatable) {
  33240. return;
  33241. }
  33242. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33243. };
  33244. /**
  33245. * Sets the mesh global Vertex Buffer
  33246. * @param buffer defines the buffer to use
  33247. * @returns the current mesh
  33248. */
  33249. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33250. if (!this._geometry) {
  33251. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33252. }
  33253. this._geometry.setVerticesBuffer(buffer);
  33254. return this;
  33255. };
  33256. /**
  33257. * Update a specific associated vertex buffer
  33258. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33259. * - BABYLON.VertexBuffer.PositionKind
  33260. * - BABYLON.VertexBuffer.UVKind
  33261. * - BABYLON.VertexBuffer.UV2Kind
  33262. * - BABYLON.VertexBuffer.UV3Kind
  33263. * - BABYLON.VertexBuffer.UV4Kind
  33264. * - BABYLON.VertexBuffer.UV5Kind
  33265. * - BABYLON.VertexBuffer.UV6Kind
  33266. * - BABYLON.VertexBuffer.ColorKind
  33267. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33268. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33269. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33270. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33271. * @param data defines the data source
  33272. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33273. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  33274. * @returns the current mesh
  33275. */
  33276. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33277. if (!this._geometry) {
  33278. return this;
  33279. }
  33280. if (!makeItUnique) {
  33281. this._geometry.updateVerticesData(kind, data, updateExtends);
  33282. }
  33283. else {
  33284. this.makeGeometryUnique();
  33285. this.updateVerticesData(kind, data, updateExtends, false);
  33286. }
  33287. return this;
  33288. };
  33289. /**
  33290. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33291. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33292. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33293. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33294. * @returns the current mesh
  33295. */
  33296. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33297. if (computeNormals === void 0) { computeNormals = true; }
  33298. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33299. if (!positions) {
  33300. return this;
  33301. }
  33302. positionFunction(positions);
  33303. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33304. if (computeNormals) {
  33305. var indices = this.getIndices();
  33306. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33307. if (!normals) {
  33308. return this;
  33309. }
  33310. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33311. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33312. }
  33313. return this;
  33314. };
  33315. /**
  33316. * Creates a un-shared specific occurence of the geometry for the mesh.
  33317. * @returns the current mesh
  33318. */
  33319. Mesh.prototype.makeGeometryUnique = function () {
  33320. if (!this._geometry) {
  33321. return this;
  33322. }
  33323. var oldGeometry = this._geometry;
  33324. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33325. oldGeometry.releaseForMesh(this, true);
  33326. geometry.applyToMesh(this);
  33327. return this;
  33328. };
  33329. /**
  33330. * Set the index buffer of this mesh
  33331. * @param indices defines the source data
  33332. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33333. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33334. * @returns the current mesh
  33335. */
  33336. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33337. if (totalVertices === void 0) { totalVertices = null; }
  33338. if (updatable === void 0) { updatable = false; }
  33339. if (!this._geometry) {
  33340. var vertexData = new BABYLON.VertexData();
  33341. vertexData.indices = indices;
  33342. var scene = this.getScene();
  33343. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33344. }
  33345. else {
  33346. this._geometry.setIndices(indices, totalVertices, updatable);
  33347. }
  33348. return this;
  33349. };
  33350. /**
  33351. * Update the current index buffer
  33352. * @param indices defines the source data
  33353. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33354. * @returns the current mesh
  33355. */
  33356. Mesh.prototype.updateIndices = function (indices, offset) {
  33357. if (!this._geometry) {
  33358. return this;
  33359. }
  33360. this._geometry.updateIndices(indices, offset);
  33361. return this;
  33362. };
  33363. /**
  33364. * Invert the geometry to move from a right handed system to a left handed one.
  33365. * @returns the current mesh
  33366. */
  33367. Mesh.prototype.toLeftHanded = function () {
  33368. if (!this._geometry) {
  33369. return this;
  33370. }
  33371. this._geometry.toLeftHanded();
  33372. return this;
  33373. };
  33374. /** @hidden */
  33375. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33376. if (!this._geometry) {
  33377. return this;
  33378. }
  33379. var engine = this.getScene().getEngine();
  33380. // Wireframe
  33381. var indexToBind;
  33382. if (this._unIndexed) {
  33383. indexToBind = null;
  33384. }
  33385. else {
  33386. switch (fillMode) {
  33387. case BABYLON.Material.PointFillMode:
  33388. indexToBind = null;
  33389. break;
  33390. case BABYLON.Material.WireFrameFillMode:
  33391. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33392. break;
  33393. default:
  33394. case BABYLON.Material.TriangleFillMode:
  33395. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33396. break;
  33397. }
  33398. }
  33399. // VBOs
  33400. this._geometry._bind(effect, indexToBind);
  33401. return this;
  33402. };
  33403. /** @hidden */
  33404. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33405. if (alternate === void 0) { alternate = false; }
  33406. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33407. return this;
  33408. }
  33409. if (this._onBeforeDrawObservable) {
  33410. this._onBeforeDrawObservable.notifyObservers(this);
  33411. }
  33412. var scene = this.getScene();
  33413. var engine = scene.getEngine();
  33414. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33415. // or triangles as points
  33416. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33417. }
  33418. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33419. // Triangles as wireframe
  33420. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33421. }
  33422. else {
  33423. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33424. }
  33425. if (scene._isAlternateRenderingEnabled && !alternate) {
  33426. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33427. if (!effect || !scene.activeCamera) {
  33428. return this;
  33429. }
  33430. scene._switchToAlternateCameraConfiguration(true);
  33431. this._effectiveMaterial.bindView(effect);
  33432. this._effectiveMaterial.bindViewProjection(effect);
  33433. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33434. this._draw(subMesh, fillMode, instancesCount, true);
  33435. engine.setViewport(scene.activeCamera.viewport);
  33436. scene._switchToAlternateCameraConfiguration(false);
  33437. this._effectiveMaterial.bindView(effect);
  33438. this._effectiveMaterial.bindViewProjection(effect);
  33439. }
  33440. return this;
  33441. };
  33442. /**
  33443. * Registers for this mesh a javascript function called just before the rendering process
  33444. * @param func defines the function to call before rendering this mesh
  33445. * @returns the current mesh
  33446. */
  33447. Mesh.prototype.registerBeforeRender = function (func) {
  33448. this.onBeforeRenderObservable.add(func);
  33449. return this;
  33450. };
  33451. /**
  33452. * Disposes a previously registered javascript function called before the rendering
  33453. * @param func defines the function to remove
  33454. * @returns the current mesh
  33455. */
  33456. Mesh.prototype.unregisterBeforeRender = function (func) {
  33457. this.onBeforeRenderObservable.removeCallback(func);
  33458. return this;
  33459. };
  33460. /**
  33461. * Registers for this mesh a javascript function called just after the rendering is complete
  33462. * @param func defines the function to call after rendering this mesh
  33463. * @returns the current mesh
  33464. */
  33465. Mesh.prototype.registerAfterRender = function (func) {
  33466. this.onAfterRenderObservable.add(func);
  33467. return this;
  33468. };
  33469. /**
  33470. * Disposes a previously registered javascript function called after the rendering.
  33471. * @param func defines the function to remove
  33472. * @returns the current mesh
  33473. */
  33474. Mesh.prototype.unregisterAfterRender = function (func) {
  33475. this.onAfterRenderObservable.removeCallback(func);
  33476. return this;
  33477. };
  33478. /** @hidden */
  33479. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33480. var scene = this.getScene();
  33481. var batchCache = this._instanceDataStorage.batchCache;
  33482. batchCache.mustReturn = false;
  33483. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33484. batchCache.visibleInstances[subMeshId] = null;
  33485. if (this._instanceDataStorage.visibleInstances) {
  33486. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33487. var currentRenderId = scene.getRenderId();
  33488. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33489. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33490. var selfRenderId = this._renderId;
  33491. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33492. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33493. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33494. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33495. }
  33496. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33497. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33498. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33499. batchCache.mustReturn = true;
  33500. return batchCache;
  33501. }
  33502. if (currentRenderId !== selfRenderId) {
  33503. batchCache.renderSelf[subMeshId] = false;
  33504. }
  33505. }
  33506. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33507. }
  33508. return batchCache;
  33509. };
  33510. /** @hidden */
  33511. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33512. var visibleInstances = batch.visibleInstances[subMesh._id];
  33513. if (!visibleInstances) {
  33514. return this;
  33515. }
  33516. var matricesCount = visibleInstances.length + 1;
  33517. var bufferSize = matricesCount * 16 * 4;
  33518. var instanceStorage = this._instanceDataStorage;
  33519. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33520. var instancesBuffer = instanceStorage.instancesBuffer;
  33521. while (instanceStorage.instancesBufferSize < bufferSize) {
  33522. instanceStorage.instancesBufferSize *= 2;
  33523. }
  33524. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33525. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33526. }
  33527. var offset = 0;
  33528. var instancesCount = 0;
  33529. var world = this.getWorldMatrix();
  33530. if (batch.renderSelf[subMesh._id]) {
  33531. world.copyToArray(instanceStorage.instancesData, offset);
  33532. offset += 16;
  33533. instancesCount++;
  33534. }
  33535. if (visibleInstances) {
  33536. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33537. var instance = visibleInstances[instanceIndex];
  33538. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33539. offset += 16;
  33540. instancesCount++;
  33541. }
  33542. }
  33543. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33544. if (instancesBuffer) {
  33545. instancesBuffer.dispose();
  33546. }
  33547. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33548. instanceStorage.instancesBuffer = instancesBuffer;
  33549. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33550. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33551. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33552. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33553. }
  33554. else {
  33555. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33556. }
  33557. this._bind(subMesh, effect, fillMode);
  33558. this._draw(subMesh, fillMode, instancesCount);
  33559. engine.unbindInstanceAttributes();
  33560. return this;
  33561. };
  33562. /** @hidden */
  33563. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33564. var scene = this.getScene();
  33565. var engine = scene.getEngine();
  33566. if (hardwareInstancedRendering) {
  33567. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33568. }
  33569. else {
  33570. if (batch.renderSelf[subMesh._id]) {
  33571. // Draw
  33572. if (onBeforeDraw) {
  33573. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33574. }
  33575. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33576. }
  33577. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33578. if (visibleInstancesForSubMesh) {
  33579. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33580. var instance = visibleInstancesForSubMesh[instanceIndex];
  33581. // World
  33582. var world = instance.getWorldMatrix();
  33583. if (onBeforeDraw) {
  33584. onBeforeDraw(true, world, effectiveMaterial);
  33585. }
  33586. // Draw
  33587. this._draw(subMesh, fillMode);
  33588. }
  33589. }
  33590. }
  33591. return this;
  33592. };
  33593. /**
  33594. * 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
  33595. * @param subMesh defines the subMesh to render
  33596. * @param enableAlphaMode defines if alpha mode can be changed
  33597. * @returns the current mesh
  33598. */
  33599. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33600. if (this._checkOcclusionQuery()) {
  33601. return this;
  33602. }
  33603. var scene = this.getScene();
  33604. // Managing instances
  33605. var batch = this._getInstancesRenderList(subMesh._id);
  33606. if (batch.mustReturn) {
  33607. return this;
  33608. }
  33609. // Checking geometry state
  33610. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33611. return this;
  33612. }
  33613. if (this._onBeforeRenderObservable) {
  33614. this._onBeforeRenderObservable.notifyObservers(this);
  33615. }
  33616. var engine = scene.getEngine();
  33617. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33618. // Material
  33619. var material = subMesh.getMaterial();
  33620. if (!material) {
  33621. return this;
  33622. }
  33623. this._effectiveMaterial = material;
  33624. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33625. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33626. return this;
  33627. }
  33628. }
  33629. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33630. return this;
  33631. }
  33632. // Alpha mode
  33633. if (enableAlphaMode) {
  33634. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33635. }
  33636. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33637. var step = _a[_i];
  33638. step.action(this, subMesh, batch);
  33639. }
  33640. var effect;
  33641. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33642. effect = subMesh.effect;
  33643. }
  33644. else {
  33645. effect = this._effectiveMaterial.getEffect();
  33646. }
  33647. if (!effect) {
  33648. return this;
  33649. }
  33650. var sideOrientation = this.overrideMaterialSideOrientation;
  33651. if (sideOrientation == null) {
  33652. sideOrientation = this._effectiveMaterial.sideOrientation;
  33653. if (this._getWorldMatrixDeterminant() < 0) {
  33654. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33655. }
  33656. }
  33657. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33658. if (this._effectiveMaterial.forceDepthWrite) {
  33659. engine.setDepthWrite(true);
  33660. }
  33661. // Bind
  33662. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33663. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33664. this._bind(subMesh, effect, fillMode);
  33665. }
  33666. var world = this.getWorldMatrix();
  33667. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33668. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33669. }
  33670. else {
  33671. this._effectiveMaterial.bind(world, this);
  33672. }
  33673. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33674. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33675. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33676. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33677. }
  33678. // Draw
  33679. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33680. // Unbind
  33681. this._effectiveMaterial.unbind();
  33682. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33683. var step = _c[_b];
  33684. step.action(this, subMesh, batch);
  33685. }
  33686. if (this._onAfterRenderObservable) {
  33687. this._onAfterRenderObservable.notifyObservers(this);
  33688. }
  33689. return this;
  33690. };
  33691. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33692. if (isInstance && effectiveMaterial) {
  33693. effectiveMaterial.bindOnlyWorldMatrix(world);
  33694. }
  33695. };
  33696. /**
  33697. * Renormalize the mesh and patch it up if there are no weights
  33698. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33699. * However in the case of zero weights then we set just a single influence to 1.
  33700. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33701. */
  33702. Mesh.prototype.cleanMatrixWeights = function () {
  33703. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33704. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33705. this.normalizeSkinWeightsAndExtra();
  33706. }
  33707. else {
  33708. this.normalizeSkinFourWeights();
  33709. }
  33710. }
  33711. };
  33712. // faster 4 weight version.
  33713. Mesh.prototype.normalizeSkinFourWeights = function () {
  33714. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33715. var numWeights = matricesWeights.length;
  33716. for (var a = 0; a < numWeights; a += 4) {
  33717. // accumulate weights
  33718. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33719. // check for invalid weight and just set it to 1.
  33720. if (t === 0) {
  33721. matricesWeights[a] = 1;
  33722. }
  33723. else {
  33724. // renormalize so everything adds to 1 use reciprical
  33725. var recip = 1 / t;
  33726. matricesWeights[a] *= recip;
  33727. matricesWeights[a + 1] *= recip;
  33728. matricesWeights[a + 2] *= recip;
  33729. matricesWeights[a + 3] *= recip;
  33730. }
  33731. }
  33732. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33733. };
  33734. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33735. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33736. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33737. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33738. var numWeights = matricesWeights.length;
  33739. for (var a = 0; a < numWeights; a += 4) {
  33740. // accumulate weights
  33741. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33742. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33743. // check for invalid weight and just set it to 1.
  33744. if (t === 0) {
  33745. matricesWeights[a] = 1;
  33746. }
  33747. else {
  33748. // renormalize so everything adds to 1 use reciprical
  33749. var recip = 1 / t;
  33750. matricesWeights[a] *= recip;
  33751. matricesWeights[a + 1] *= recip;
  33752. matricesWeights[a + 2] *= recip;
  33753. matricesWeights[a + 3] *= recip;
  33754. // same goes for extras
  33755. matricesWeightsExtra[a] *= recip;
  33756. matricesWeightsExtra[a + 1] *= recip;
  33757. matricesWeightsExtra[a + 2] *= recip;
  33758. matricesWeightsExtra[a + 3] *= recip;
  33759. }
  33760. }
  33761. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33762. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33763. };
  33764. /**
  33765. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33766. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33767. * the user know there was an issue with importing the mesh
  33768. * @returns a validation object with skinned, valid and report string
  33769. */
  33770. Mesh.prototype.validateSkinning = function () {
  33771. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33772. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33773. if (matricesWeights === null || this.skeleton == null) {
  33774. return { skinned: false, valid: true, report: "not skinned" };
  33775. }
  33776. var numWeights = matricesWeights.length;
  33777. var numberNotSorted = 0;
  33778. var missingWeights = 0;
  33779. var maxUsedWeights = 0;
  33780. var numberNotNormalized = 0;
  33781. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33782. var usedWeightCounts = new Array();
  33783. for (var a = 0; a <= numInfluences; a++) {
  33784. usedWeightCounts[a] = 0;
  33785. }
  33786. var toleranceEpsilon = 0.001;
  33787. for (var a = 0; a < numWeights; a += 4) {
  33788. var lastWeight = matricesWeights[a];
  33789. var t = lastWeight;
  33790. var usedWeights = t === 0 ? 0 : 1;
  33791. for (var b = 1; b < numInfluences; b++) {
  33792. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33793. if (d > lastWeight) {
  33794. numberNotSorted++;
  33795. }
  33796. if (d !== 0) {
  33797. usedWeights++;
  33798. }
  33799. t += d;
  33800. lastWeight = d;
  33801. }
  33802. // count the buffer weights usage
  33803. usedWeightCounts[usedWeights]++;
  33804. // max influences
  33805. if (usedWeights > maxUsedWeights) {
  33806. maxUsedWeights = usedWeights;
  33807. }
  33808. // check for invalid weight and just set it to 1.
  33809. if (t === 0) {
  33810. missingWeights++;
  33811. }
  33812. else {
  33813. // renormalize so everything adds to 1 use reciprical
  33814. var recip = 1 / t;
  33815. var tolerance = 0;
  33816. for (b = 0; b < numInfluences; b++) {
  33817. if (b < 4) {
  33818. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33819. }
  33820. else {
  33821. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33822. }
  33823. }
  33824. // arbitary epsilon value for dicdating not normalized
  33825. if (tolerance > toleranceEpsilon) {
  33826. numberNotNormalized++;
  33827. }
  33828. }
  33829. }
  33830. // validate bone indices are in range of the skeleton
  33831. var numBones = this.skeleton.bones.length;
  33832. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33833. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33834. var numBadBoneIndices = 0;
  33835. for (var a = 0; a < numWeights; a++) {
  33836. for (var b = 0; b < numInfluences; b++) {
  33837. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33838. if (index >= numBones || index < 0) {
  33839. numBadBoneIndices++;
  33840. }
  33841. }
  33842. }
  33843. // log mesh stats
  33844. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33845. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33846. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33847. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33848. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33849. };
  33850. /** @hidden */
  33851. Mesh.prototype._checkDelayState = function () {
  33852. var scene = this.getScene();
  33853. if (this._geometry) {
  33854. this._geometry.load(scene);
  33855. }
  33856. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33857. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33858. this._queueLoad(scene);
  33859. }
  33860. return this;
  33861. };
  33862. Mesh.prototype._queueLoad = function (scene) {
  33863. var _this = this;
  33864. scene._addPendingData(this);
  33865. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33866. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33867. if (data instanceof ArrayBuffer) {
  33868. _this._delayLoadingFunction(data, _this);
  33869. }
  33870. else {
  33871. _this._delayLoadingFunction(JSON.parse(data), _this);
  33872. }
  33873. _this.instances.forEach(function (instance) {
  33874. instance._syncSubMeshes();
  33875. });
  33876. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33877. scene._removePendingData(_this);
  33878. }, function () { }, scene.offlineProvider, getBinaryData);
  33879. return this;
  33880. };
  33881. /**
  33882. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33883. * A mesh is in the frustum if its bounding box intersects the frustum
  33884. * @param frustumPlanes defines the frustum to test
  33885. * @returns true if the mesh is in the frustum planes
  33886. */
  33887. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33888. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33889. return false;
  33890. }
  33891. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33892. return false;
  33893. }
  33894. this._checkDelayState();
  33895. return true;
  33896. };
  33897. /**
  33898. * Sets the mesh material by the material or multiMaterial `id` property
  33899. * @param id is a string identifying the material or the multiMaterial
  33900. * @returns the current mesh
  33901. */
  33902. Mesh.prototype.setMaterialByID = function (id) {
  33903. var materials = this.getScene().materials;
  33904. var index;
  33905. for (index = materials.length - 1; index > -1; index--) {
  33906. if (materials[index].id === id) {
  33907. this.material = materials[index];
  33908. return this;
  33909. }
  33910. }
  33911. // Multi
  33912. var multiMaterials = this.getScene().multiMaterials;
  33913. for (index = multiMaterials.length - 1; index > -1; index--) {
  33914. if (multiMaterials[index].id === id) {
  33915. this.material = multiMaterials[index];
  33916. return this;
  33917. }
  33918. }
  33919. return this;
  33920. };
  33921. /**
  33922. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33923. * @returns an array of IAnimatable
  33924. */
  33925. Mesh.prototype.getAnimatables = function () {
  33926. var results = new Array();
  33927. if (this.material) {
  33928. results.push(this.material);
  33929. }
  33930. if (this.skeleton) {
  33931. results.push(this.skeleton);
  33932. }
  33933. return results;
  33934. };
  33935. /**
  33936. * Modifies the mesh geometry according to the passed transformation matrix.
  33937. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33938. * The mesh normals are modified using the same transformation.
  33939. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33940. * @param transform defines the transform matrix to use
  33941. * @see http://doc.babylonjs.com/resources/baking_transformations
  33942. * @returns the current mesh
  33943. */
  33944. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33945. // Position
  33946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33947. return this;
  33948. }
  33949. var submeshes = this.subMeshes.splice(0);
  33950. this._resetPointsArrayCache();
  33951. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33952. var temp = new Array();
  33953. var index;
  33954. for (index = 0; index < data.length; index += 3) {
  33955. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33956. }
  33957. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33958. // Normals
  33959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33960. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33961. temp = [];
  33962. for (index = 0; index < data.length; index += 3) {
  33963. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33964. }
  33965. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33966. }
  33967. // flip faces?
  33968. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33969. this.flipFaces();
  33970. }
  33971. // Restore submeshes
  33972. this.releaseSubMeshes();
  33973. this.subMeshes = submeshes;
  33974. return this;
  33975. };
  33976. /**
  33977. * Modifies the mesh geometry according to its own current World Matrix.
  33978. * The mesh World Matrix is then reset.
  33979. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33980. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33981. * @see http://doc.babylonjs.com/resources/baking_transformations
  33982. * @returns the current mesh
  33983. */
  33984. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33985. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33986. this.scaling.copyFromFloats(1, 1, 1);
  33987. this.position.copyFromFloats(0, 0, 0);
  33988. this.rotation.copyFromFloats(0, 0, 0);
  33989. //only if quaternion is already set
  33990. if (this.rotationQuaternion) {
  33991. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33992. }
  33993. this._worldMatrix = BABYLON.Matrix.Identity();
  33994. return this;
  33995. };
  33996. Object.defineProperty(Mesh.prototype, "_positions", {
  33997. // Cache
  33998. /** @hidden */
  33999. get: function () {
  34000. if (this._geometry) {
  34001. return this._geometry._positions;
  34002. }
  34003. return null;
  34004. },
  34005. enumerable: true,
  34006. configurable: true
  34007. });
  34008. /** @hidden */
  34009. Mesh.prototype._resetPointsArrayCache = function () {
  34010. if (this._geometry) {
  34011. this._geometry._resetPointsArrayCache();
  34012. }
  34013. return this;
  34014. };
  34015. /** @hidden */
  34016. Mesh.prototype._generatePointsArray = function () {
  34017. if (this._geometry) {
  34018. return this._geometry._generatePointsArray();
  34019. }
  34020. return false;
  34021. };
  34022. /**
  34023. * Returns a new Mesh object generated from the current mesh properties.
  34024. * This method must not get confused with createInstance()
  34025. * @param name is a string, the name given to the new mesh
  34026. * @param newParent can be any Node object (default `null`)
  34027. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  34028. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  34029. * @returns a new mesh
  34030. */
  34031. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  34032. if (name === void 0) { name = ""; }
  34033. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  34034. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  34035. };
  34036. /**
  34037. * Releases resources associated with this mesh.
  34038. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  34039. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  34040. */
  34041. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  34042. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  34043. this.morphTargetManager = null;
  34044. if (this._geometry) {
  34045. this._geometry.releaseForMesh(this, true);
  34046. }
  34047. if (this._onBeforeDrawObservable) {
  34048. this._onBeforeDrawObservable.clear();
  34049. }
  34050. if (this._onBeforeRenderObservable) {
  34051. this._onBeforeRenderObservable.clear();
  34052. }
  34053. if (this._onAfterRenderObservable) {
  34054. this._onAfterRenderObservable.clear();
  34055. }
  34056. // Sources
  34057. if (this._scene.useClonedMeshhMap) {
  34058. if (this.meshMap) {
  34059. for (var uniqueId in this.meshMap) {
  34060. var mesh = this.meshMap[uniqueId];
  34061. if (mesh) {
  34062. mesh._source = null;
  34063. this.meshMap[uniqueId] = undefined;
  34064. }
  34065. }
  34066. }
  34067. if (this._source && this._source.meshMap) {
  34068. this._source.meshMap[this.uniqueId] = undefined;
  34069. }
  34070. }
  34071. else {
  34072. var meshes = this.getScene().meshes;
  34073. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34074. var abstractMesh = meshes_1[_i];
  34075. var mesh = abstractMesh;
  34076. if (mesh._source && mesh._source === this) {
  34077. mesh._source = null;
  34078. }
  34079. }
  34080. }
  34081. this._source = null;
  34082. // Instances
  34083. if (this._instanceDataStorage.instancesBuffer) {
  34084. this._instanceDataStorage.instancesBuffer.dispose();
  34085. this._instanceDataStorage.instancesBuffer = null;
  34086. }
  34087. while (this.instances.length) {
  34088. this.instances[0].dispose();
  34089. }
  34090. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34091. };
  34092. /**
  34093. * Modifies the mesh geometry according to a displacement map.
  34094. * 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.
  34095. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34096. * @param url is a string, the URL from the image file is to be downloaded.
  34097. * @param minHeight is the lower limit of the displacement.
  34098. * @param maxHeight is the upper limit of the displacement.
  34099. * @param 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.
  34100. * @param uvOffset is an optional vector2 used to offset UV.
  34101. * @param uvScale is an optional vector2 used to scale UV.
  34102. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  34103. * @returns the Mesh.
  34104. */
  34105. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34106. var _this = this;
  34107. if (forceUpdate === void 0) { forceUpdate = false; }
  34108. var scene = this.getScene();
  34109. var onload = function (img) {
  34110. // Getting height map data
  34111. var canvas = document.createElement("canvas");
  34112. var context = canvas.getContext("2d");
  34113. var heightMapWidth = img.width;
  34114. var heightMapHeight = img.height;
  34115. canvas.width = heightMapWidth;
  34116. canvas.height = heightMapHeight;
  34117. context.drawImage(img, 0, 0);
  34118. // Create VertexData from map data
  34119. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34120. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34121. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34122. //execute success callback, if set
  34123. if (onSuccess) {
  34124. onSuccess(_this);
  34125. }
  34126. };
  34127. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34128. return this;
  34129. };
  34130. /**
  34131. * Modifies the mesh geometry according to a displacementMap buffer.
  34132. * 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.
  34133. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34134. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34135. * @param heightMapWidth is the width of the buffer image.
  34136. * @param heightMapHeight is the height of the buffer image.
  34137. * @param minHeight is the lower limit of the displacement.
  34138. * @param maxHeight is the upper limit of the displacement.
  34139. * @param 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.
  34140. * @param uvOffset is an optional vector2 used to offset UV.
  34141. * @param uvScale is an optional vector2 used to scale UV.
  34142. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  34143. * @returns the Mesh.
  34144. */
  34145. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34146. if (forceUpdate === void 0) { forceUpdate = false; }
  34147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34148. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34149. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34150. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34151. return this;
  34152. }
  34153. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34154. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34155. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34156. var position = BABYLON.Vector3.Zero();
  34157. var normal = BABYLON.Vector3.Zero();
  34158. var uv = BABYLON.Vector2.Zero();
  34159. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34160. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34161. for (var index = 0; index < positions.length; index += 3) {
  34162. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34163. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34164. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34165. // Compute height
  34166. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34167. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34168. var pos = (u + v * heightMapWidth) * 4;
  34169. var r = buffer[pos] / 255.0;
  34170. var g = buffer[pos + 1] / 255.0;
  34171. var b = buffer[pos + 2] / 255.0;
  34172. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34173. normal.normalize();
  34174. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34175. position = position.add(normal);
  34176. position.toArray(positions, index);
  34177. }
  34178. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34179. if (forceUpdate) {
  34180. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34181. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34182. }
  34183. else {
  34184. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34185. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34186. }
  34187. return this;
  34188. };
  34189. /**
  34190. * Modify the mesh to get a flat shading rendering.
  34191. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34192. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34193. * @returns current mesh
  34194. */
  34195. Mesh.prototype.convertToFlatShadedMesh = function () {
  34196. var kinds = this.getVerticesDataKinds();
  34197. var vbs = {};
  34198. var data = {};
  34199. var newdata = {};
  34200. var updatableNormals = false;
  34201. var kindIndex;
  34202. var kind;
  34203. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34204. kind = kinds[kindIndex];
  34205. var vertexBuffer = this.getVertexBuffer(kind);
  34206. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34207. updatableNormals = vertexBuffer.isUpdatable();
  34208. kinds.splice(kindIndex, 1);
  34209. kindIndex--;
  34210. continue;
  34211. }
  34212. vbs[kind] = vertexBuffer;
  34213. data[kind] = vbs[kind].getData();
  34214. newdata[kind] = [];
  34215. }
  34216. // Save previous submeshes
  34217. var previousSubmeshes = this.subMeshes.slice(0);
  34218. var indices = this.getIndices();
  34219. var totalIndices = this.getTotalIndices();
  34220. // Generating unique vertices per face
  34221. var index;
  34222. for (index = 0; index < totalIndices; index++) {
  34223. var vertexIndex = indices[index];
  34224. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34225. kind = kinds[kindIndex];
  34226. var stride = vbs[kind].getStrideSize();
  34227. for (var offset = 0; offset < stride; offset++) {
  34228. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34229. }
  34230. }
  34231. }
  34232. // Updating faces & normal
  34233. var normals = [];
  34234. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34235. for (index = 0; index < totalIndices; index += 3) {
  34236. indices[index] = index;
  34237. indices[index + 1] = index + 1;
  34238. indices[index + 2] = index + 2;
  34239. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34240. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34241. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34242. var p1p2 = p1.subtract(p2);
  34243. var p3p2 = p3.subtract(p2);
  34244. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34245. // Store same normals for every vertex
  34246. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34247. normals.push(normal.x);
  34248. normals.push(normal.y);
  34249. normals.push(normal.z);
  34250. }
  34251. }
  34252. this.setIndices(indices);
  34253. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34254. // Updating vertex buffers
  34255. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34256. kind = kinds[kindIndex];
  34257. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34258. }
  34259. // Updating submeshes
  34260. this.releaseSubMeshes();
  34261. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34262. var previousOne = previousSubmeshes[submeshIndex];
  34263. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34264. }
  34265. this.synchronizeInstances();
  34266. return this;
  34267. };
  34268. /**
  34269. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34270. * In other words, more vertices, no more indices and a single bigger VBO.
  34271. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34272. * @returns current mesh
  34273. */
  34274. Mesh.prototype.convertToUnIndexedMesh = function () {
  34275. var kinds = this.getVerticesDataKinds();
  34276. var vbs = {};
  34277. var data = {};
  34278. var newdata = {};
  34279. var kindIndex;
  34280. var kind;
  34281. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34282. kind = kinds[kindIndex];
  34283. var vertexBuffer = this.getVertexBuffer(kind);
  34284. vbs[kind] = vertexBuffer;
  34285. data[kind] = vbs[kind].getData();
  34286. newdata[kind] = [];
  34287. }
  34288. // Save previous submeshes
  34289. var previousSubmeshes = this.subMeshes.slice(0);
  34290. var indices = this.getIndices();
  34291. var totalIndices = this.getTotalIndices();
  34292. // Generating unique vertices per face
  34293. var index;
  34294. for (index = 0; index < totalIndices; index++) {
  34295. var vertexIndex = indices[index];
  34296. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34297. kind = kinds[kindIndex];
  34298. var stride = vbs[kind].getStrideSize();
  34299. for (var offset = 0; offset < stride; offset++) {
  34300. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34301. }
  34302. }
  34303. }
  34304. // Updating indices
  34305. for (index = 0; index < totalIndices; index += 3) {
  34306. indices[index] = index;
  34307. indices[index + 1] = index + 1;
  34308. indices[index + 2] = index + 2;
  34309. }
  34310. this.setIndices(indices);
  34311. // Updating vertex buffers
  34312. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34313. kind = kinds[kindIndex];
  34314. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34315. }
  34316. // Updating submeshes
  34317. this.releaseSubMeshes();
  34318. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34319. var previousOne = previousSubmeshes[submeshIndex];
  34320. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34321. }
  34322. this._unIndexed = true;
  34323. this.synchronizeInstances();
  34324. return this;
  34325. };
  34326. /**
  34327. * Inverses facet orientations.
  34328. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34329. * @param flipNormals will also inverts the normals
  34330. * @returns current mesh
  34331. */
  34332. Mesh.prototype.flipFaces = function (flipNormals) {
  34333. if (flipNormals === void 0) { flipNormals = false; }
  34334. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34335. var i;
  34336. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34337. for (i = 0; i < vertex_data.normals.length; i++) {
  34338. vertex_data.normals[i] *= -1;
  34339. }
  34340. }
  34341. if (vertex_data.indices) {
  34342. var temp;
  34343. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34344. // reassign indices
  34345. temp = vertex_data.indices[i + 1];
  34346. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34347. vertex_data.indices[i + 2] = temp;
  34348. }
  34349. }
  34350. vertex_data.applyToMesh(this);
  34351. return this;
  34352. };
  34353. // Instances
  34354. /**
  34355. * Creates a new InstancedMesh object from the mesh model.
  34356. * Warning : this method is not supported for Line mesh and LineSystem
  34357. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34358. * @param name defines the name of the new instance
  34359. * @returns a new InstancedMesh
  34360. */
  34361. Mesh.prototype.createInstance = function (name) {
  34362. return new BABYLON.InstancedMesh(name, this);
  34363. };
  34364. /**
  34365. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34366. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34367. * @returns the current mesh
  34368. */
  34369. Mesh.prototype.synchronizeInstances = function () {
  34370. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34371. var instance = this.instances[instanceIndex];
  34372. instance._syncSubMeshes();
  34373. }
  34374. return this;
  34375. };
  34376. /**
  34377. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34378. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34379. * This should be used together with the simplification to avoid disappearing triangles.
  34380. * @param successCallback an optional success callback to be called after the optimization finished.
  34381. * @returns the current mesh
  34382. */
  34383. Mesh.prototype.optimizeIndices = function (successCallback) {
  34384. var _this = this;
  34385. var indices = this.getIndices();
  34386. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34387. if (!positions || !indices) {
  34388. return this;
  34389. }
  34390. var vectorPositions = new Array();
  34391. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34392. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34393. }
  34394. var dupes = new Array();
  34395. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34396. var realPos = vectorPositions.length - 1 - iteration;
  34397. var testedPosition = vectorPositions[realPos];
  34398. for (var j = 0; j < realPos; ++j) {
  34399. var againstPosition = vectorPositions[j];
  34400. if (testedPosition.equals(againstPosition)) {
  34401. dupes[realPos] = j;
  34402. break;
  34403. }
  34404. }
  34405. }, function () {
  34406. for (var i = 0; i < indices.length; ++i) {
  34407. indices[i] = dupes[indices[i]] || indices[i];
  34408. }
  34409. //indices are now reordered
  34410. var originalSubMeshes = _this.subMeshes.slice(0);
  34411. _this.setIndices(indices);
  34412. _this.subMeshes = originalSubMeshes;
  34413. if (successCallback) {
  34414. successCallback(_this);
  34415. }
  34416. });
  34417. return this;
  34418. };
  34419. /**
  34420. * Serialize current mesh
  34421. * @param serializationObject defines the object which will receive the serialization data
  34422. */
  34423. Mesh.prototype.serialize = function (serializationObject) {
  34424. serializationObject.name = this.name;
  34425. serializationObject.id = this.id;
  34426. serializationObject.type = this.getClassName();
  34427. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34428. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34429. }
  34430. serializationObject.position = this.position.asArray();
  34431. if (this.rotationQuaternion) {
  34432. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34433. }
  34434. else if (this.rotation) {
  34435. serializationObject.rotation = this.rotation.asArray();
  34436. }
  34437. serializationObject.scaling = this.scaling.asArray();
  34438. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34439. serializationObject.isEnabled = this.isEnabled(false);
  34440. serializationObject.isVisible = this.isVisible;
  34441. serializationObject.infiniteDistance = this.infiniteDistance;
  34442. serializationObject.pickable = this.isPickable;
  34443. serializationObject.receiveShadows = this.receiveShadows;
  34444. serializationObject.billboardMode = this.billboardMode;
  34445. serializationObject.visibility = this.visibility;
  34446. serializationObject.checkCollisions = this.checkCollisions;
  34447. serializationObject.isBlocker = this.isBlocker;
  34448. // Parent
  34449. if (this.parent) {
  34450. serializationObject.parentId = this.parent.id;
  34451. }
  34452. // Geometry
  34453. serializationObject.isUnIndexed = this.isUnIndexed;
  34454. var geometry = this._geometry;
  34455. if (geometry) {
  34456. var geometryId = geometry.id;
  34457. serializationObject.geometryId = geometryId;
  34458. // SubMeshes
  34459. serializationObject.subMeshes = [];
  34460. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34461. var subMesh = this.subMeshes[subIndex];
  34462. serializationObject.subMeshes.push({
  34463. materialIndex: subMesh.materialIndex,
  34464. verticesStart: subMesh.verticesStart,
  34465. verticesCount: subMesh.verticesCount,
  34466. indexStart: subMesh.indexStart,
  34467. indexCount: subMesh.indexCount
  34468. });
  34469. }
  34470. }
  34471. // Material
  34472. if (this.material) {
  34473. serializationObject.materialId = this.material.id;
  34474. }
  34475. else {
  34476. this.material = null;
  34477. }
  34478. // Morph targets
  34479. if (this.morphTargetManager) {
  34480. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34481. }
  34482. // Skeleton
  34483. if (this.skeleton) {
  34484. serializationObject.skeletonId = this.skeleton.id;
  34485. }
  34486. // Physics
  34487. //TODO implement correct serialization for physics impostors.
  34488. var impostor = this.getPhysicsImpostor();
  34489. if (impostor) {
  34490. serializationObject.physicsMass = impostor.getParam("mass");
  34491. serializationObject.physicsFriction = impostor.getParam("friction");
  34492. serializationObject.physicsRestitution = impostor.getParam("mass");
  34493. serializationObject.physicsImpostor = impostor.type;
  34494. }
  34495. // Metadata
  34496. if (this.metadata) {
  34497. serializationObject.metadata = this.metadata;
  34498. }
  34499. // Instances
  34500. serializationObject.instances = [];
  34501. for (var index = 0; index < this.instances.length; index++) {
  34502. var instance = this.instances[index];
  34503. if (instance.doNotSerialize) {
  34504. continue;
  34505. }
  34506. var serializationInstance = {
  34507. name: instance.name,
  34508. id: instance.id,
  34509. position: instance.position.asArray(),
  34510. scaling: instance.scaling.asArray()
  34511. };
  34512. if (instance.parent) {
  34513. serializationInstance.parentId = instance.parent.id;
  34514. }
  34515. if (instance.rotationQuaternion) {
  34516. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34517. }
  34518. else if (instance.rotation) {
  34519. serializationInstance.rotation = instance.rotation.asArray();
  34520. }
  34521. serializationObject.instances.push(serializationInstance);
  34522. // Animations
  34523. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34524. serializationInstance.ranges = instance.serializeAnimationRanges();
  34525. }
  34526. //
  34527. // Animations
  34528. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34529. serializationObject.ranges = this.serializeAnimationRanges();
  34530. // Layer mask
  34531. serializationObject.layerMask = this.layerMask;
  34532. // Alpha
  34533. serializationObject.alphaIndex = this.alphaIndex;
  34534. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34535. // Overlay
  34536. serializationObject.overlayAlpha = this.overlayAlpha;
  34537. serializationObject.overlayColor = this.overlayColor.asArray();
  34538. serializationObject.renderOverlay = this.renderOverlay;
  34539. // Fog
  34540. serializationObject.applyFog = this.applyFog;
  34541. // Action Manager
  34542. if (this.actionManager) {
  34543. serializationObject.actions = this.actionManager.serialize(this.name);
  34544. }
  34545. };
  34546. /** @hidden */
  34547. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34548. if (!this.geometry) {
  34549. return;
  34550. }
  34551. this._markSubMeshesAsAttributesDirty();
  34552. var morphTargetManager = this._morphTargetManager;
  34553. if (morphTargetManager && morphTargetManager.vertexCount) {
  34554. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34555. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34556. this.morphTargetManager = null;
  34557. return;
  34558. }
  34559. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34560. var morphTarget = morphTargetManager.getActiveTarget(index);
  34561. var positions = morphTarget.getPositions();
  34562. if (!positions) {
  34563. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34564. return;
  34565. }
  34566. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34567. var normals = morphTarget.getNormals();
  34568. if (normals) {
  34569. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34570. }
  34571. var tangents = morphTarget.getTangents();
  34572. if (tangents) {
  34573. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34574. }
  34575. }
  34576. }
  34577. else {
  34578. var index = 0;
  34579. // Positions
  34580. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34581. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34582. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34583. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34584. }
  34585. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34586. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34587. }
  34588. index++;
  34589. }
  34590. }
  34591. };
  34592. // Statics
  34593. /**
  34594. * Returns a new Mesh object parsed from the source provided.
  34595. * @param parsedMesh is the source
  34596. * @param scene defines the hosting scene
  34597. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34598. * @returns a new Mesh
  34599. */
  34600. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34601. var mesh;
  34602. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34603. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34604. }
  34605. else {
  34606. mesh = new Mesh(parsedMesh.name, scene);
  34607. }
  34608. mesh.id = parsedMesh.id;
  34609. if (BABYLON.Tags) {
  34610. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34611. }
  34612. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34613. if (parsedMesh.metadata !== undefined) {
  34614. mesh.metadata = parsedMesh.metadata;
  34615. }
  34616. if (parsedMesh.rotationQuaternion) {
  34617. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34618. }
  34619. else if (parsedMesh.rotation) {
  34620. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34621. }
  34622. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34623. if (parsedMesh.localMatrix) {
  34624. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34625. }
  34626. else if (parsedMesh.pivotMatrix) {
  34627. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34628. }
  34629. mesh.setEnabled(parsedMesh.isEnabled);
  34630. mesh.isVisible = parsedMesh.isVisible;
  34631. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34632. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34633. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34634. if (parsedMesh.applyFog !== undefined) {
  34635. mesh.applyFog = parsedMesh.applyFog;
  34636. }
  34637. if (parsedMesh.pickable !== undefined) {
  34638. mesh.isPickable = parsedMesh.pickable;
  34639. }
  34640. if (parsedMesh.alphaIndex !== undefined) {
  34641. mesh.alphaIndex = parsedMesh.alphaIndex;
  34642. }
  34643. mesh.receiveShadows = parsedMesh.receiveShadows;
  34644. mesh.billboardMode = parsedMesh.billboardMode;
  34645. if (parsedMesh.visibility !== undefined) {
  34646. mesh.visibility = parsedMesh.visibility;
  34647. }
  34648. mesh.checkCollisions = parsedMesh.checkCollisions;
  34649. if (parsedMesh.isBlocker !== undefined) {
  34650. mesh.isBlocker = parsedMesh.isBlocker;
  34651. }
  34652. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34653. // freezeWorldMatrix
  34654. if (parsedMesh.freezeWorldMatrix) {
  34655. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34656. }
  34657. // Parent
  34658. if (parsedMesh.parentId) {
  34659. mesh._waitingParentId = parsedMesh.parentId;
  34660. }
  34661. // Actions
  34662. if (parsedMesh.actions !== undefined) {
  34663. mesh._waitingActions = parsedMesh.actions;
  34664. }
  34665. // Overlay
  34666. if (parsedMesh.overlayAlpha !== undefined) {
  34667. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34668. }
  34669. if (parsedMesh.overlayColor !== undefined) {
  34670. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34671. }
  34672. if (parsedMesh.renderOverlay !== undefined) {
  34673. mesh.renderOverlay = parsedMesh.renderOverlay;
  34674. }
  34675. // Geometry
  34676. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34677. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34678. if (parsedMesh.delayLoadingFile) {
  34679. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34680. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34681. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34682. if (parsedMesh._binaryInfo) {
  34683. mesh._binaryInfo = parsedMesh._binaryInfo;
  34684. }
  34685. mesh._delayInfo = [];
  34686. if (parsedMesh.hasUVs) {
  34687. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34688. }
  34689. if (parsedMesh.hasUVs2) {
  34690. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34691. }
  34692. if (parsedMesh.hasUVs3) {
  34693. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34694. }
  34695. if (parsedMesh.hasUVs4) {
  34696. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34697. }
  34698. if (parsedMesh.hasUVs5) {
  34699. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34700. }
  34701. if (parsedMesh.hasUVs6) {
  34702. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34703. }
  34704. if (parsedMesh.hasColors) {
  34705. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34706. }
  34707. if (parsedMesh.hasMatricesIndices) {
  34708. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34709. }
  34710. if (parsedMesh.hasMatricesWeights) {
  34711. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34712. }
  34713. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34714. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34715. mesh._checkDelayState();
  34716. }
  34717. }
  34718. else {
  34719. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34720. }
  34721. // Material
  34722. if (parsedMesh.materialId) {
  34723. mesh.setMaterialByID(parsedMesh.materialId);
  34724. }
  34725. else {
  34726. mesh.material = null;
  34727. }
  34728. // Morph targets
  34729. if (parsedMesh.morphTargetManagerId > -1) {
  34730. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34731. }
  34732. // Skeleton
  34733. if (parsedMesh.skeletonId > -1) {
  34734. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34735. if (parsedMesh.numBoneInfluencers) {
  34736. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34737. }
  34738. }
  34739. // Animations
  34740. if (parsedMesh.animations) {
  34741. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34742. var parsedAnimation = parsedMesh.animations[animationIndex];
  34743. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34744. }
  34745. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34746. }
  34747. if (parsedMesh.autoAnimate) {
  34748. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34749. }
  34750. // Layer Mask
  34751. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34752. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34753. }
  34754. else {
  34755. mesh.layerMask = 0x0FFFFFFF;
  34756. }
  34757. // Physics
  34758. if (parsedMesh.physicsImpostor) {
  34759. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34760. mass: parsedMesh.physicsMass,
  34761. friction: parsedMesh.physicsFriction,
  34762. restitution: parsedMesh.physicsRestitution
  34763. }, scene);
  34764. }
  34765. // Instances
  34766. if (parsedMesh.instances) {
  34767. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34768. var parsedInstance = parsedMesh.instances[index];
  34769. var instance = mesh.createInstance(parsedInstance.name);
  34770. if (parsedInstance.id) {
  34771. instance.id = parsedInstance.id;
  34772. }
  34773. if (BABYLON.Tags) {
  34774. if (parsedInstance.tags) {
  34775. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34776. }
  34777. else {
  34778. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34779. }
  34780. }
  34781. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34782. if (parsedInstance.parentId) {
  34783. instance._waitingParentId = parsedInstance.parentId;
  34784. }
  34785. if (parsedInstance.rotationQuaternion) {
  34786. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34787. }
  34788. else if (parsedInstance.rotation) {
  34789. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34790. }
  34791. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34792. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34793. instance.checkCollisions = parsedInstance.checkCollisions;
  34794. }
  34795. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34796. instance.isPickable = parsedInstance.pickable;
  34797. }
  34798. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34799. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34800. }
  34801. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34802. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34803. }
  34804. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34805. instance.alphaIndex = parsedInstance.alphaIndex;
  34806. }
  34807. // Physics
  34808. if (parsedInstance.physicsImpostor) {
  34809. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34810. mass: parsedInstance.physicsMass,
  34811. friction: parsedInstance.physicsFriction,
  34812. restitution: parsedInstance.physicsRestitution
  34813. }, scene);
  34814. }
  34815. // Animation
  34816. if (parsedInstance.animations) {
  34817. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34818. parsedAnimation = parsedInstance.animations[animationIndex];
  34819. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34820. }
  34821. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34822. if (parsedInstance.autoAnimate) {
  34823. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34824. }
  34825. }
  34826. }
  34827. }
  34828. return mesh;
  34829. };
  34830. /**
  34831. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34832. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34833. * @param name defines the name of the mesh to create
  34834. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34835. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34836. * @param closePath creates a seam between the first and the last points of each path of the path array
  34837. * @param offset is taken in account only if the `pathArray` is containing a single path
  34838. * @param scene defines the hosting scene
  34839. * @param updatable defines if the mesh must be flagged as updatable
  34840. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34841. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34842. * @returns a new Mesh
  34843. */
  34844. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34845. if (closeArray === void 0) { closeArray = false; }
  34846. if (updatable === void 0) { updatable = false; }
  34847. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34848. pathArray: pathArray,
  34849. closeArray: closeArray,
  34850. closePath: closePath,
  34851. offset: offset,
  34852. updatable: updatable,
  34853. sideOrientation: sideOrientation,
  34854. instance: instance
  34855. }, scene);
  34856. };
  34857. /**
  34858. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34859. * @param name defines the name of the mesh to create
  34860. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34861. * @param 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
  34862. * @param scene defines the hosting scene
  34863. * @param updatable defines if the mesh must be flagged as updatable
  34864. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34865. * @returns a new Mesh
  34866. */
  34867. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34868. if (scene === void 0) { scene = null; }
  34869. var options = {
  34870. radius: radius,
  34871. tessellation: tessellation,
  34872. sideOrientation: sideOrientation,
  34873. updatable: updatable
  34874. };
  34875. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34876. };
  34877. /**
  34878. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34879. * @param name defines the name of the mesh to create
  34880. * @param size sets the size (float) of each box side (default 1)
  34881. * @param scene defines the hosting scene
  34882. * @param updatable defines if the mesh must be flagged as updatable
  34883. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34884. * @returns a new Mesh
  34885. */
  34886. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34887. if (scene === void 0) { scene = null; }
  34888. var options = {
  34889. size: size,
  34890. sideOrientation: sideOrientation,
  34891. updatable: updatable
  34892. };
  34893. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34894. };
  34895. /**
  34896. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34897. * @param name defines the name of the mesh to create
  34898. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34899. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34900. * @param scene defines the hosting scene
  34901. * @param updatable defines if the mesh must be flagged as updatable
  34902. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34903. * @returns a new Mesh
  34904. */
  34905. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34906. var options = {
  34907. segments: segments,
  34908. diameterX: diameter,
  34909. diameterY: diameter,
  34910. diameterZ: diameter,
  34911. sideOrientation: sideOrientation,
  34912. updatable: updatable
  34913. };
  34914. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34915. };
  34916. /**
  34917. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34918. * @param name defines the name of the mesh to create
  34919. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34920. * @param diameterTop set the top cap diameter (floats, default 1)
  34921. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34922. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34923. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34924. * @param scene defines the hosting scene
  34925. * @param updatable defines if the mesh must be flagged as updatable
  34926. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34927. * @returns a new Mesh
  34928. */
  34929. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34930. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34931. if (scene !== undefined) {
  34932. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34933. updatable = scene;
  34934. }
  34935. scene = subdivisions;
  34936. subdivisions = 1;
  34937. }
  34938. var options = {
  34939. height: height,
  34940. diameterTop: diameterTop,
  34941. diameterBottom: diameterBottom,
  34942. tessellation: tessellation,
  34943. subdivisions: subdivisions,
  34944. sideOrientation: sideOrientation,
  34945. updatable: updatable
  34946. };
  34947. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34948. };
  34949. // Torus (Code from SharpDX.org)
  34950. /**
  34951. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34952. * @param name defines the name of the mesh to create
  34953. * @param diameter sets the diameter size (float) of the torus (default 1)
  34954. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34955. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34956. * @param scene defines the hosting scene
  34957. * @param updatable defines if the mesh must be flagged as updatable
  34958. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34959. * @returns a new Mesh
  34960. */
  34961. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34962. var options = {
  34963. diameter: diameter,
  34964. thickness: thickness,
  34965. tessellation: tessellation,
  34966. sideOrientation: sideOrientation,
  34967. updatable: updatable
  34968. };
  34969. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34970. };
  34971. /**
  34972. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34973. * @param name defines the name of the mesh to create
  34974. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34975. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34976. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34977. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34978. * @param p the number of windings on X axis (positive integers, default 2)
  34979. * @param q the number of windings on Y axis (positive integers, default 3)
  34980. * @param scene defines the hosting scene
  34981. * @param updatable defines if the mesh must be flagged as updatable
  34982. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34983. * @returns a new Mesh
  34984. */
  34985. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34986. var options = {
  34987. radius: radius,
  34988. tube: tube,
  34989. radialSegments: radialSegments,
  34990. tubularSegments: tubularSegments,
  34991. p: p,
  34992. q: q,
  34993. sideOrientation: sideOrientation,
  34994. updatable: updatable
  34995. };
  34996. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34997. };
  34998. /**
  34999. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  35000. * @param name defines the name of the mesh to create
  35001. * @param points is an array successive Vector3
  35002. * @param scene defines the hosting scene
  35003. * @param updatable defines if the mesh must be flagged as updatable
  35004. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  35005. * @returns a new Mesh
  35006. */
  35007. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  35008. if (scene === void 0) { scene = null; }
  35009. if (updatable === void 0) { updatable = false; }
  35010. if (instance === void 0) { instance = null; }
  35011. var options = {
  35012. points: points,
  35013. updatable: updatable,
  35014. instance: instance
  35015. };
  35016. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  35017. };
  35018. /**
  35019. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  35020. * @param name defines the name of the mesh to create
  35021. * @param points is an array successive Vector3
  35022. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  35023. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  35024. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  35025. * @param scene defines the hosting scene
  35026. * @param updatable defines if the mesh must be flagged as updatable
  35027. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  35028. * @returns a new Mesh
  35029. */
  35030. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  35031. if (scene === void 0) { scene = null; }
  35032. var options = {
  35033. points: points,
  35034. dashSize: dashSize,
  35035. gapSize: gapSize,
  35036. dashNb: dashNb,
  35037. updatable: updatable,
  35038. instance: instance
  35039. };
  35040. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  35041. };
  35042. /**
  35043. * Creates a polygon mesh.
  35044. * Please consider using the same method from the MeshBuilder class instead.
  35045. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  35046. * 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.
  35047. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35049. * Remember you can only change the shape positions, not their number when updating a polygon.
  35050. */
  35051. /**
  35052. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35053. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35054. * @param name defines the name of the mesh to create
  35055. * @param 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
  35056. * @param scene defines the hosting scene
  35057. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35058. * @param updatable defines if the mesh must be flagged as updatable
  35059. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35060. * @returns a new Mesh
  35061. */
  35062. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35063. var options = {
  35064. shape: shape,
  35065. holes: holes,
  35066. updatable: updatable,
  35067. sideOrientation: sideOrientation
  35068. };
  35069. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35070. };
  35071. /**
  35072. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35073. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35074. * @param name defines the name of the mesh to create
  35075. * @param 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
  35076. * @param depth defines the height of extrusion
  35077. * @param scene defines the hosting scene
  35078. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35079. * @param updatable defines if the mesh must be flagged as updatable
  35080. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35081. * @returns a new Mesh
  35082. */
  35083. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35084. var options = {
  35085. shape: shape,
  35086. holes: holes,
  35087. depth: depth,
  35088. updatable: updatable,
  35089. sideOrientation: sideOrientation
  35090. };
  35091. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35092. };
  35093. /**
  35094. * Creates an extruded shape mesh.
  35095. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  35096. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35097. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35098. * @param name defines the name of the mesh to create
  35099. * @param 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
  35100. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35101. * @param scale is the value to scale the shape
  35102. * @param rotation 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
  35103. * @param 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
  35104. * @param scene defines the hosting scene
  35105. * @param updatable defines if the mesh must be flagged as updatable
  35106. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35107. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  35108. * @returns a new Mesh
  35109. */
  35110. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35111. if (scene === void 0) { scene = null; }
  35112. var options = {
  35113. shape: shape,
  35114. path: path,
  35115. scale: scale,
  35116. rotation: rotation,
  35117. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35118. sideOrientation: sideOrientation,
  35119. instance: instance,
  35120. updatable: updatable
  35121. };
  35122. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35123. };
  35124. /**
  35125. * Creates an custom extruded shape mesh.
  35126. * The custom extrusion is a parametric shape.
  35127. * It has no predefined shape. Its final shape will depend on the input parameters.
  35128. * Please consider using the same method from the MeshBuilder class instead
  35129. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35130. * @param name defines the name of the mesh to create
  35131. * @param 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
  35132. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35133. * @param scaleFunction is a custom Javascript function called on each path point
  35134. * @param rotationFunction is a custom Javascript function called on each path point
  35135. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35136. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35137. * @param 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
  35138. * @param scene defines the hosting scene
  35139. * @param updatable defines if the mesh must be flagged as updatable
  35140. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35141. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  35142. * @returns a new Mesh
  35143. */
  35144. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35145. var options = {
  35146. shape: shape,
  35147. path: path,
  35148. scaleFunction: scaleFunction,
  35149. rotationFunction: rotationFunction,
  35150. ribbonCloseArray: ribbonCloseArray,
  35151. ribbonClosePath: ribbonClosePath,
  35152. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35153. sideOrientation: sideOrientation,
  35154. instance: instance,
  35155. updatable: updatable
  35156. };
  35157. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35158. };
  35159. /**
  35160. * Creates lathe mesh.
  35161. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35162. * Please consider using the same method from the MeshBuilder class instead
  35163. * @param name defines the name of the mesh to create
  35164. * @param 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
  35165. * @param radius is the radius value of the lathe
  35166. * @param tessellation is the side number of the lathe.
  35167. * @param scene defines the hosting scene
  35168. * @param updatable defines if the mesh must be flagged as updatable
  35169. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35170. * @returns a new Mesh
  35171. */
  35172. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35173. var options = {
  35174. shape: shape,
  35175. radius: radius,
  35176. tessellation: tessellation,
  35177. sideOrientation: sideOrientation,
  35178. updatable: updatable
  35179. };
  35180. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35181. };
  35182. /**
  35183. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35184. * @param name defines the name of the mesh to create
  35185. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35186. * @param scene defines the hosting scene
  35187. * @param updatable defines if the mesh must be flagged as updatable
  35188. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35189. * @returns a new Mesh
  35190. */
  35191. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35192. var options = {
  35193. size: size,
  35194. width: size,
  35195. height: size,
  35196. sideOrientation: sideOrientation,
  35197. updatable: updatable
  35198. };
  35199. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35200. };
  35201. /**
  35202. * Creates a ground mesh.
  35203. * Please consider using the same method from the MeshBuilder class instead
  35204. * @param name defines the name of the mesh to create
  35205. * @param width set the width of the ground
  35206. * @param height set the height of the ground
  35207. * @param subdivisions sets the number of subdivisions per side
  35208. * @param scene defines the hosting scene
  35209. * @param updatable defines if the mesh must be flagged as updatable
  35210. * @returns a new Mesh
  35211. */
  35212. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35213. var options = {
  35214. width: width,
  35215. height: height,
  35216. subdivisions: subdivisions,
  35217. updatable: updatable
  35218. };
  35219. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35220. };
  35221. /**
  35222. * Creates a tiled ground mesh.
  35223. * Please consider using the same method from the MeshBuilder class instead
  35224. * @param name defines the name of the mesh to create
  35225. * @param xmin set the ground minimum X coordinate
  35226. * @param zmin set the ground minimum Y coordinate
  35227. * @param xmax set the ground maximum X coordinate
  35228. * @param zmax set the ground maximum Z coordinate
  35229. * @param subdivisions is an 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
  35230. * @param precision is an 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
  35231. * @param scene defines the hosting scene
  35232. * @param updatable defines if the mesh must be flagged as updatable
  35233. * @returns a new Mesh
  35234. */
  35235. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35236. var options = {
  35237. xmin: xmin,
  35238. zmin: zmin,
  35239. xmax: xmax,
  35240. zmax: zmax,
  35241. subdivisions: subdivisions,
  35242. precision: precision,
  35243. updatable: updatable
  35244. };
  35245. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35246. };
  35247. /**
  35248. * Creates a ground mesh from a height map.
  35249. * Please consider using the same method from the MeshBuilder class instead
  35250. * @see http://doc.babylonjs.com/babylon101/height_map
  35251. * @param name defines the name of the mesh to create
  35252. * @param url sets the URL of the height map image resource
  35253. * @param width set the ground width size
  35254. * @param height set the ground height size
  35255. * @param subdivisions sets the number of subdivision per side
  35256. * @param minHeight is the minimum altitude on the ground
  35257. * @param maxHeight is the maximum altitude on the ground
  35258. * @param scene defines the hosting scene
  35259. * @param updatable defines if the mesh must be flagged as updatable
  35260. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35261. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35262. * @returns a new Mesh
  35263. */
  35264. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35265. var options = {
  35266. width: width,
  35267. height: height,
  35268. subdivisions: subdivisions,
  35269. minHeight: minHeight,
  35270. maxHeight: maxHeight,
  35271. updatable: updatable,
  35272. onReady: onReady,
  35273. alphaFilter: alphaFilter
  35274. };
  35275. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35276. };
  35277. /**
  35278. * Creates a tube mesh.
  35279. * The tube is a parametric shape.
  35280. * It has no predefined shape. Its final shape will depend on the input parameters.
  35281. * Please consider using the same method from the MeshBuilder class instead
  35282. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35283. * @param name defines the name of the mesh to create
  35284. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35285. * @param radius sets the tube radius size
  35286. * @param tessellation is the number of sides on the tubular surface
  35287. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  35288. * @param 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
  35289. * @param scene defines the hosting scene
  35290. * @param updatable defines if the mesh must be flagged as updatable
  35291. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35292. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  35293. * @returns a new Mesh
  35294. */
  35295. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35296. var options = {
  35297. path: path,
  35298. radius: radius,
  35299. tessellation: tessellation,
  35300. radiusFunction: radiusFunction,
  35301. arc: 1,
  35302. cap: cap,
  35303. updatable: updatable,
  35304. sideOrientation: sideOrientation,
  35305. instance: instance
  35306. };
  35307. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35308. };
  35309. /**
  35310. * Creates a polyhedron mesh.
  35311. * Please consider using the same method from the MeshBuilder class instead.
  35312. * * 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
  35313. * * The parameter `size` (positive float, default 1) sets the polygon size
  35314. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35315. * * 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`
  35316. * * 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
  35317. * * 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)`)
  35318. * * 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
  35319. * * 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
  35320. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35321. * * 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
  35322. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35323. * @param name defines the name of the mesh to create
  35324. * @param options defines the options used to create the mesh
  35325. * @param scene defines the hosting scene
  35326. * @returns a new Mesh
  35327. */
  35328. Mesh.CreatePolyhedron = function (name, options, scene) {
  35329. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35330. };
  35331. /**
  35332. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35333. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35334. * * 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`)
  35335. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35336. * * 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
  35337. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35338. * * 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
  35339. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35340. * @param name defines the name of the mesh
  35341. * @param options defines the options used to create the mesh
  35342. * @param scene defines the hosting scene
  35343. * @returns a new Mesh
  35344. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35345. */
  35346. Mesh.CreateIcoSphere = function (name, options, scene) {
  35347. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35348. };
  35349. /**
  35350. * Creates a decal mesh.
  35351. * Please consider using the same method from the MeshBuilder class instead.
  35352. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35353. * @param name defines the name of the mesh
  35354. * @param sourceMesh defines the mesh receiving the decal
  35355. * @param position sets the position of the decal in world coordinates
  35356. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35357. * @param size sets the decal scaling
  35358. * @param angle sets the angle to rotate the decal
  35359. * @returns a new Mesh
  35360. */
  35361. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35362. var options = {
  35363. position: position,
  35364. normal: normal,
  35365. size: size,
  35366. angle: angle
  35367. };
  35368. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35369. };
  35370. // Skeletons
  35371. /**
  35372. * Prepare internal position array for software CPU skinning
  35373. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35374. */
  35375. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35376. if (!this._sourcePositions) {
  35377. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35378. if (!source) {
  35379. return this._sourcePositions;
  35380. }
  35381. this._sourcePositions = new Float32Array(source);
  35382. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35383. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35384. }
  35385. }
  35386. return this._sourcePositions;
  35387. };
  35388. /**
  35389. * Prepare internal normal array for software CPU skinning
  35390. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35391. */
  35392. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35393. if (!this._sourceNormals) {
  35394. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35395. if (!source) {
  35396. return this._sourceNormals;
  35397. }
  35398. this._sourceNormals = new Float32Array(source);
  35399. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35400. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35401. }
  35402. }
  35403. return this._sourceNormals;
  35404. };
  35405. /**
  35406. * Updates the vertex buffer by applying transformation from the bones
  35407. * @param skeleton defines the skeleton to apply to current mesh
  35408. * @returns the current mesh
  35409. */
  35410. Mesh.prototype.applySkeleton = function (skeleton) {
  35411. if (!this.geometry) {
  35412. return this;
  35413. }
  35414. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35415. return this;
  35416. }
  35417. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35418. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35419. return this;
  35420. }
  35421. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35422. return this;
  35423. }
  35424. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35425. return this;
  35426. }
  35427. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35428. return this;
  35429. }
  35430. if (!this._sourcePositions) {
  35431. var submeshes = this.subMeshes.slice();
  35432. this.setPositionsForCPUSkinning();
  35433. this.subMeshes = submeshes;
  35434. }
  35435. if (!this._sourceNormals) {
  35436. this.setNormalsForCPUSkinning();
  35437. }
  35438. // positionsData checks for not being Float32Array will only pass at most once
  35439. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35440. if (!positionsData) {
  35441. return this;
  35442. }
  35443. if (!(positionsData instanceof Float32Array)) {
  35444. positionsData = new Float32Array(positionsData);
  35445. }
  35446. // normalsData checks for not being Float32Array will only pass at most once
  35447. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35448. if (!normalsData) {
  35449. return this;
  35450. }
  35451. if (!(normalsData instanceof Float32Array)) {
  35452. normalsData = new Float32Array(normalsData);
  35453. }
  35454. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35455. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35456. if (!matricesWeightsData || !matricesIndicesData) {
  35457. return this;
  35458. }
  35459. var needExtras = this.numBoneInfluencers > 4;
  35460. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35461. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35462. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35463. var tempVector3 = BABYLON.Vector3.Zero();
  35464. var finalMatrix = new BABYLON.Matrix();
  35465. var tempMatrix = new BABYLON.Matrix();
  35466. var matWeightIdx = 0;
  35467. var inf;
  35468. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35469. var weight;
  35470. for (inf = 0; inf < 4; inf++) {
  35471. weight = matricesWeightsData[matWeightIdx + inf];
  35472. if (weight > 0) {
  35473. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35474. finalMatrix.addToSelf(tempMatrix);
  35475. }
  35476. }
  35477. if (needExtras) {
  35478. for (inf = 0; inf < 4; inf++) {
  35479. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35480. if (weight > 0) {
  35481. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35482. finalMatrix.addToSelf(tempMatrix);
  35483. }
  35484. }
  35485. }
  35486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35487. tempVector3.toArray(positionsData, index);
  35488. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35489. tempVector3.toArray(normalsData, index);
  35490. finalMatrix.reset();
  35491. }
  35492. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35493. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35494. return this;
  35495. };
  35496. // Tools
  35497. /**
  35498. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  35499. * @param meshes defines the list of meshes to scan
  35500. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35501. */
  35502. Mesh.MinMax = function (meshes) {
  35503. var minVector = null;
  35504. var maxVector = null;
  35505. meshes.forEach(function (mesh, index, array) {
  35506. var boundingInfo = mesh.getBoundingInfo();
  35507. var boundingBox = boundingInfo.boundingBox;
  35508. if (!minVector || !maxVector) {
  35509. minVector = boundingBox.minimumWorld;
  35510. maxVector = boundingBox.maximumWorld;
  35511. }
  35512. else {
  35513. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35514. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35515. }
  35516. });
  35517. if (!minVector || !maxVector) {
  35518. return {
  35519. min: BABYLON.Vector3.Zero(),
  35520. max: BABYLON.Vector3.Zero()
  35521. };
  35522. }
  35523. return {
  35524. min: minVector,
  35525. max: maxVector
  35526. };
  35527. };
  35528. /**
  35529. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35530. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35531. * @returns a vector3
  35532. */
  35533. Mesh.Center = function (meshesOrMinMaxVector) {
  35534. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35535. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35536. };
  35537. /**
  35538. * Merge the array of meshes into a single mesh for performance reasons.
  35539. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35540. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35541. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35542. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35543. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35544. * @returns a new mesh
  35545. */
  35546. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35547. if (disposeSource === void 0) { disposeSource = true; }
  35548. var index;
  35549. if (!allow32BitsIndices) {
  35550. var totalVertices = 0;
  35551. // Counting vertices
  35552. for (index = 0; index < meshes.length; index++) {
  35553. if (meshes[index]) {
  35554. totalVertices += meshes[index].getTotalVertices();
  35555. if (totalVertices > 65536) {
  35556. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35557. return null;
  35558. }
  35559. }
  35560. }
  35561. }
  35562. // Merge
  35563. var vertexData = null;
  35564. var otherVertexData;
  35565. var indiceArray = new Array();
  35566. var source = null;
  35567. for (index = 0; index < meshes.length; index++) {
  35568. if (meshes[index]) {
  35569. var wm = meshes[index].computeWorldMatrix(true);
  35570. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35571. otherVertexData.transform(wm);
  35572. if (vertexData) {
  35573. vertexData.merge(otherVertexData, allow32BitsIndices);
  35574. }
  35575. else {
  35576. vertexData = otherVertexData;
  35577. source = meshes[index];
  35578. }
  35579. if (subdivideWithSubMeshes) {
  35580. indiceArray.push(meshes[index].getTotalIndices());
  35581. }
  35582. }
  35583. }
  35584. source = source;
  35585. if (!meshSubclass) {
  35586. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35587. }
  35588. vertexData.applyToMesh(meshSubclass);
  35589. // Setting properties
  35590. meshSubclass.material = source.material;
  35591. meshSubclass.checkCollisions = source.checkCollisions;
  35592. // Cleaning
  35593. if (disposeSource) {
  35594. for (index = 0; index < meshes.length; index++) {
  35595. if (meshes[index]) {
  35596. meshes[index].dispose();
  35597. }
  35598. }
  35599. }
  35600. // Subdivide
  35601. if (subdivideWithSubMeshes) {
  35602. //-- removal of global submesh
  35603. meshSubclass.releaseSubMeshes();
  35604. index = 0;
  35605. var offset = 0;
  35606. //-- apply subdivision according to index table
  35607. while (index < indiceArray.length) {
  35608. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35609. offset += indiceArray[index];
  35610. index++;
  35611. }
  35612. }
  35613. return meshSubclass;
  35614. };
  35615. /** @hidden */
  35616. Mesh.prototype.addInstance = function (instance) {
  35617. instance._indexInSourceMeshInstanceArray = this.instances.length;
  35618. this.instances.push(instance);
  35619. };
  35620. /** @hidden */
  35621. Mesh.prototype.removeInstance = function (instance) {
  35622. // Remove from mesh
  35623. var index = instance._indexInSourceMeshInstanceArray;
  35624. if (index != -1) {
  35625. if (index !== this.instances.length - 1) {
  35626. var last = this.instances[this.instances.length - 1];
  35627. this.instances[index] = last;
  35628. last._indexInSourceMeshInstanceArray = index;
  35629. }
  35630. instance._indexInSourceMeshInstanceArray = -1;
  35631. this.instances.pop();
  35632. }
  35633. };
  35634. // Consts
  35635. /**
  35636. * Mesh side orientation : usually the external or front surface
  35637. */
  35638. Mesh.FRONTSIDE = 0;
  35639. /**
  35640. * Mesh side orientation : usually the internal or back surface
  35641. */
  35642. Mesh.BACKSIDE = 1;
  35643. /**
  35644. * Mesh side orientation : both internal and external or front and back surfaces
  35645. */
  35646. Mesh.DOUBLESIDE = 2;
  35647. /**
  35648. * Mesh side orientation : by default, `FRONTSIDE`
  35649. */
  35650. Mesh.DEFAULTSIDE = 0;
  35651. /**
  35652. * Mesh cap setting : no cap
  35653. */
  35654. Mesh.NO_CAP = 0;
  35655. /**
  35656. * Mesh cap setting : one cap at the beginning of the mesh
  35657. */
  35658. Mesh.CAP_START = 1;
  35659. /**
  35660. * Mesh cap setting : one cap at the end of the mesh
  35661. */
  35662. Mesh.CAP_END = 2;
  35663. /**
  35664. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35665. */
  35666. Mesh.CAP_ALL = 3;
  35667. return Mesh;
  35668. }(BABYLON.AbstractMesh));
  35669. BABYLON.Mesh = Mesh;
  35670. })(BABYLON || (BABYLON = {}));
  35671. //# sourceMappingURL=babylon.mesh.js.map
  35672. var BABYLON;
  35673. (function (BABYLON) {
  35674. /**
  35675. * Base class for submeshes
  35676. */
  35677. var BaseSubMesh = /** @class */ (function () {
  35678. function BaseSubMesh() {
  35679. }
  35680. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35681. /**
  35682. * Gets associated effect
  35683. */
  35684. get: function () {
  35685. return this._materialEffect;
  35686. },
  35687. enumerable: true,
  35688. configurable: true
  35689. });
  35690. /**
  35691. * Sets associated effect (effect used to render this submesh)
  35692. * @param effect defines the effect to associate with
  35693. * @param defines defines the set of defines used to compile this effect
  35694. */
  35695. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35696. if (defines === void 0) { defines = null; }
  35697. if (this._materialEffect === effect) {
  35698. if (!effect) {
  35699. this._materialDefines = null;
  35700. }
  35701. return;
  35702. }
  35703. this._materialDefines = defines;
  35704. this._materialEffect = effect;
  35705. };
  35706. return BaseSubMesh;
  35707. }());
  35708. BABYLON.BaseSubMesh = BaseSubMesh;
  35709. /**
  35710. * Defines a subdivision inside a mesh
  35711. */
  35712. var SubMesh = /** @class */ (function (_super) {
  35713. __extends(SubMesh, _super);
  35714. /**
  35715. * Creates a new submesh
  35716. * @param materialIndex defines the material index to use
  35717. * @param verticesStart defines vertex index start
  35718. * @param verticesCount defines vertices count
  35719. * @param indexStart defines index start
  35720. * @param indexCount defines indices count
  35721. * @param mesh defines the parent mesh
  35722. * @param renderingMesh defines an optional rendering mesh
  35723. * @param createBoundingBox defines if bounding box should be created for this submesh
  35724. */
  35725. function SubMesh(
  35726. /** the material index to use */
  35727. materialIndex,
  35728. /** vertex index start */
  35729. verticesStart,
  35730. /** vertices count */
  35731. verticesCount,
  35732. /** index start */
  35733. indexStart,
  35734. /** indices count */
  35735. indexCount, mesh, renderingMesh, createBoundingBox) {
  35736. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35737. var _this = _super.call(this) || this;
  35738. _this.materialIndex = materialIndex;
  35739. _this.verticesStart = verticesStart;
  35740. _this.verticesCount = verticesCount;
  35741. _this.indexStart = indexStart;
  35742. _this.indexCount = indexCount;
  35743. /** @hidden */
  35744. _this._renderId = 0;
  35745. _this._mesh = mesh;
  35746. _this._renderingMesh = renderingMesh || mesh;
  35747. mesh.subMeshes.push(_this);
  35748. _this._trianglePlanes = [];
  35749. _this._id = mesh.subMeshes.length - 1;
  35750. if (createBoundingBox) {
  35751. _this.refreshBoundingInfo();
  35752. mesh.computeWorldMatrix(true);
  35753. }
  35754. return _this;
  35755. }
  35756. /**
  35757. * Add a new submesh to a mesh
  35758. * @param materialIndex defines the material index to use
  35759. * @param verticesStart defines vertex index start
  35760. * @param verticesCount defines vertices count
  35761. * @param indexStart defines index start
  35762. * @param indexCount defines indices count
  35763. * @param mesh defines the parent mesh
  35764. * @param renderingMesh defines an optional rendering mesh
  35765. * @param createBoundingBox defines if bounding box should be created for this submesh
  35766. * @returns the new submesh
  35767. */
  35768. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35769. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35770. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35771. };
  35772. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35773. /**
  35774. * Returns true if this submesh covers the entire parent mesh
  35775. * @ignorenaming
  35776. */
  35777. get: function () {
  35778. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35779. },
  35780. enumerable: true,
  35781. configurable: true
  35782. });
  35783. /**
  35784. * Returns the submesh BoudingInfo object
  35785. * @returns current bounding info (or mesh's one if the submesh is global)
  35786. */
  35787. SubMesh.prototype.getBoundingInfo = function () {
  35788. if (this.IsGlobal) {
  35789. return this._mesh.getBoundingInfo();
  35790. }
  35791. return this._boundingInfo;
  35792. };
  35793. /**
  35794. * Sets the submesh BoundingInfo
  35795. * @param boundingInfo defines the new bounding info to use
  35796. * @returns the SubMesh
  35797. */
  35798. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35799. this._boundingInfo = boundingInfo;
  35800. return this;
  35801. };
  35802. /**
  35803. * Returns the mesh of the current submesh
  35804. * @return the parent mesh
  35805. */
  35806. SubMesh.prototype.getMesh = function () {
  35807. return this._mesh;
  35808. };
  35809. /**
  35810. * Returns the rendering mesh of the submesh
  35811. * @returns the rendering mesh (could be different from parent mesh)
  35812. */
  35813. SubMesh.prototype.getRenderingMesh = function () {
  35814. return this._renderingMesh;
  35815. };
  35816. /**
  35817. * Returns the submesh material
  35818. * @returns null or the current material
  35819. */
  35820. SubMesh.prototype.getMaterial = function () {
  35821. var rootMaterial = this._renderingMesh.material;
  35822. if (rootMaterial === null || rootMaterial === undefined) {
  35823. return this._mesh.getScene().defaultMaterial;
  35824. }
  35825. else if (rootMaterial.getSubMaterial) {
  35826. var multiMaterial = rootMaterial;
  35827. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35828. if (this._currentMaterial !== effectiveMaterial) {
  35829. this._currentMaterial = effectiveMaterial;
  35830. this._materialDefines = null;
  35831. }
  35832. return effectiveMaterial;
  35833. }
  35834. return rootMaterial;
  35835. };
  35836. // Methods
  35837. /**
  35838. * Sets a new updated BoundingInfo object to the submesh
  35839. * @returns the SubMesh
  35840. */
  35841. SubMesh.prototype.refreshBoundingInfo = function () {
  35842. this._lastColliderWorldVertices = null;
  35843. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35844. return this;
  35845. }
  35846. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35847. if (!data) {
  35848. this._boundingInfo = this._mesh.getBoundingInfo();
  35849. return this;
  35850. }
  35851. var indices = this._renderingMesh.getIndices();
  35852. var extend;
  35853. //is this the only submesh?
  35854. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35855. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35856. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35857. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35858. }
  35859. else {
  35860. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35861. }
  35862. if (this._boundingInfo) {
  35863. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  35864. }
  35865. else {
  35866. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35867. }
  35868. return this;
  35869. };
  35870. /** @hidden */
  35871. SubMesh.prototype._checkCollision = function (collider) {
  35872. var boundingInfo = this.getBoundingInfo();
  35873. return boundingInfo._checkCollision(collider);
  35874. };
  35875. /**
  35876. * Updates the submesh BoundingInfo
  35877. * @param world defines the world matrix to use to update the bounding info
  35878. * @returns the submesh
  35879. */
  35880. SubMesh.prototype.updateBoundingInfo = function (world) {
  35881. var boundingInfo = this.getBoundingInfo();
  35882. if (!boundingInfo) {
  35883. this.refreshBoundingInfo();
  35884. boundingInfo = this.getBoundingInfo();
  35885. }
  35886. boundingInfo.update(world);
  35887. return this;
  35888. };
  35889. /**
  35890. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35891. * @param frustumPlanes defines the frustum planes
  35892. * @returns true if the submesh is intersecting with the frustum
  35893. */
  35894. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35895. var boundingInfo = this.getBoundingInfo();
  35896. if (!boundingInfo) {
  35897. return false;
  35898. }
  35899. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35900. };
  35901. /**
  35902. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35903. * @param frustumPlanes defines the frustum planes
  35904. * @returns true if the submesh is inside the frustum
  35905. */
  35906. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35907. var boundingInfo = this.getBoundingInfo();
  35908. if (!boundingInfo) {
  35909. return false;
  35910. }
  35911. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35912. };
  35913. /**
  35914. * Renders the submesh
  35915. * @param enableAlphaMode defines if alpha needs to be used
  35916. * @returns the submesh
  35917. */
  35918. SubMesh.prototype.render = function (enableAlphaMode) {
  35919. this._renderingMesh.render(this, enableAlphaMode);
  35920. return this;
  35921. };
  35922. /**
  35923. * @hidden
  35924. */
  35925. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35926. if (!this._linesIndexBuffer) {
  35927. var linesIndices = [];
  35928. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35929. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35930. }
  35931. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35932. this._linesIndexCount = linesIndices.length;
  35933. }
  35934. return this._linesIndexBuffer;
  35935. };
  35936. /**
  35937. * Checks if the submesh intersects with a ray
  35938. * @param ray defines the ray to test
  35939. * @returns true is the passed ray intersects the submesh bounding box
  35940. */
  35941. SubMesh.prototype.canIntersects = function (ray) {
  35942. var boundingInfo = this.getBoundingInfo();
  35943. if (!boundingInfo) {
  35944. return false;
  35945. }
  35946. return ray.intersectsBox(boundingInfo.boundingBox);
  35947. };
  35948. /**
  35949. * Intersects current submesh with a ray
  35950. * @param ray defines the ray to test
  35951. * @param positions defines mesh's positions array
  35952. * @param indices defines mesh's indices array
  35953. * @param fastCheck defines if only bounding info should be used
  35954. * @returns intersection info or null if no intersection
  35955. */
  35956. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35957. var material = this.getMaterial();
  35958. if (!material) {
  35959. return null;
  35960. }
  35961. switch (material.fillMode) {
  35962. case BABYLON.Material.PointListDrawMode:
  35963. case BABYLON.Material.LineListDrawMode:
  35964. case BABYLON.Material.LineLoopDrawMode:
  35965. case BABYLON.Material.LineStripDrawMode:
  35966. case BABYLON.Material.TriangleFanDrawMode:
  35967. case BABYLON.Material.TriangleStripDrawMode:
  35968. return null;
  35969. }
  35970. // LineMesh first as it's also a Mesh...
  35971. if (BABYLON.LinesMesh) {
  35972. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35973. if (mesh instanceof BABYLON.LinesMesh) {
  35974. var linesMesh = mesh;
  35975. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35976. }
  35977. }
  35978. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35979. };
  35980. /** @hidden */
  35981. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35982. var intersectInfo = null;
  35983. // Line test
  35984. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35985. var p0 = positions[indices[index]];
  35986. var p1 = positions[indices[index + 1]];
  35987. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35988. if (length < 0) {
  35989. continue;
  35990. }
  35991. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35992. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35993. if (fastCheck) {
  35994. break;
  35995. }
  35996. }
  35997. }
  35998. return intersectInfo;
  35999. };
  36000. /** @hidden */
  36001. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  36002. var intersectInfo = null;
  36003. // Triangles test
  36004. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36005. var p0 = positions[indices[index]];
  36006. var p1 = positions[indices[index + 1]];
  36007. var p2 = positions[indices[index + 2]];
  36008. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  36009. if (currentIntersectInfo) {
  36010. if (currentIntersectInfo.distance < 0) {
  36011. continue;
  36012. }
  36013. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  36014. intersectInfo = currentIntersectInfo;
  36015. intersectInfo.faceId = index / 3;
  36016. if (fastCheck) {
  36017. break;
  36018. }
  36019. }
  36020. }
  36021. }
  36022. return intersectInfo;
  36023. };
  36024. /** @hidden */
  36025. SubMesh.prototype._rebuild = function () {
  36026. if (this._linesIndexBuffer) {
  36027. this._linesIndexBuffer = null;
  36028. }
  36029. };
  36030. // Clone
  36031. /**
  36032. * Creates a new submesh from the passed mesh
  36033. * @param newMesh defines the new hosting mesh
  36034. * @param newRenderingMesh defines an optional rendering mesh
  36035. * @returns the new submesh
  36036. */
  36037. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  36038. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  36039. if (!this.IsGlobal) {
  36040. var boundingInfo = this.getBoundingInfo();
  36041. if (!boundingInfo) {
  36042. return result;
  36043. }
  36044. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  36045. }
  36046. return result;
  36047. };
  36048. // Dispose
  36049. /**
  36050. * Release associated resources
  36051. */
  36052. SubMesh.prototype.dispose = function () {
  36053. if (this._linesIndexBuffer) {
  36054. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36055. this._linesIndexBuffer = null;
  36056. }
  36057. // Remove from mesh
  36058. var index = this._mesh.subMeshes.indexOf(this);
  36059. this._mesh.subMeshes.splice(index, 1);
  36060. };
  36061. // Statics
  36062. /**
  36063. * Creates a new submesh from indices data
  36064. * @param materialIndex the index of the main mesh material
  36065. * @param startIndex the index where to start the copy in the mesh indices array
  36066. * @param indexCount the number of indices to copy then from the startIndex
  36067. * @param mesh the main mesh to create the submesh from
  36068. * @param renderingMesh the optional rendering mesh
  36069. * @returns a new submesh
  36070. */
  36071. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36072. var minVertexIndex = Number.MAX_VALUE;
  36073. var maxVertexIndex = -Number.MAX_VALUE;
  36074. renderingMesh = (renderingMesh || mesh);
  36075. var indices = renderingMesh.getIndices();
  36076. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36077. var vertexIndex = indices[index];
  36078. if (vertexIndex < minVertexIndex) {
  36079. minVertexIndex = vertexIndex;
  36080. }
  36081. if (vertexIndex > maxVertexIndex) {
  36082. maxVertexIndex = vertexIndex;
  36083. }
  36084. }
  36085. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36086. };
  36087. return SubMesh;
  36088. }(BaseSubMesh));
  36089. BABYLON.SubMesh = SubMesh;
  36090. })(BABYLON || (BABYLON = {}));
  36091. //# sourceMappingURL=babylon.subMesh.js.map
  36092. var __assign = (this && this.__assign) || function () {
  36093. __assign = Object.assign || function(t) {
  36094. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36095. s = arguments[i];
  36096. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36097. t[p] = s[p];
  36098. }
  36099. return t;
  36100. };
  36101. return __assign.apply(this, arguments);
  36102. };
  36103. var BABYLON;
  36104. (function (BABYLON) {
  36105. /**
  36106. * Manages the defines for the Material
  36107. */
  36108. var MaterialDefines = /** @class */ (function () {
  36109. function MaterialDefines() {
  36110. this._isDirty = true;
  36111. /** @hidden */
  36112. this._areLightsDirty = true;
  36113. /** @hidden */
  36114. this._areAttributesDirty = true;
  36115. /** @hidden */
  36116. this._areTexturesDirty = true;
  36117. /** @hidden */
  36118. this._areFresnelDirty = true;
  36119. /** @hidden */
  36120. this._areMiscDirty = true;
  36121. /** @hidden */
  36122. this._areImageProcessingDirty = true;
  36123. /** @hidden */
  36124. this._normals = false;
  36125. /** @hidden */
  36126. this._uvs = false;
  36127. /** @hidden */
  36128. this._needNormals = false;
  36129. /** @hidden */
  36130. this._needUVs = false;
  36131. }
  36132. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36133. /**
  36134. * Specifies if the material needs to be re-calculated
  36135. */
  36136. get: function () {
  36137. return this._isDirty;
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. /**
  36143. * Marks the material to indicate that it has been re-calculated
  36144. */
  36145. MaterialDefines.prototype.markAsProcessed = function () {
  36146. this._isDirty = false;
  36147. this._areAttributesDirty = false;
  36148. this._areTexturesDirty = false;
  36149. this._areFresnelDirty = false;
  36150. this._areLightsDirty = false;
  36151. this._areMiscDirty = false;
  36152. this._areImageProcessingDirty = false;
  36153. };
  36154. /**
  36155. * Marks the material to indicate that it needs to be re-calculated
  36156. */
  36157. MaterialDefines.prototype.markAsUnprocessed = function () {
  36158. this._isDirty = true;
  36159. };
  36160. /**
  36161. * Marks the material to indicate all of its defines need to be re-calculated
  36162. */
  36163. MaterialDefines.prototype.markAllAsDirty = function () {
  36164. this._areTexturesDirty = true;
  36165. this._areAttributesDirty = true;
  36166. this._areLightsDirty = true;
  36167. this._areFresnelDirty = true;
  36168. this._areMiscDirty = true;
  36169. this._areImageProcessingDirty = true;
  36170. this._isDirty = true;
  36171. };
  36172. /**
  36173. * Marks the material to indicate that image processing needs to be re-calculated
  36174. */
  36175. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36176. this._areImageProcessingDirty = true;
  36177. this._isDirty = true;
  36178. };
  36179. /**
  36180. * Marks the material to indicate the lights need to be re-calculated
  36181. */
  36182. MaterialDefines.prototype.markAsLightDirty = function () {
  36183. this._areLightsDirty = true;
  36184. this._isDirty = true;
  36185. };
  36186. /**
  36187. * Marks the attribute state as changed
  36188. */
  36189. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36190. this._areAttributesDirty = true;
  36191. this._isDirty = true;
  36192. };
  36193. /**
  36194. * Marks the texture state as changed
  36195. */
  36196. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36197. this._areTexturesDirty = true;
  36198. this._isDirty = true;
  36199. };
  36200. /**
  36201. * Marks the fresnel state as changed
  36202. */
  36203. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36204. this._areFresnelDirty = true;
  36205. this._isDirty = true;
  36206. };
  36207. /**
  36208. * Marks the misc state as changed
  36209. */
  36210. MaterialDefines.prototype.markAsMiscDirty = function () {
  36211. this._areMiscDirty = true;
  36212. this._isDirty = true;
  36213. };
  36214. /**
  36215. * Rebuilds the material defines
  36216. */
  36217. MaterialDefines.prototype.rebuild = function () {
  36218. if (this._keys) {
  36219. delete this._keys;
  36220. }
  36221. this._keys = [];
  36222. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36223. var key = _a[_i];
  36224. if (key[0] === "_") {
  36225. continue;
  36226. }
  36227. this._keys.push(key);
  36228. }
  36229. };
  36230. /**
  36231. * Specifies if two material defines are equal
  36232. * @param other - A material define instance to compare to
  36233. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36234. */
  36235. MaterialDefines.prototype.isEqual = function (other) {
  36236. if (this._keys.length !== other._keys.length) {
  36237. return false;
  36238. }
  36239. for (var index = 0; index < this._keys.length; index++) {
  36240. var prop = this._keys[index];
  36241. if (this[prop] !== other[prop]) {
  36242. return false;
  36243. }
  36244. }
  36245. return true;
  36246. };
  36247. /**
  36248. * Clones this instance's defines to another instance
  36249. * @param other - material defines to clone values to
  36250. */
  36251. MaterialDefines.prototype.cloneTo = function (other) {
  36252. if (this._keys.length !== other._keys.length) {
  36253. other._keys = this._keys.slice(0);
  36254. }
  36255. for (var index = 0; index < this._keys.length; index++) {
  36256. var prop = this._keys[index];
  36257. other[prop] = this[prop];
  36258. }
  36259. };
  36260. /**
  36261. * Resets the material define values
  36262. */
  36263. MaterialDefines.prototype.reset = function () {
  36264. for (var index = 0; index < this._keys.length; index++) {
  36265. var prop = this._keys[index];
  36266. var type = typeof this[prop];
  36267. switch (type) {
  36268. case "number":
  36269. this[prop] = 0;
  36270. break;
  36271. case "string":
  36272. this[prop] = "";
  36273. break;
  36274. default:
  36275. this[prop] = false;
  36276. break;
  36277. }
  36278. }
  36279. };
  36280. /**
  36281. * Converts the material define values to a string
  36282. * @returns - String of material define information
  36283. */
  36284. MaterialDefines.prototype.toString = function () {
  36285. var result = "";
  36286. for (var index = 0; index < this._keys.length; index++) {
  36287. var prop = this._keys[index];
  36288. var value = this[prop];
  36289. var type = typeof value;
  36290. switch (type) {
  36291. case "number":
  36292. case "string":
  36293. result += "#define " + prop + " " + value + "\n";
  36294. break;
  36295. default:
  36296. if (value) {
  36297. result += "#define " + prop + "\n";
  36298. }
  36299. break;
  36300. }
  36301. }
  36302. return result;
  36303. };
  36304. return MaterialDefines;
  36305. }());
  36306. BABYLON.MaterialDefines = MaterialDefines;
  36307. /**
  36308. * Base class for the main features of a material in Babylon.js
  36309. */
  36310. var Material = /** @class */ (function () {
  36311. /**
  36312. * Creates a material instance
  36313. * @param name defines the name of the material
  36314. * @param scene defines the scene to reference
  36315. * @param doNotAdd specifies if the material should be added to the scene
  36316. */
  36317. function Material(name, scene, doNotAdd) {
  36318. /**
  36319. * Specifies if the ready state should be checked on each call
  36320. */
  36321. this.checkReadyOnEveryCall = false;
  36322. /**
  36323. * Specifies if the ready state should be checked once
  36324. */
  36325. this.checkReadyOnlyOnce = false;
  36326. /**
  36327. * The state of the material
  36328. */
  36329. this.state = "";
  36330. /**
  36331. * The alpha value of the material
  36332. */
  36333. this._alpha = 1.0;
  36334. /**
  36335. * Specifies if back face culling is enabled
  36336. */
  36337. this._backFaceCulling = true;
  36338. /**
  36339. * Specifies if the material should be serialized
  36340. */
  36341. this.doNotSerialize = false;
  36342. /**
  36343. * @hidden
  36344. */
  36345. this._storeEffectOnSubMeshes = false;
  36346. /**
  36347. * An event triggered when the material is disposed
  36348. */
  36349. this.onDisposeObservable = new BABYLON.Observable();
  36350. /**
  36351. * Stores the value of the alpha mode
  36352. */
  36353. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36354. /**
  36355. * Stores the state of the need depth pre-pass value
  36356. */
  36357. this._needDepthPrePass = false;
  36358. /**
  36359. * Specifies if depth writing should be disabled
  36360. */
  36361. this.disableDepthWrite = false;
  36362. /**
  36363. * Specifies if depth writing should be forced
  36364. */
  36365. this.forceDepthWrite = false;
  36366. /**
  36367. * Specifies if there should be a separate pass for culling
  36368. */
  36369. this.separateCullingPass = false;
  36370. /**
  36371. * Stores the state specifing if fog should be enabled
  36372. */
  36373. this._fogEnabled = true;
  36374. /**
  36375. * Stores the size of points
  36376. */
  36377. this.pointSize = 1.0;
  36378. /**
  36379. * Stores the z offset value
  36380. */
  36381. this.zOffset = 0;
  36382. /**
  36383. * @hidden
  36384. * Specifies if the material was previously ready
  36385. */
  36386. this._wasPreviouslyReady = false;
  36387. /**
  36388. * Stores the fill mode state
  36389. */
  36390. this._fillMode = Material.TriangleFillMode;
  36391. /** @hidden */
  36392. this._indexInSceneMaterialArray = -1;
  36393. this.name = name;
  36394. this.id = name || BABYLON.Tools.RandomId();
  36395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36396. this.uniqueId = this._scene.getUniqueId();
  36397. if (this._scene.useRightHandedSystem) {
  36398. this.sideOrientation = Material.ClockWiseSideOrientation;
  36399. }
  36400. else {
  36401. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36402. }
  36403. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36404. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36405. if (!doNotAdd) {
  36406. this._scene.addMaterial(this);
  36407. }
  36408. if (this._scene.useMaterialMeshMap) {
  36409. this.meshMap = {};
  36410. }
  36411. }
  36412. Object.defineProperty(Material, "TriangleFillMode", {
  36413. /**
  36414. * Returns the triangle fill mode
  36415. */
  36416. get: function () {
  36417. return Material._TriangleFillMode;
  36418. },
  36419. enumerable: true,
  36420. configurable: true
  36421. });
  36422. Object.defineProperty(Material, "WireFrameFillMode", {
  36423. /**
  36424. * Returns the wireframe mode
  36425. */
  36426. get: function () {
  36427. return Material._WireFrameFillMode;
  36428. },
  36429. enumerable: true,
  36430. configurable: true
  36431. });
  36432. Object.defineProperty(Material, "PointFillMode", {
  36433. /**
  36434. * Returns the point fill mode
  36435. */
  36436. get: function () {
  36437. return Material._PointFillMode;
  36438. },
  36439. enumerable: true,
  36440. configurable: true
  36441. });
  36442. Object.defineProperty(Material, "PointListDrawMode", {
  36443. /**
  36444. * Returns the point list draw mode
  36445. */
  36446. get: function () {
  36447. return Material._PointListDrawMode;
  36448. },
  36449. enumerable: true,
  36450. configurable: true
  36451. });
  36452. Object.defineProperty(Material, "LineListDrawMode", {
  36453. /**
  36454. * Returns the line list draw mode
  36455. */
  36456. get: function () {
  36457. return Material._LineListDrawMode;
  36458. },
  36459. enumerable: true,
  36460. configurable: true
  36461. });
  36462. Object.defineProperty(Material, "LineLoopDrawMode", {
  36463. /**
  36464. * Returns the line loop draw mode
  36465. */
  36466. get: function () {
  36467. return Material._LineLoopDrawMode;
  36468. },
  36469. enumerable: true,
  36470. configurable: true
  36471. });
  36472. Object.defineProperty(Material, "LineStripDrawMode", {
  36473. /**
  36474. * Returns the line strip draw mode
  36475. */
  36476. get: function () {
  36477. return Material._LineStripDrawMode;
  36478. },
  36479. enumerable: true,
  36480. configurable: true
  36481. });
  36482. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36483. /**
  36484. * Returns the triangle strip draw mode
  36485. */
  36486. get: function () {
  36487. return Material._TriangleStripDrawMode;
  36488. },
  36489. enumerable: true,
  36490. configurable: true
  36491. });
  36492. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36493. /**
  36494. * Returns the triangle fan draw mode
  36495. */
  36496. get: function () {
  36497. return Material._TriangleFanDrawMode;
  36498. },
  36499. enumerable: true,
  36500. configurable: true
  36501. });
  36502. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36503. /**
  36504. * Returns the clock-wise side orientation
  36505. */
  36506. get: function () {
  36507. return Material._ClockWiseSideOrientation;
  36508. },
  36509. enumerable: true,
  36510. configurable: true
  36511. });
  36512. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36513. /**
  36514. * Returns the counter clock-wise side orientation
  36515. */
  36516. get: function () {
  36517. return Material._CounterClockWiseSideOrientation;
  36518. },
  36519. enumerable: true,
  36520. configurable: true
  36521. });
  36522. Object.defineProperty(Material.prototype, "alpha", {
  36523. /**
  36524. * Gets the alpha value of the material
  36525. */
  36526. get: function () {
  36527. return this._alpha;
  36528. },
  36529. /**
  36530. * Sets the alpha value of the material
  36531. */
  36532. set: function (value) {
  36533. if (this._alpha === value) {
  36534. return;
  36535. }
  36536. this._alpha = value;
  36537. this.markAsDirty(Material.MiscDirtyFlag);
  36538. },
  36539. enumerable: true,
  36540. configurable: true
  36541. });
  36542. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36543. /**
  36544. * Gets the back-face culling state
  36545. */
  36546. get: function () {
  36547. return this._backFaceCulling;
  36548. },
  36549. /**
  36550. * Sets the back-face culling state
  36551. */
  36552. set: function (value) {
  36553. if (this._backFaceCulling === value) {
  36554. return;
  36555. }
  36556. this._backFaceCulling = value;
  36557. this.markAsDirty(Material.TextureDirtyFlag);
  36558. },
  36559. enumerable: true,
  36560. configurable: true
  36561. });
  36562. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36563. /**
  36564. * Gets a boolean indicating that current material needs to register RTT
  36565. */
  36566. get: function () {
  36567. return false;
  36568. },
  36569. enumerable: true,
  36570. configurable: true
  36571. });
  36572. Object.defineProperty(Material.prototype, "onDispose", {
  36573. /**
  36574. * Called during a dispose event
  36575. */
  36576. set: function (callback) {
  36577. if (this._onDisposeObserver) {
  36578. this.onDisposeObservable.remove(this._onDisposeObserver);
  36579. }
  36580. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36581. },
  36582. enumerable: true,
  36583. configurable: true
  36584. });
  36585. Object.defineProperty(Material.prototype, "onBindObservable", {
  36586. /**
  36587. * An event triggered when the material is bound
  36588. */
  36589. get: function () {
  36590. if (!this._onBindObservable) {
  36591. this._onBindObservable = new BABYLON.Observable();
  36592. }
  36593. return this._onBindObservable;
  36594. },
  36595. enumerable: true,
  36596. configurable: true
  36597. });
  36598. Object.defineProperty(Material.prototype, "onBind", {
  36599. /**
  36600. * Called during a bind event
  36601. */
  36602. set: function (callback) {
  36603. if (this._onBindObserver) {
  36604. this.onBindObservable.remove(this._onBindObserver);
  36605. }
  36606. this._onBindObserver = this.onBindObservable.add(callback);
  36607. },
  36608. enumerable: true,
  36609. configurable: true
  36610. });
  36611. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36612. /**
  36613. * An event triggered when the material is unbound
  36614. */
  36615. get: function () {
  36616. if (!this._onUnBindObservable) {
  36617. this._onUnBindObservable = new BABYLON.Observable();
  36618. }
  36619. return this._onUnBindObservable;
  36620. },
  36621. enumerable: true,
  36622. configurable: true
  36623. });
  36624. Object.defineProperty(Material.prototype, "alphaMode", {
  36625. /**
  36626. * Gets the value of the alpha mode
  36627. */
  36628. get: function () {
  36629. return this._alphaMode;
  36630. },
  36631. /**
  36632. * Sets the value of the alpha mode.
  36633. *
  36634. * | Value | Type | Description |
  36635. * | --- | --- | --- |
  36636. * | 0 | ALPHA_DISABLE | |
  36637. * | 1 | ALPHA_ADD | |
  36638. * | 2 | ALPHA_COMBINE | |
  36639. * | 3 | ALPHA_SUBTRACT | |
  36640. * | 4 | ALPHA_MULTIPLY | |
  36641. * | 5 | ALPHA_MAXIMIZED | |
  36642. * | 6 | ALPHA_ONEONE | |
  36643. * | 7 | ALPHA_PREMULTIPLIED | |
  36644. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36645. * | 9 | ALPHA_INTERPOLATE | |
  36646. * | 10 | ALPHA_SCREENMODE | |
  36647. *
  36648. */
  36649. set: function (value) {
  36650. if (this._alphaMode === value) {
  36651. return;
  36652. }
  36653. this._alphaMode = value;
  36654. this.markAsDirty(Material.TextureDirtyFlag);
  36655. },
  36656. enumerable: true,
  36657. configurable: true
  36658. });
  36659. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36660. /**
  36661. * Gets the depth pre-pass value
  36662. */
  36663. get: function () {
  36664. return this._needDepthPrePass;
  36665. },
  36666. /**
  36667. * Sets the need depth pre-pass value
  36668. */
  36669. set: function (value) {
  36670. if (this._needDepthPrePass === value) {
  36671. return;
  36672. }
  36673. this._needDepthPrePass = value;
  36674. if (this._needDepthPrePass) {
  36675. this.checkReadyOnEveryCall = true;
  36676. }
  36677. },
  36678. enumerable: true,
  36679. configurable: true
  36680. });
  36681. Object.defineProperty(Material.prototype, "fogEnabled", {
  36682. /**
  36683. * Gets the value of the fog enabled state
  36684. */
  36685. get: function () {
  36686. return this._fogEnabled;
  36687. },
  36688. /**
  36689. * Sets the state for enabling fog
  36690. */
  36691. set: function (value) {
  36692. if (this._fogEnabled === value) {
  36693. return;
  36694. }
  36695. this._fogEnabled = value;
  36696. this.markAsDirty(Material.MiscDirtyFlag);
  36697. },
  36698. enumerable: true,
  36699. configurable: true
  36700. });
  36701. Object.defineProperty(Material.prototype, "wireframe", {
  36702. /**
  36703. * Gets a value specifying if wireframe mode is enabled
  36704. */
  36705. get: function () {
  36706. switch (this._fillMode) {
  36707. case Material.WireFrameFillMode:
  36708. case Material.LineListDrawMode:
  36709. case Material.LineLoopDrawMode:
  36710. case Material.LineStripDrawMode:
  36711. return true;
  36712. }
  36713. return this._scene.forceWireframe;
  36714. },
  36715. /**
  36716. * Sets the state of wireframe mode
  36717. */
  36718. set: function (value) {
  36719. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36720. },
  36721. enumerable: true,
  36722. configurable: true
  36723. });
  36724. Object.defineProperty(Material.prototype, "pointsCloud", {
  36725. /**
  36726. * Gets the value specifying if point clouds are enabled
  36727. */
  36728. get: function () {
  36729. switch (this._fillMode) {
  36730. case Material.PointFillMode:
  36731. case Material.PointListDrawMode:
  36732. return true;
  36733. }
  36734. return this._scene.forcePointsCloud;
  36735. },
  36736. /**
  36737. * Sets the state of point cloud mode
  36738. */
  36739. set: function (value) {
  36740. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36741. },
  36742. enumerable: true,
  36743. configurable: true
  36744. });
  36745. Object.defineProperty(Material.prototype, "fillMode", {
  36746. /**
  36747. * Gets the material fill mode
  36748. */
  36749. get: function () {
  36750. return this._fillMode;
  36751. },
  36752. /**
  36753. * Sets the material fill mode
  36754. */
  36755. set: function (value) {
  36756. if (this._fillMode === value) {
  36757. return;
  36758. }
  36759. this._fillMode = value;
  36760. this.markAsDirty(Material.MiscDirtyFlag);
  36761. },
  36762. enumerable: true,
  36763. configurable: true
  36764. });
  36765. /**
  36766. * Returns a string representation of the current material
  36767. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36768. * @returns a string with material information
  36769. */
  36770. Material.prototype.toString = function (fullDetails) {
  36771. var ret = "Name: " + this.name;
  36772. if (fullDetails) {
  36773. }
  36774. return ret;
  36775. };
  36776. /**
  36777. * Gets the class name of the material
  36778. * @returns a string with the class name of the material
  36779. */
  36780. Material.prototype.getClassName = function () {
  36781. return "Material";
  36782. };
  36783. Object.defineProperty(Material.prototype, "isFrozen", {
  36784. /**
  36785. * Specifies if updates for the material been locked
  36786. */
  36787. get: function () {
  36788. return this.checkReadyOnlyOnce;
  36789. },
  36790. enumerable: true,
  36791. configurable: true
  36792. });
  36793. /**
  36794. * Locks updates for the material
  36795. */
  36796. Material.prototype.freeze = function () {
  36797. this.checkReadyOnlyOnce = true;
  36798. };
  36799. /**
  36800. * Unlocks updates for the material
  36801. */
  36802. Material.prototype.unfreeze = function () {
  36803. this.checkReadyOnlyOnce = false;
  36804. };
  36805. /**
  36806. * Specifies if the material is ready to be used
  36807. * @param mesh defines the mesh to check
  36808. * @param useInstances specifies if instances should be used
  36809. * @returns a boolean indicating if the material is ready to be used
  36810. */
  36811. Material.prototype.isReady = function (mesh, useInstances) {
  36812. return true;
  36813. };
  36814. /**
  36815. * Specifies that the submesh is ready to be used
  36816. * @param mesh defines the mesh to check
  36817. * @param subMesh defines which submesh to check
  36818. * @param useInstances specifies that instances should be used
  36819. * @returns a boolean indicating that the submesh is ready or not
  36820. */
  36821. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36822. return false;
  36823. };
  36824. /**
  36825. * Returns the material effect
  36826. * @returns the effect associated with the material
  36827. */
  36828. Material.prototype.getEffect = function () {
  36829. return this._effect;
  36830. };
  36831. /**
  36832. * Returns the current scene
  36833. * @returns a Scene
  36834. */
  36835. Material.prototype.getScene = function () {
  36836. return this._scene;
  36837. };
  36838. /**
  36839. * Specifies if the material will require alpha blending
  36840. * @returns a boolean specifying if alpha blending is needed
  36841. */
  36842. Material.prototype.needAlphaBlending = function () {
  36843. return (this.alpha < 1.0);
  36844. };
  36845. /**
  36846. * Specifies if the mesh will require alpha blending
  36847. * @param mesh defines the mesh to check
  36848. * @returns a boolean specifying if alpha blending is needed for the mesh
  36849. */
  36850. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36851. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36852. };
  36853. /**
  36854. * Specifies if this material should be rendered in alpha test mode
  36855. * @returns a boolean specifying if an alpha test is needed.
  36856. */
  36857. Material.prototype.needAlphaTesting = function () {
  36858. return false;
  36859. };
  36860. /**
  36861. * Gets the texture used for the alpha test
  36862. * @returns the texture to use for alpha testing
  36863. */
  36864. Material.prototype.getAlphaTestTexture = function () {
  36865. return null;
  36866. };
  36867. /**
  36868. * Marks the material to indicate that it needs to be re-calculated
  36869. */
  36870. Material.prototype.markDirty = function () {
  36871. this._wasPreviouslyReady = false;
  36872. };
  36873. /** @hidden */
  36874. Material.prototype._preBind = function (effect, overrideOrientation) {
  36875. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36876. var engine = this._scene.getEngine();
  36877. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36878. var reverse = orientation === Material.ClockWiseSideOrientation;
  36879. engine.enableEffect(effect ? effect : this._effect);
  36880. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36881. return reverse;
  36882. };
  36883. /**
  36884. * Binds the material to the mesh
  36885. * @param world defines the world transformation matrix
  36886. * @param mesh defines the mesh to bind the material to
  36887. */
  36888. Material.prototype.bind = function (world, mesh) {
  36889. };
  36890. /**
  36891. * Binds the submesh to the material
  36892. * @param world defines the world transformation matrix
  36893. * @param mesh defines the mesh containing the submesh
  36894. * @param subMesh defines the submesh to bind the material to
  36895. */
  36896. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36897. };
  36898. /**
  36899. * Binds the world matrix to the material
  36900. * @param world defines the world transformation matrix
  36901. */
  36902. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36903. };
  36904. /**
  36905. * Binds the scene's uniform buffer to the effect.
  36906. * @param effect defines the effect to bind to the scene uniform buffer
  36907. * @param sceneUbo defines the uniform buffer storing scene data
  36908. */
  36909. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36910. sceneUbo.bindToEffect(effect, "Scene");
  36911. };
  36912. /**
  36913. * Binds the view matrix to the effect
  36914. * @param effect defines the effect to bind the view matrix to
  36915. */
  36916. Material.prototype.bindView = function (effect) {
  36917. if (!this._useUBO) {
  36918. effect.setMatrix("view", this.getScene().getViewMatrix());
  36919. }
  36920. else {
  36921. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36922. }
  36923. };
  36924. /**
  36925. * Binds the view projection matrix to the effect
  36926. * @param effect defines the effect to bind the view projection matrix to
  36927. */
  36928. Material.prototype.bindViewProjection = function (effect) {
  36929. if (!this._useUBO) {
  36930. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36931. }
  36932. else {
  36933. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36934. }
  36935. };
  36936. /**
  36937. * Specifies if material alpha testing should be turned on for the mesh
  36938. * @param mesh defines the mesh to check
  36939. */
  36940. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36941. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36942. };
  36943. /**
  36944. * Processes to execute after binding the material to a mesh
  36945. * @param mesh defines the rendered mesh
  36946. */
  36947. Material.prototype._afterBind = function (mesh) {
  36948. this._scene._cachedMaterial = this;
  36949. if (mesh) {
  36950. this._scene._cachedVisibility = mesh.visibility;
  36951. }
  36952. else {
  36953. this._scene._cachedVisibility = 1;
  36954. }
  36955. if (this._onBindObservable && mesh) {
  36956. this._onBindObservable.notifyObservers(mesh);
  36957. }
  36958. if (this.disableDepthWrite) {
  36959. var engine = this._scene.getEngine();
  36960. this._cachedDepthWriteState = engine.getDepthWrite();
  36961. engine.setDepthWrite(false);
  36962. }
  36963. };
  36964. /**
  36965. * Unbinds the material from the mesh
  36966. */
  36967. Material.prototype.unbind = function () {
  36968. if (this._onUnBindObservable) {
  36969. this._onUnBindObservable.notifyObservers(this);
  36970. }
  36971. if (this.disableDepthWrite) {
  36972. var engine = this._scene.getEngine();
  36973. engine.setDepthWrite(this._cachedDepthWriteState);
  36974. }
  36975. };
  36976. /**
  36977. * Gets the active textures from the material
  36978. * @returns an array of textures
  36979. */
  36980. Material.prototype.getActiveTextures = function () {
  36981. return [];
  36982. };
  36983. /**
  36984. * Specifies if the material uses a texture
  36985. * @param texture defines the texture to check against the material
  36986. * @returns a boolean specifying if the material uses the texture
  36987. */
  36988. Material.prototype.hasTexture = function (texture) {
  36989. return false;
  36990. };
  36991. /**
  36992. * Makes a duplicate of the material, and gives it a new name
  36993. * @param name defines the new name for the duplicated material
  36994. * @returns the cloned material
  36995. */
  36996. Material.prototype.clone = function (name) {
  36997. return null;
  36998. };
  36999. /**
  37000. * Gets the meshes bound to the material
  37001. * @returns an array of meshes bound to the material
  37002. */
  37003. Material.prototype.getBindedMeshes = function () {
  37004. var _this = this;
  37005. if (this.meshMap) {
  37006. var result = new Array();
  37007. for (var meshId in this.meshMap) {
  37008. var mesh = this.meshMap[meshId];
  37009. if (mesh) {
  37010. result.push(mesh);
  37011. }
  37012. }
  37013. return result;
  37014. }
  37015. else {
  37016. var meshes = this._scene.meshes;
  37017. return meshes.filter(function (mesh) { return mesh.material === _this; });
  37018. }
  37019. };
  37020. /**
  37021. * Force shader compilation
  37022. * @param mesh defines the mesh associated with this material
  37023. * @param onCompiled defines a function to execute once the material is compiled
  37024. * @param options defines the options to configure the compilation
  37025. */
  37026. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  37027. var _this = this;
  37028. var localOptions = __assign({ clipPlane: false }, options);
  37029. var subMesh = new BABYLON.BaseSubMesh();
  37030. var scene = this.getScene();
  37031. var checkReady = function () {
  37032. if (!_this._scene || !_this._scene.getEngine()) {
  37033. return;
  37034. }
  37035. if (subMesh._materialDefines) {
  37036. subMesh._materialDefines._renderId = -1;
  37037. }
  37038. var clipPlaneState = scene.clipPlane;
  37039. if (localOptions.clipPlane) {
  37040. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  37041. }
  37042. if (_this._storeEffectOnSubMeshes) {
  37043. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  37044. if (onCompiled) {
  37045. onCompiled(_this);
  37046. }
  37047. }
  37048. else {
  37049. setTimeout(checkReady, 16);
  37050. }
  37051. }
  37052. else {
  37053. if (_this.isReady(mesh)) {
  37054. if (onCompiled) {
  37055. onCompiled(_this);
  37056. }
  37057. }
  37058. else {
  37059. setTimeout(checkReady, 16);
  37060. }
  37061. }
  37062. if (localOptions.clipPlane) {
  37063. scene.clipPlane = clipPlaneState;
  37064. }
  37065. };
  37066. checkReady();
  37067. };
  37068. /**
  37069. * Force shader compilation
  37070. * @param mesh defines the mesh that will use this material
  37071. * @param options defines additional options for compiling the shaders
  37072. * @returns a promise that resolves when the compilation completes
  37073. */
  37074. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37075. var _this = this;
  37076. return new Promise(function (resolve) {
  37077. _this.forceCompilation(mesh, function () {
  37078. resolve();
  37079. }, options);
  37080. });
  37081. };
  37082. /**
  37083. * Marks a define in the material to indicate that it needs to be re-computed
  37084. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37085. */
  37086. Material.prototype.markAsDirty = function (flag) {
  37087. if (this.getScene().blockMaterialDirtyMechanism) {
  37088. return;
  37089. }
  37090. Material._DirtyCallbackArray.length = 0;
  37091. if (flag & Material.TextureDirtyFlag) {
  37092. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  37093. }
  37094. if (flag & Material.LightDirtyFlag) {
  37095. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  37096. }
  37097. if (flag & Material.FresnelDirtyFlag) {
  37098. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  37099. }
  37100. if (flag & Material.AttributesDirtyFlag) {
  37101. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  37102. }
  37103. if (flag & Material.MiscDirtyFlag) {
  37104. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  37105. }
  37106. if (Material._DirtyCallbackArray.length) {
  37107. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  37108. }
  37109. this.getScene().resetCachedMaterial();
  37110. };
  37111. /**
  37112. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37113. * @param func defines a function which checks material defines against the submeshes
  37114. */
  37115. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37116. if (this.getScene().blockMaterialDirtyMechanism) {
  37117. return;
  37118. }
  37119. var meshes = this.getScene().meshes;
  37120. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37121. var mesh = meshes_1[_i];
  37122. if (!mesh.subMeshes) {
  37123. continue;
  37124. }
  37125. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  37126. var subMesh = _b[_a];
  37127. if (subMesh.getMaterial() !== this) {
  37128. continue;
  37129. }
  37130. if (!subMesh._materialDefines) {
  37131. continue;
  37132. }
  37133. func(subMesh._materialDefines);
  37134. }
  37135. }
  37136. };
  37137. /**
  37138. * Indicates that image processing needs to be re-calculated for all submeshes
  37139. */
  37140. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37141. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  37142. };
  37143. /**
  37144. * Indicates that textures need to be re-calculated for all submeshes
  37145. */
  37146. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37147. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  37148. };
  37149. /**
  37150. * Indicates that fresnel needs to be re-calculated for all submeshes
  37151. */
  37152. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37153. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  37154. };
  37155. /**
  37156. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37157. */
  37158. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37159. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  37160. };
  37161. /**
  37162. * Indicates that lights need to be re-calculated for all submeshes
  37163. */
  37164. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37165. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  37166. };
  37167. /**
  37168. * Indicates that attributes need to be re-calculated for all submeshes
  37169. */
  37170. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37171. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  37172. };
  37173. /**
  37174. * Indicates that misc needs to be re-calculated for all submeshes
  37175. */
  37176. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37177. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  37178. };
  37179. /**
  37180. * Indicates that textures and misc need to be re-calculated for all submeshes
  37181. */
  37182. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37183. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  37184. };
  37185. /**
  37186. * Disposes the material
  37187. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37188. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37189. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37190. */
  37191. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37192. var scene = this.getScene();
  37193. // Animations
  37194. scene.stopAnimation(this);
  37195. scene.freeProcessedMaterials();
  37196. // Remove from scene
  37197. scene.removeMaterial(this);
  37198. if (notBoundToMesh !== true) {
  37199. // Remove from meshes
  37200. if (this.meshMap) {
  37201. for (var meshId in this.meshMap) {
  37202. var mesh = this.meshMap[meshId];
  37203. if (mesh) {
  37204. mesh.material = null; // will set the entry in the map to undefined
  37205. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37206. }
  37207. }
  37208. }
  37209. else {
  37210. var meshes = scene.meshes;
  37211. for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) {
  37212. var mesh = meshes_2[_i];
  37213. if (mesh.material === this) {
  37214. mesh.material = null;
  37215. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37216. }
  37217. }
  37218. }
  37219. }
  37220. this._uniformBuffer.dispose();
  37221. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37222. if (forceDisposeEffect && this._effect) {
  37223. if (!this._storeEffectOnSubMeshes) {
  37224. scene.getEngine()._releaseEffect(this._effect);
  37225. }
  37226. this._effect = null;
  37227. }
  37228. // Callback
  37229. this.onDisposeObservable.notifyObservers(this);
  37230. this.onDisposeObservable.clear();
  37231. if (this._onBindObservable) {
  37232. this._onBindObservable.clear();
  37233. }
  37234. if (this._onUnBindObservable) {
  37235. this._onUnBindObservable.clear();
  37236. }
  37237. };
  37238. /** @hidden */
  37239. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37240. if (mesh.geometry) {
  37241. var geometry = (mesh.geometry);
  37242. var scene = this.getScene();
  37243. if (this._storeEffectOnSubMeshes) {
  37244. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37245. var subMesh = _a[_i];
  37246. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37247. if (forceDisposeEffect && subMesh._materialEffect) {
  37248. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37249. }
  37250. }
  37251. }
  37252. else {
  37253. geometry._releaseVertexArrayObject(this._effect);
  37254. }
  37255. }
  37256. };
  37257. /**
  37258. * Serializes this material
  37259. * @returns the serialized material object
  37260. */
  37261. Material.prototype.serialize = function () {
  37262. return BABYLON.SerializationHelper.Serialize(this);
  37263. };
  37264. /**
  37265. * Creates a MultiMaterial from parsed MultiMaterial data.
  37266. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37267. * @param scene defines the hosting scene
  37268. * @returns a new MultiMaterial
  37269. */
  37270. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37271. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37272. multiMaterial.id = parsedMultiMaterial.id;
  37273. if (BABYLON.Tags) {
  37274. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37275. }
  37276. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37277. var subMatId = parsedMultiMaterial.materials[matIndex];
  37278. if (subMatId) {
  37279. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37280. }
  37281. else {
  37282. multiMaterial.subMaterials.push(null);
  37283. }
  37284. }
  37285. return multiMaterial;
  37286. };
  37287. /**
  37288. * Creates a material from parsed material data
  37289. * @param parsedMaterial defines parsed material data
  37290. * @param scene defines the hosting scene
  37291. * @param rootUrl defines the root URL to use to load textures
  37292. * @returns a new material
  37293. */
  37294. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37295. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37296. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37297. }
  37298. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37299. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37300. if (!BABYLON.LegacyPBRMaterial) {
  37301. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37302. return;
  37303. }
  37304. }
  37305. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37306. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37307. };
  37308. // Triangle views
  37309. Material._TriangleFillMode = 0;
  37310. Material._WireFrameFillMode = 1;
  37311. Material._PointFillMode = 2;
  37312. // Draw modes
  37313. Material._PointListDrawMode = 3;
  37314. Material._LineListDrawMode = 4;
  37315. Material._LineLoopDrawMode = 5;
  37316. Material._LineStripDrawMode = 6;
  37317. Material._TriangleStripDrawMode = 7;
  37318. Material._TriangleFanDrawMode = 8;
  37319. /**
  37320. * Stores the clock-wise side orientation
  37321. */
  37322. Material._ClockWiseSideOrientation = 0;
  37323. /**
  37324. * Stores the counter clock-wise side orientation
  37325. */
  37326. Material._CounterClockWiseSideOrientation = 1;
  37327. /**
  37328. * The dirty texture flag value
  37329. */
  37330. Material.TextureDirtyFlag = 1;
  37331. /**
  37332. * The dirty light flag value
  37333. */
  37334. Material.LightDirtyFlag = 2;
  37335. /**
  37336. * The dirty fresnel flag value
  37337. */
  37338. Material.FresnelDirtyFlag = 4;
  37339. /**
  37340. * The dirty attribute flag value
  37341. */
  37342. Material.AttributesDirtyFlag = 8;
  37343. /**
  37344. * The dirty misc flag value
  37345. */
  37346. Material.MiscDirtyFlag = 16;
  37347. /**
  37348. * The all dirty flag value
  37349. */
  37350. Material.AllDirtyFlag = 31;
  37351. Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); };
  37352. Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); };
  37353. Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); };
  37354. Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); };
  37355. Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); };
  37356. Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); };
  37357. Material._FresnelAndMiscDirtyCallBack = function (defines) {
  37358. Material._FresnelDirtyCallBack(defines);
  37359. Material._MiscDirtyCallBack(defines);
  37360. };
  37361. Material._TextureAndMiscDirtyCallBack = function (defines) {
  37362. Material._TextureDirtyCallBack(defines);
  37363. Material._MiscDirtyCallBack(defines);
  37364. };
  37365. Material._DirtyCallbackArray = [];
  37366. Material._RunDirtyCallBacks = function (defines) {
  37367. for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) {
  37368. var cb = _a[_i];
  37369. cb(defines);
  37370. }
  37371. };
  37372. __decorate([
  37373. BABYLON.serialize()
  37374. ], Material.prototype, "id", void 0);
  37375. __decorate([
  37376. BABYLON.serialize()
  37377. ], Material.prototype, "uniqueId", void 0);
  37378. __decorate([
  37379. BABYLON.serialize()
  37380. ], Material.prototype, "name", void 0);
  37381. __decorate([
  37382. BABYLON.serialize()
  37383. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37384. __decorate([
  37385. BABYLON.serialize()
  37386. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37387. __decorate([
  37388. BABYLON.serialize()
  37389. ], Material.prototype, "state", void 0);
  37390. __decorate([
  37391. BABYLON.serialize("alpha")
  37392. ], Material.prototype, "_alpha", void 0);
  37393. __decorate([
  37394. BABYLON.serialize("backFaceCulling")
  37395. ], Material.prototype, "_backFaceCulling", void 0);
  37396. __decorate([
  37397. BABYLON.serialize()
  37398. ], Material.prototype, "sideOrientation", void 0);
  37399. __decorate([
  37400. BABYLON.serialize("alphaMode")
  37401. ], Material.prototype, "_alphaMode", void 0);
  37402. __decorate([
  37403. BABYLON.serialize()
  37404. ], Material.prototype, "_needDepthPrePass", void 0);
  37405. __decorate([
  37406. BABYLON.serialize()
  37407. ], Material.prototype, "disableDepthWrite", void 0);
  37408. __decorate([
  37409. BABYLON.serialize()
  37410. ], Material.prototype, "forceDepthWrite", void 0);
  37411. __decorate([
  37412. BABYLON.serialize()
  37413. ], Material.prototype, "separateCullingPass", void 0);
  37414. __decorate([
  37415. BABYLON.serialize("fogEnabled")
  37416. ], Material.prototype, "_fogEnabled", void 0);
  37417. __decorate([
  37418. BABYLON.serialize()
  37419. ], Material.prototype, "pointSize", void 0);
  37420. __decorate([
  37421. BABYLON.serialize()
  37422. ], Material.prototype, "zOffset", void 0);
  37423. __decorate([
  37424. BABYLON.serialize()
  37425. ], Material.prototype, "wireframe", null);
  37426. __decorate([
  37427. BABYLON.serialize()
  37428. ], Material.prototype, "pointsCloud", null);
  37429. __decorate([
  37430. BABYLON.serialize()
  37431. ], Material.prototype, "fillMode", null);
  37432. return Material;
  37433. }());
  37434. BABYLON.Material = Material;
  37435. })(BABYLON || (BABYLON = {}));
  37436. //# sourceMappingURL=babylon.material.js.map
  37437. var BABYLON;
  37438. (function (BABYLON) {
  37439. /**
  37440. * Uniform buffer objects.
  37441. *
  37442. * Handles blocks of uniform on the GPU.
  37443. *
  37444. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37445. *
  37446. * For more information, please refer to :
  37447. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37448. */
  37449. var UniformBuffer = /** @class */ (function () {
  37450. /**
  37451. * Instantiates a new Uniform buffer objects.
  37452. *
  37453. * Handles blocks of uniform on the GPU.
  37454. *
  37455. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37456. *
  37457. * For more information, please refer to :
  37458. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37459. * @param engine Define the engine the buffer is associated with
  37460. * @param data Define the data contained in the buffer
  37461. * @param dynamic Define if the buffer is updatable
  37462. */
  37463. function UniformBuffer(engine, data, dynamic) {
  37464. this._engine = engine;
  37465. this._noUBO = !engine.supportsUniformBuffers;
  37466. this._dynamic = dynamic;
  37467. this._data = data || [];
  37468. this._uniformLocations = {};
  37469. this._uniformSizes = {};
  37470. this._uniformLocationPointer = 0;
  37471. this._needSync = false;
  37472. if (this._noUBO) {
  37473. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37474. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37475. this.updateFloat = this._updateFloatForEffect;
  37476. this.updateFloat2 = this._updateFloat2ForEffect;
  37477. this.updateFloat3 = this._updateFloat3ForEffect;
  37478. this.updateFloat4 = this._updateFloat4ForEffect;
  37479. this.updateMatrix = this._updateMatrixForEffect;
  37480. this.updateVector3 = this._updateVector3ForEffect;
  37481. this.updateVector4 = this._updateVector4ForEffect;
  37482. this.updateColor3 = this._updateColor3ForEffect;
  37483. this.updateColor4 = this._updateColor4ForEffect;
  37484. }
  37485. else {
  37486. this._engine._uniformBuffers.push(this);
  37487. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37488. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37489. this.updateFloat = this._updateFloatForUniform;
  37490. this.updateFloat2 = this._updateFloat2ForUniform;
  37491. this.updateFloat3 = this._updateFloat3ForUniform;
  37492. this.updateFloat4 = this._updateFloat4ForUniform;
  37493. this.updateMatrix = this._updateMatrixForUniform;
  37494. this.updateVector3 = this._updateVector3ForUniform;
  37495. this.updateVector4 = this._updateVector4ForUniform;
  37496. this.updateColor3 = this._updateColor3ForUniform;
  37497. this.updateColor4 = this._updateColor4ForUniform;
  37498. }
  37499. }
  37500. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37501. /**
  37502. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37503. * or just falling back on setUniformXXX calls.
  37504. */
  37505. get: function () {
  37506. return !this._noUBO;
  37507. },
  37508. enumerable: true,
  37509. configurable: true
  37510. });
  37511. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37512. /**
  37513. * Indicates if the WebGL underlying uniform buffer is in sync
  37514. * with the javascript cache data.
  37515. */
  37516. get: function () {
  37517. return !this._needSync;
  37518. },
  37519. enumerable: true,
  37520. configurable: true
  37521. });
  37522. /**
  37523. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37524. * Also, a dynamic UniformBuffer will disable cache verification and always
  37525. * update the underlying WebGL uniform buffer to the GPU.
  37526. * @returns if Dynamic, otherwise false
  37527. */
  37528. UniformBuffer.prototype.isDynamic = function () {
  37529. return this._dynamic !== undefined;
  37530. };
  37531. /**
  37532. * The data cache on JS side.
  37533. * @returns the underlying data as a float array
  37534. */
  37535. UniformBuffer.prototype.getData = function () {
  37536. return this._bufferData;
  37537. };
  37538. /**
  37539. * The underlying WebGL Uniform buffer.
  37540. * @returns the webgl buffer
  37541. */
  37542. UniformBuffer.prototype.getBuffer = function () {
  37543. return this._buffer;
  37544. };
  37545. /**
  37546. * std140 layout specifies how to align data within an UBO structure.
  37547. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37548. * for specs.
  37549. */
  37550. UniformBuffer.prototype._fillAlignment = function (size) {
  37551. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37552. // and 4x4 matrices
  37553. // TODO : change if other types are used
  37554. var alignment;
  37555. if (size <= 2) {
  37556. alignment = size;
  37557. }
  37558. else {
  37559. alignment = 4;
  37560. }
  37561. if ((this._uniformLocationPointer % alignment) !== 0) {
  37562. var oldPointer = this._uniformLocationPointer;
  37563. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37564. var diff = this._uniformLocationPointer - oldPointer;
  37565. for (var i = 0; i < diff; i++) {
  37566. this._data.push(0);
  37567. }
  37568. }
  37569. };
  37570. /**
  37571. * Adds an uniform in the buffer.
  37572. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37573. * for the layout to be correct !
  37574. * @param name Name of the uniform, as used in the uniform block in the shader.
  37575. * @param size Data size, or data directly.
  37576. */
  37577. UniformBuffer.prototype.addUniform = function (name, size) {
  37578. if (this._noUBO) {
  37579. return;
  37580. }
  37581. if (this._uniformLocations[name] !== undefined) {
  37582. // Already existing uniform
  37583. return;
  37584. }
  37585. // This function must be called in the order of the shader layout !
  37586. // size can be the size of the uniform, or data directly
  37587. var data;
  37588. if (size instanceof Array) {
  37589. data = size;
  37590. size = data.length;
  37591. }
  37592. else {
  37593. size = size;
  37594. data = [];
  37595. // Fill with zeros
  37596. for (var i = 0; i < size; i++) {
  37597. data.push(0);
  37598. }
  37599. }
  37600. this._fillAlignment(size);
  37601. this._uniformSizes[name] = size;
  37602. this._uniformLocations[name] = this._uniformLocationPointer;
  37603. this._uniformLocationPointer += size;
  37604. for (var i = 0; i < size; i++) {
  37605. this._data.push(data[i]);
  37606. }
  37607. this._needSync = true;
  37608. };
  37609. /**
  37610. * Adds a Matrix 4x4 to the uniform buffer.
  37611. * @param name Name of the uniform, as used in the uniform block in the shader.
  37612. * @param mat A 4x4 matrix.
  37613. */
  37614. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37615. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37616. };
  37617. /**
  37618. * Adds a vec2 to the uniform buffer.
  37619. * @param name Name of the uniform, as used in the uniform block in the shader.
  37620. * @param x Define the x component value of the vec2
  37621. * @param y Define the y component value of the vec2
  37622. */
  37623. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37624. var temp = [x, y];
  37625. this.addUniform(name, temp);
  37626. };
  37627. /**
  37628. * Adds a vec3 to the uniform buffer.
  37629. * @param name Name of the uniform, as used in the uniform block in the shader.
  37630. * @param x Define the x component value of the vec3
  37631. * @param y Define the y component value of the vec3
  37632. * @param z Define the z component value of the vec3
  37633. */
  37634. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37635. var temp = [x, y, z];
  37636. this.addUniform(name, temp);
  37637. };
  37638. /**
  37639. * Adds a vec3 to the uniform buffer.
  37640. * @param name Name of the uniform, as used in the uniform block in the shader.
  37641. * @param color Define the vec3 from a Color
  37642. */
  37643. UniformBuffer.prototype.addColor3 = function (name, color) {
  37644. var temp = new Array();
  37645. color.toArray(temp);
  37646. this.addUniform(name, temp);
  37647. };
  37648. /**
  37649. * Adds a vec4 to the uniform buffer.
  37650. * @param name Name of the uniform, as used in the uniform block in the shader.
  37651. * @param color Define the rgb components from a Color
  37652. * @param alpha Define the a component of the vec4
  37653. */
  37654. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37655. var temp = new Array();
  37656. color.toArray(temp);
  37657. temp.push(alpha);
  37658. this.addUniform(name, temp);
  37659. };
  37660. /**
  37661. * Adds a vec3 to the uniform buffer.
  37662. * @param name Name of the uniform, as used in the uniform block in the shader.
  37663. * @param vector Define the vec3 components from a Vector
  37664. */
  37665. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37666. var temp = new Array();
  37667. vector.toArray(temp);
  37668. this.addUniform(name, temp);
  37669. };
  37670. /**
  37671. * Adds a Matrix 3x3 to the uniform buffer.
  37672. * @param name Name of the uniform, as used in the uniform block in the shader.
  37673. */
  37674. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37675. this.addUniform(name, 12);
  37676. };
  37677. /**
  37678. * Adds a Matrix 2x2 to the uniform buffer.
  37679. * @param name Name of the uniform, as used in the uniform block in the shader.
  37680. */
  37681. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37682. this.addUniform(name, 8);
  37683. };
  37684. /**
  37685. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37686. */
  37687. UniformBuffer.prototype.create = function () {
  37688. if (this._noUBO) {
  37689. return;
  37690. }
  37691. if (this._buffer) {
  37692. return; // nothing to do
  37693. }
  37694. // See spec, alignment must be filled as a vec4
  37695. this._fillAlignment(4);
  37696. this._bufferData = new Float32Array(this._data);
  37697. this._rebuild();
  37698. this._needSync = true;
  37699. };
  37700. /** @hidden */
  37701. UniformBuffer.prototype._rebuild = function () {
  37702. if (this._noUBO) {
  37703. return;
  37704. }
  37705. if (this._dynamic) {
  37706. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37707. }
  37708. else {
  37709. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37710. }
  37711. };
  37712. /**
  37713. * Updates the WebGL Uniform Buffer on the GPU.
  37714. * If the `dynamic` flag is set to true, no cache comparison is done.
  37715. * Otherwise, the buffer will be updated only if the cache differs.
  37716. */
  37717. UniformBuffer.prototype.update = function () {
  37718. if (!this._buffer) {
  37719. this.create();
  37720. return;
  37721. }
  37722. if (!this._dynamic && !this._needSync) {
  37723. return;
  37724. }
  37725. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37726. this._needSync = false;
  37727. };
  37728. /**
  37729. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37730. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37731. * @param data Define the flattened data
  37732. * @param size Define the size of the data.
  37733. */
  37734. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37735. var location = this._uniformLocations[uniformName];
  37736. if (location === undefined) {
  37737. if (this._buffer) {
  37738. // Cannot add an uniform if the buffer is already created
  37739. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37740. return;
  37741. }
  37742. this.addUniform(uniformName, size);
  37743. location = this._uniformLocations[uniformName];
  37744. }
  37745. if (!this._buffer) {
  37746. this.create();
  37747. }
  37748. if (!this._dynamic) {
  37749. // Cache for static uniform buffers
  37750. var changed = false;
  37751. for (var i = 0; i < size; i++) {
  37752. if (this._bufferData[location + i] !== data[i]) {
  37753. changed = true;
  37754. this._bufferData[location + i] = data[i];
  37755. }
  37756. }
  37757. this._needSync = this._needSync || changed;
  37758. }
  37759. else {
  37760. // No cache for dynamic
  37761. for (var i = 0; i < size; i++) {
  37762. this._bufferData[location + i] = data[i];
  37763. }
  37764. }
  37765. };
  37766. // Update methods
  37767. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37768. // To match std140, matrix must be realigned
  37769. for (var i = 0; i < 3; i++) {
  37770. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37771. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37772. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37773. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37774. }
  37775. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37776. };
  37777. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37778. this._currentEffect.setMatrix3x3(name, matrix);
  37779. };
  37780. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37781. this._currentEffect.setMatrix2x2(name, matrix);
  37782. };
  37783. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37784. // To match std140, matrix must be realigned
  37785. for (var i = 0; i < 2; i++) {
  37786. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37787. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37788. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37789. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37790. }
  37791. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37792. };
  37793. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37794. this._currentEffect.setFloat(name, x);
  37795. };
  37796. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37797. UniformBuffer._tempBuffer[0] = x;
  37798. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37799. };
  37800. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37801. if (suffix === void 0) { suffix = ""; }
  37802. this._currentEffect.setFloat2(name + suffix, x, y);
  37803. };
  37804. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37805. if (suffix === void 0) { suffix = ""; }
  37806. UniformBuffer._tempBuffer[0] = x;
  37807. UniformBuffer._tempBuffer[1] = y;
  37808. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37809. };
  37810. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37811. if (suffix === void 0) { suffix = ""; }
  37812. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37813. };
  37814. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37815. if (suffix === void 0) { suffix = ""; }
  37816. UniformBuffer._tempBuffer[0] = x;
  37817. UniformBuffer._tempBuffer[1] = y;
  37818. UniformBuffer._tempBuffer[2] = z;
  37819. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37820. };
  37821. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37822. if (suffix === void 0) { suffix = ""; }
  37823. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37824. };
  37825. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37826. if (suffix === void 0) { suffix = ""; }
  37827. UniformBuffer._tempBuffer[0] = x;
  37828. UniformBuffer._tempBuffer[1] = y;
  37829. UniformBuffer._tempBuffer[2] = z;
  37830. UniformBuffer._tempBuffer[3] = w;
  37831. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37832. };
  37833. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37834. this._currentEffect.setMatrix(name, mat);
  37835. };
  37836. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37837. this.updateUniform(name, mat.toArray(), 16);
  37838. };
  37839. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37840. this._currentEffect.setVector3(name, vector);
  37841. };
  37842. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37843. vector.toArray(UniformBuffer._tempBuffer);
  37844. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37845. };
  37846. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37847. this._currentEffect.setVector4(name, vector);
  37848. };
  37849. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37850. vector.toArray(UniformBuffer._tempBuffer);
  37851. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37852. };
  37853. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37854. if (suffix === void 0) { suffix = ""; }
  37855. this._currentEffect.setColor3(name + suffix, color);
  37856. };
  37857. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37858. if (suffix === void 0) { suffix = ""; }
  37859. color.toArray(UniformBuffer._tempBuffer);
  37860. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37861. };
  37862. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37863. if (suffix === void 0) { suffix = ""; }
  37864. this._currentEffect.setColor4(name + suffix, color, alpha);
  37865. };
  37866. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37867. if (suffix === void 0) { suffix = ""; }
  37868. color.toArray(UniformBuffer._tempBuffer);
  37869. UniformBuffer._tempBuffer[3] = alpha;
  37870. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37871. };
  37872. /**
  37873. * Sets a sampler uniform on the effect.
  37874. * @param name Define the name of the sampler.
  37875. * @param texture Define the texture to set in the sampler
  37876. */
  37877. UniformBuffer.prototype.setTexture = function (name, texture) {
  37878. this._currentEffect.setTexture(name, texture);
  37879. };
  37880. /**
  37881. * Directly updates the value of the uniform in the cache AND on the GPU.
  37882. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37883. * @param data Define the flattened data
  37884. */
  37885. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37886. this.updateUniform(uniformName, data, data.length);
  37887. this.update();
  37888. };
  37889. /**
  37890. * Binds this uniform buffer to an effect.
  37891. * @param effect Define the effect to bind the buffer to
  37892. * @param name Name of the uniform block in the shader.
  37893. */
  37894. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37895. this._currentEffect = effect;
  37896. if (this._noUBO || !this._buffer) {
  37897. return;
  37898. }
  37899. effect.bindUniformBuffer(this._buffer, name);
  37900. };
  37901. /**
  37902. * Disposes the uniform buffer.
  37903. */
  37904. UniformBuffer.prototype.dispose = function () {
  37905. if (this._noUBO) {
  37906. return;
  37907. }
  37908. var uniformBuffers = this._engine._uniformBuffers;
  37909. var index = uniformBuffers.indexOf(this);
  37910. if (index !== -1) {
  37911. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  37912. uniformBuffers.pop();
  37913. }
  37914. if (!this._buffer) {
  37915. return;
  37916. }
  37917. if (this._engine._releaseBuffer(this._buffer)) {
  37918. this._buffer = null;
  37919. }
  37920. };
  37921. // Pool for avoiding memory leaks
  37922. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37923. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37924. return UniformBuffer;
  37925. }());
  37926. BABYLON.UniformBuffer = UniformBuffer;
  37927. })(BABYLON || (BABYLON = {}));
  37928. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37929. var BABYLON;
  37930. (function (BABYLON) {
  37931. /**
  37932. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37933. */
  37934. var VertexData = /** @class */ (function () {
  37935. function VertexData() {
  37936. }
  37937. /**
  37938. * Uses the passed data array to set the set the values for the specified kind of data
  37939. * @param data a linear array of floating numbers
  37940. * @param kind the type of data that is being set, eg positions, colors etc
  37941. */
  37942. VertexData.prototype.set = function (data, kind) {
  37943. switch (kind) {
  37944. case BABYLON.VertexBuffer.PositionKind:
  37945. this.positions = data;
  37946. break;
  37947. case BABYLON.VertexBuffer.NormalKind:
  37948. this.normals = data;
  37949. break;
  37950. case BABYLON.VertexBuffer.TangentKind:
  37951. this.tangents = data;
  37952. break;
  37953. case BABYLON.VertexBuffer.UVKind:
  37954. this.uvs = data;
  37955. break;
  37956. case BABYLON.VertexBuffer.UV2Kind:
  37957. this.uvs2 = data;
  37958. break;
  37959. case BABYLON.VertexBuffer.UV3Kind:
  37960. this.uvs3 = data;
  37961. break;
  37962. case BABYLON.VertexBuffer.UV4Kind:
  37963. this.uvs4 = data;
  37964. break;
  37965. case BABYLON.VertexBuffer.UV5Kind:
  37966. this.uvs5 = data;
  37967. break;
  37968. case BABYLON.VertexBuffer.UV6Kind:
  37969. this.uvs6 = data;
  37970. break;
  37971. case BABYLON.VertexBuffer.ColorKind:
  37972. this.colors = data;
  37973. break;
  37974. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37975. this.matricesIndices = data;
  37976. break;
  37977. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37978. this.matricesWeights = data;
  37979. break;
  37980. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37981. this.matricesIndicesExtra = data;
  37982. break;
  37983. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37984. this.matricesWeightsExtra = data;
  37985. break;
  37986. }
  37987. };
  37988. /**
  37989. * Associates the vertexData to the passed Mesh.
  37990. * Sets it as updatable or not (default `false`)
  37991. * @param mesh the mesh the vertexData is applied to
  37992. * @param updatable when used and having the value true allows new data to update the vertexData
  37993. * @returns the VertexData
  37994. */
  37995. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37996. this._applyTo(mesh, updatable);
  37997. return this;
  37998. };
  37999. /**
  38000. * Associates the vertexData to the passed Geometry.
  38001. * Sets it as updatable or not (default `false`)
  38002. * @param geometry the geometry the vertexData is applied to
  38003. * @param updatable when used and having the value true allows new data to update the vertexData
  38004. * @returns VertexData
  38005. */
  38006. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38007. this._applyTo(geometry, updatable);
  38008. return this;
  38009. };
  38010. /**
  38011. * Updates the associated mesh
  38012. * @param mesh the mesh to be updated
  38013. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38014. * @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
  38015. * @returns VertexData
  38016. */
  38017. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38018. this._update(mesh);
  38019. return this;
  38020. };
  38021. /**
  38022. * Updates the associated geometry
  38023. * @param geometry the geometry to be updated
  38024. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38025. * @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
  38026. * @returns VertexData.
  38027. */
  38028. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38029. this._update(geometry);
  38030. return this;
  38031. };
  38032. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38033. if (updatable === void 0) { updatable = false; }
  38034. if (this.positions) {
  38035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38036. }
  38037. if (this.normals) {
  38038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38039. }
  38040. if (this.tangents) {
  38041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38042. }
  38043. if (this.uvs) {
  38044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38045. }
  38046. if (this.uvs2) {
  38047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38048. }
  38049. if (this.uvs3) {
  38050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38051. }
  38052. if (this.uvs4) {
  38053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38054. }
  38055. if (this.uvs5) {
  38056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38057. }
  38058. if (this.uvs6) {
  38059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38060. }
  38061. if (this.colors) {
  38062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38063. }
  38064. if (this.matricesIndices) {
  38065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38066. }
  38067. if (this.matricesWeights) {
  38068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38069. }
  38070. if (this.matricesIndicesExtra) {
  38071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38072. }
  38073. if (this.matricesWeightsExtra) {
  38074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38075. }
  38076. if (this.indices) {
  38077. meshOrGeometry.setIndices(this.indices, null, updatable);
  38078. }
  38079. else {
  38080. meshOrGeometry.setIndices([], null);
  38081. }
  38082. return this;
  38083. };
  38084. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38085. if (this.positions) {
  38086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38087. }
  38088. if (this.normals) {
  38089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38090. }
  38091. if (this.tangents) {
  38092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38093. }
  38094. if (this.uvs) {
  38095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38096. }
  38097. if (this.uvs2) {
  38098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38099. }
  38100. if (this.uvs3) {
  38101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38102. }
  38103. if (this.uvs4) {
  38104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38105. }
  38106. if (this.uvs5) {
  38107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38108. }
  38109. if (this.uvs6) {
  38110. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38111. }
  38112. if (this.colors) {
  38113. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38114. }
  38115. if (this.matricesIndices) {
  38116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38117. }
  38118. if (this.matricesWeights) {
  38119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38120. }
  38121. if (this.matricesIndicesExtra) {
  38122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38123. }
  38124. if (this.matricesWeightsExtra) {
  38125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38126. }
  38127. if (this.indices) {
  38128. meshOrGeometry.setIndices(this.indices, null);
  38129. }
  38130. return this;
  38131. };
  38132. /**
  38133. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38134. * @param matrix the transforming matrix
  38135. * @returns the VertexData
  38136. */
  38137. VertexData.prototype.transform = function (matrix) {
  38138. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38139. var transformed = BABYLON.Vector3.Zero();
  38140. var index;
  38141. if (this.positions) {
  38142. var position = BABYLON.Vector3.Zero();
  38143. for (index = 0; index < this.positions.length; index += 3) {
  38144. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38145. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38146. this.positions[index] = transformed.x;
  38147. this.positions[index + 1] = transformed.y;
  38148. this.positions[index + 2] = transformed.z;
  38149. }
  38150. }
  38151. if (this.normals) {
  38152. var normal = BABYLON.Vector3.Zero();
  38153. for (index = 0; index < this.normals.length; index += 3) {
  38154. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38155. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38156. this.normals[index] = transformed.x;
  38157. this.normals[index + 1] = transformed.y;
  38158. this.normals[index + 2] = transformed.z;
  38159. }
  38160. }
  38161. if (this.tangents) {
  38162. var tangent = BABYLON.Vector4.Zero();
  38163. var tangentTransformed = BABYLON.Vector4.Zero();
  38164. for (index = 0; index < this.tangents.length; index += 4) {
  38165. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38166. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38167. this.tangents[index] = tangentTransformed.x;
  38168. this.tangents[index + 1] = tangentTransformed.y;
  38169. this.tangents[index + 2] = tangentTransformed.z;
  38170. this.tangents[index + 3] = tangentTransformed.w;
  38171. }
  38172. }
  38173. if (flip && this.indices) {
  38174. for (index = 0; index < this.indices.length; index += 3) {
  38175. var tmp = this.indices[index + 1];
  38176. this.indices[index + 1] = this.indices[index + 2];
  38177. this.indices[index + 2] = tmp;
  38178. }
  38179. }
  38180. return this;
  38181. };
  38182. /**
  38183. * Merges the passed VertexData into the current one
  38184. * @param other the VertexData to be merged into the current one
  38185. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38186. * @returns the modified VertexData
  38187. */
  38188. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38189. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38190. this._validate();
  38191. other._validate();
  38192. if (!this.normals !== !other.normals ||
  38193. !this.tangents !== !other.tangents ||
  38194. !this.uvs !== !other.uvs ||
  38195. !this.uvs2 !== !other.uvs2 ||
  38196. !this.uvs3 !== !other.uvs3 ||
  38197. !this.uvs4 !== !other.uvs4 ||
  38198. !this.uvs5 !== !other.uvs5 ||
  38199. !this.uvs6 !== !other.uvs6 ||
  38200. !this.colors !== !other.colors ||
  38201. !this.matricesIndices !== !other.matricesIndices ||
  38202. !this.matricesWeights !== !other.matricesWeights ||
  38203. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38204. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38205. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38206. }
  38207. if (other.indices) {
  38208. if (!this.indices) {
  38209. this.indices = [];
  38210. }
  38211. var offset = this.positions ? this.positions.length / 3 : 0;
  38212. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38213. if (isSrcTypedArray) {
  38214. var len = this.indices.length + other.indices.length;
  38215. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38216. temp.set(this.indices);
  38217. var decal = this.indices.length;
  38218. for (var index = 0; index < other.indices.length; index++) {
  38219. temp[decal + index] = other.indices[index] + offset;
  38220. }
  38221. this.indices = temp;
  38222. }
  38223. else {
  38224. for (var index = 0; index < other.indices.length; index++) {
  38225. this.indices.push(other.indices[index] + offset);
  38226. }
  38227. }
  38228. }
  38229. this.positions = this._mergeElement(this.positions, other.positions);
  38230. this.normals = this._mergeElement(this.normals, other.normals);
  38231. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38232. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38233. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38234. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38235. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38236. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38237. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38238. this.colors = this._mergeElement(this.colors, other.colors);
  38239. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38240. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38241. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38242. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38243. return this;
  38244. };
  38245. VertexData.prototype._mergeElement = function (source, other) {
  38246. if (!source) {
  38247. return other;
  38248. }
  38249. if (!other) {
  38250. return source;
  38251. }
  38252. var len = other.length + source.length;
  38253. var isSrcTypedArray = source instanceof Float32Array;
  38254. var isOthTypedArray = other instanceof Float32Array;
  38255. // use non-loop method when the source is Float32Array
  38256. if (isSrcTypedArray) {
  38257. var ret32 = new Float32Array(len);
  38258. ret32.set(source);
  38259. ret32.set(other, source.length);
  38260. return ret32;
  38261. // source is number[], when other is also use concat
  38262. }
  38263. else if (!isOthTypedArray) {
  38264. return source.concat(other);
  38265. // source is a number[], but other is a Float32Array, loop required
  38266. }
  38267. else {
  38268. var ret = source.slice(0); // copy source to a separate array
  38269. for (var i = 0, len = other.length; i < len; i++) {
  38270. ret.push(other[i]);
  38271. }
  38272. return ret;
  38273. }
  38274. };
  38275. VertexData.prototype._validate = function () {
  38276. if (!this.positions) {
  38277. throw new Error("Positions are required");
  38278. }
  38279. var getElementCount = function (kind, values) {
  38280. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38281. if ((values.length % stride) !== 0) {
  38282. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38283. }
  38284. return values.length / stride;
  38285. };
  38286. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38287. var validateElementCount = function (kind, values) {
  38288. var elementCount = getElementCount(kind, values);
  38289. if (elementCount !== positionsElementCount) {
  38290. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38291. }
  38292. };
  38293. if (this.normals) {
  38294. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38295. }
  38296. if (this.tangents) {
  38297. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38298. }
  38299. if (this.uvs) {
  38300. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38301. }
  38302. if (this.uvs2) {
  38303. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38304. }
  38305. if (this.uvs3) {
  38306. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38307. }
  38308. if (this.uvs4) {
  38309. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38310. }
  38311. if (this.uvs5) {
  38312. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38313. }
  38314. if (this.uvs6) {
  38315. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38316. }
  38317. if (this.colors) {
  38318. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38319. }
  38320. if (this.matricesIndices) {
  38321. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38322. }
  38323. if (this.matricesWeights) {
  38324. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38325. }
  38326. if (this.matricesIndicesExtra) {
  38327. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38328. }
  38329. if (this.matricesWeightsExtra) {
  38330. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38331. }
  38332. };
  38333. /**
  38334. * Serializes the VertexData
  38335. * @returns a serialized object
  38336. */
  38337. VertexData.prototype.serialize = function () {
  38338. var serializationObject = this.serialize();
  38339. if (this.positions) {
  38340. serializationObject.positions = this.positions;
  38341. }
  38342. if (this.normals) {
  38343. serializationObject.normals = this.normals;
  38344. }
  38345. if (this.tangents) {
  38346. serializationObject.tangents = this.tangents;
  38347. }
  38348. if (this.uvs) {
  38349. serializationObject.uvs = this.uvs;
  38350. }
  38351. if (this.uvs2) {
  38352. serializationObject.uvs2 = this.uvs2;
  38353. }
  38354. if (this.uvs3) {
  38355. serializationObject.uvs3 = this.uvs3;
  38356. }
  38357. if (this.uvs4) {
  38358. serializationObject.uvs4 = this.uvs4;
  38359. }
  38360. if (this.uvs5) {
  38361. serializationObject.uvs5 = this.uvs5;
  38362. }
  38363. if (this.uvs6) {
  38364. serializationObject.uvs6 = this.uvs6;
  38365. }
  38366. if (this.colors) {
  38367. serializationObject.colors = this.colors;
  38368. }
  38369. if (this.matricesIndices) {
  38370. serializationObject.matricesIndices = this.matricesIndices;
  38371. serializationObject.matricesIndices._isExpanded = true;
  38372. }
  38373. if (this.matricesWeights) {
  38374. serializationObject.matricesWeights = this.matricesWeights;
  38375. }
  38376. if (this.matricesIndicesExtra) {
  38377. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38378. serializationObject.matricesIndicesExtra._isExpanded = true;
  38379. }
  38380. if (this.matricesWeightsExtra) {
  38381. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38382. }
  38383. serializationObject.indices = this.indices;
  38384. return serializationObject;
  38385. };
  38386. // Statics
  38387. /**
  38388. * Extracts the vertexData from a mesh
  38389. * @param mesh the mesh from which to extract the VertexData
  38390. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38391. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38392. * @returns the object VertexData associated to the passed mesh
  38393. */
  38394. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38395. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38396. };
  38397. /**
  38398. * Extracts the vertexData from the geometry
  38399. * @param geometry the geometry from which to extract the VertexData
  38400. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38401. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38402. * @returns the object VertexData associated to the passed mesh
  38403. */
  38404. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38405. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38406. };
  38407. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38408. var result = new VertexData();
  38409. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38410. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38411. }
  38412. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38413. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38414. }
  38415. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38416. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38417. }
  38418. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38419. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38420. }
  38421. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38422. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38423. }
  38424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38425. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38426. }
  38427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38428. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38429. }
  38430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38431. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38432. }
  38433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38434. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38435. }
  38436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38437. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38438. }
  38439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38440. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38441. }
  38442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38443. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38444. }
  38445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38446. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38447. }
  38448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38449. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38450. }
  38451. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38452. return result;
  38453. };
  38454. /**
  38455. * Creates the VertexData for a Ribbon
  38456. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38457. * * pathArray array of paths, each of which an array of successive Vector3
  38458. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38459. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38460. * * 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
  38461. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38462. * * 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)
  38463. * * 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)
  38464. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38465. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38466. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38467. * @returns the VertexData of the ribbon
  38468. */
  38469. VertexData.CreateRibbon = function (options) {
  38470. var pathArray = options.pathArray;
  38471. var closeArray = options.closeArray || false;
  38472. var closePath = options.closePath || false;
  38473. var invertUV = options.invertUV || false;
  38474. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38475. var offset = options.offset || defaultOffset;
  38476. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38477. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38478. var customUV = options.uvs;
  38479. var customColors = options.colors;
  38480. var positions = [];
  38481. var indices = [];
  38482. var normals = [];
  38483. var uvs = [];
  38484. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38485. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38486. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38487. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38488. var minlg; // minimal length among all paths from pathArray
  38489. var lg = []; // array of path lengths : nb of vertex per path
  38490. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38491. var p; // path iterator
  38492. var i; // point iterator
  38493. var j; // point iterator
  38494. // if single path in pathArray
  38495. if (pathArray.length < 2) {
  38496. var ar1 = [];
  38497. var ar2 = [];
  38498. for (i = 0; i < pathArray[0].length - offset; i++) {
  38499. ar1.push(pathArray[0][i]);
  38500. ar2.push(pathArray[0][i + offset]);
  38501. }
  38502. pathArray = [ar1, ar2];
  38503. }
  38504. // positions and horizontal distances (u)
  38505. var idc = 0;
  38506. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38507. var path;
  38508. var l;
  38509. minlg = pathArray[0].length;
  38510. var vectlg;
  38511. var dist;
  38512. for (p = 0; p < pathArray.length; p++) {
  38513. uTotalDistance[p] = 0;
  38514. us[p] = [0];
  38515. path = pathArray[p];
  38516. l = path.length;
  38517. minlg = (minlg < l) ? minlg : l;
  38518. j = 0;
  38519. while (j < l) {
  38520. positions.push(path[j].x, path[j].y, path[j].z);
  38521. if (j > 0) {
  38522. vectlg = path[j].subtract(path[j - 1]).length();
  38523. dist = vectlg + uTotalDistance[p];
  38524. us[p].push(dist);
  38525. uTotalDistance[p] = dist;
  38526. }
  38527. j++;
  38528. }
  38529. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38530. j--;
  38531. positions.push(path[0].x, path[0].y, path[0].z);
  38532. vectlg = path[j].subtract(path[0]).length();
  38533. dist = vectlg + uTotalDistance[p];
  38534. us[p].push(dist);
  38535. uTotalDistance[p] = dist;
  38536. }
  38537. lg[p] = l + closePathCorr;
  38538. idx[p] = idc;
  38539. idc += (l + closePathCorr);
  38540. }
  38541. // vertical distances (v)
  38542. var path1;
  38543. var path2;
  38544. var vertex1 = null;
  38545. var vertex2 = null;
  38546. for (i = 0; i < minlg + closePathCorr; i++) {
  38547. vTotalDistance[i] = 0;
  38548. vs[i] = [0];
  38549. for (p = 0; p < pathArray.length - 1; p++) {
  38550. path1 = pathArray[p];
  38551. path2 = pathArray[p + 1];
  38552. if (i === minlg) { // closePath
  38553. vertex1 = path1[0];
  38554. vertex2 = path2[0];
  38555. }
  38556. else {
  38557. vertex1 = path1[i];
  38558. vertex2 = path2[i];
  38559. }
  38560. vectlg = vertex2.subtract(vertex1).length();
  38561. dist = vectlg + vTotalDistance[i];
  38562. vs[i].push(dist);
  38563. vTotalDistance[i] = dist;
  38564. }
  38565. if (closeArray && vertex2 && vertex1) {
  38566. path1 = pathArray[p];
  38567. path2 = pathArray[0];
  38568. if (i === minlg) { // closePath
  38569. vertex2 = path2[0];
  38570. }
  38571. vectlg = vertex2.subtract(vertex1).length();
  38572. dist = vectlg + vTotalDistance[i];
  38573. vTotalDistance[i] = dist;
  38574. }
  38575. }
  38576. // uvs
  38577. var u;
  38578. var v;
  38579. if (customUV) {
  38580. for (p = 0; p < customUV.length; p++) {
  38581. uvs.push(customUV[p].x, customUV[p].y);
  38582. }
  38583. }
  38584. else {
  38585. for (p = 0; p < pathArray.length; p++) {
  38586. for (i = 0; i < minlg + closePathCorr; i++) {
  38587. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38588. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38589. if (invertUV) {
  38590. uvs.push(v, u);
  38591. }
  38592. else {
  38593. uvs.push(u, v);
  38594. }
  38595. }
  38596. }
  38597. }
  38598. // indices
  38599. p = 0; // path index
  38600. var pi = 0; // positions array index
  38601. var l1 = lg[p] - 1; // path1 length
  38602. var l2 = lg[p + 1] - 1; // path2 length
  38603. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38604. var shft = idx[1] - idx[0]; // shift
  38605. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38606. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38607. // 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
  38608. indices.push(pi, pi + shft, pi + 1);
  38609. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38610. pi += 1;
  38611. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38612. p++;
  38613. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38614. shft = idx[0] - idx[p];
  38615. l1 = lg[p] - 1;
  38616. l2 = lg[0] - 1;
  38617. }
  38618. else {
  38619. shft = idx[p + 1] - idx[p];
  38620. l1 = lg[p] - 1;
  38621. l2 = lg[p + 1] - 1;
  38622. }
  38623. pi = idx[p];
  38624. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38625. }
  38626. }
  38627. // normals
  38628. VertexData.ComputeNormals(positions, indices, normals);
  38629. if (closePath) { // update both the first and last vertex normals to their average value
  38630. var indexFirst = 0;
  38631. var indexLast = 0;
  38632. for (p = 0; p < pathArray.length; p++) {
  38633. indexFirst = idx[p] * 3;
  38634. if (p + 1 < pathArray.length) {
  38635. indexLast = (idx[p + 1] - 1) * 3;
  38636. }
  38637. else {
  38638. indexLast = normals.length - 3;
  38639. }
  38640. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38641. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38642. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38643. normals[indexLast] = normals[indexFirst];
  38644. normals[indexLast + 1] = normals[indexFirst + 1];
  38645. normals[indexLast + 2] = normals[indexFirst + 2];
  38646. }
  38647. }
  38648. // sides
  38649. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38650. // Colors
  38651. var colors = null;
  38652. if (customColors) {
  38653. colors = new Float32Array(customColors.length * 4);
  38654. for (var c = 0; c < customColors.length; c++) {
  38655. colors[c * 4] = customColors[c].r;
  38656. colors[c * 4 + 1] = customColors[c].g;
  38657. colors[c * 4 + 2] = customColors[c].b;
  38658. colors[c * 4 + 3] = customColors[c].a;
  38659. }
  38660. }
  38661. // Result
  38662. var vertexData = new VertexData();
  38663. var positions32 = new Float32Array(positions);
  38664. var normals32 = new Float32Array(normals);
  38665. var uvs32 = new Float32Array(uvs);
  38666. vertexData.indices = indices;
  38667. vertexData.positions = positions32;
  38668. vertexData.normals = normals32;
  38669. vertexData.uvs = uvs32;
  38670. if (colors) {
  38671. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38672. }
  38673. if (closePath) {
  38674. vertexData._idx = idx;
  38675. }
  38676. return vertexData;
  38677. };
  38678. /**
  38679. * Creates the VertexData for a box
  38680. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38681. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38682. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38683. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38684. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38685. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38686. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38687. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38688. * * 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)
  38689. * * 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)
  38690. * @returns the VertexData of the box
  38691. */
  38692. VertexData.CreateBox = function (options) {
  38693. var normalsSource = [
  38694. new BABYLON.Vector3(0, 0, 1),
  38695. new BABYLON.Vector3(0, 0, -1),
  38696. new BABYLON.Vector3(1, 0, 0),
  38697. new BABYLON.Vector3(-1, 0, 0),
  38698. new BABYLON.Vector3(0, 1, 0),
  38699. new BABYLON.Vector3(0, -1, 0)
  38700. ];
  38701. var indices = [];
  38702. var positions = [];
  38703. var normals = [];
  38704. var uvs = [];
  38705. var width = options.width || options.size || 1;
  38706. var height = options.height || options.size || 1;
  38707. var depth = options.depth || options.size || 1;
  38708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38709. var faceUV = options.faceUV || new Array(6);
  38710. var faceColors = options.faceColors;
  38711. var colors = [];
  38712. // default face colors and UV if undefined
  38713. for (var f = 0; f < 6; f++) {
  38714. if (faceUV[f] === undefined) {
  38715. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38716. }
  38717. if (faceColors && faceColors[f] === undefined) {
  38718. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38719. }
  38720. }
  38721. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38722. // Create each face in turn.
  38723. for (var index = 0; index < normalsSource.length; index++) {
  38724. var normal = normalsSource[index];
  38725. // Get two vectors perpendicular to the face normal and to each other.
  38726. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38727. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38728. // Six indices (two triangles) per face.
  38729. var verticesLength = positions.length / 3;
  38730. indices.push(verticesLength);
  38731. indices.push(verticesLength + 1);
  38732. indices.push(verticesLength + 2);
  38733. indices.push(verticesLength);
  38734. indices.push(verticesLength + 2);
  38735. indices.push(verticesLength + 3);
  38736. // Four vertices per face.
  38737. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38738. positions.push(vertex.x, vertex.y, vertex.z);
  38739. normals.push(normal.x, normal.y, normal.z);
  38740. uvs.push(faceUV[index].z, faceUV[index].w);
  38741. if (faceColors) {
  38742. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38743. }
  38744. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38745. positions.push(vertex.x, vertex.y, vertex.z);
  38746. normals.push(normal.x, normal.y, normal.z);
  38747. uvs.push(faceUV[index].x, faceUV[index].w);
  38748. if (faceColors) {
  38749. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38750. }
  38751. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38752. positions.push(vertex.x, vertex.y, vertex.z);
  38753. normals.push(normal.x, normal.y, normal.z);
  38754. uvs.push(faceUV[index].x, faceUV[index].y);
  38755. if (faceColors) {
  38756. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38757. }
  38758. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38759. positions.push(vertex.x, vertex.y, vertex.z);
  38760. normals.push(normal.x, normal.y, normal.z);
  38761. uvs.push(faceUV[index].z, faceUV[index].y);
  38762. if (faceColors) {
  38763. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38764. }
  38765. }
  38766. // sides
  38767. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38768. // Result
  38769. var vertexData = new VertexData();
  38770. vertexData.indices = indices;
  38771. vertexData.positions = positions;
  38772. vertexData.normals = normals;
  38773. vertexData.uvs = uvs;
  38774. if (faceColors) {
  38775. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38776. vertexData.colors = totalColors;
  38777. }
  38778. return vertexData;
  38779. };
  38780. /**
  38781. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38782. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38783. * * segments sets the number of horizontal strips optional, default 32
  38784. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38785. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38786. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38787. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38788. * * 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
  38789. * * 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
  38790. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38791. * * 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)
  38792. * * 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)
  38793. * @returns the VertexData of the ellipsoid
  38794. */
  38795. VertexData.CreateSphere = function (options) {
  38796. var segments = options.segments || 32;
  38797. var diameterX = options.diameterX || options.diameter || 1;
  38798. var diameterY = options.diameterY || options.diameter || 1;
  38799. var diameterZ = options.diameterZ || options.diameter || 1;
  38800. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38801. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38802. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38803. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38804. var totalZRotationSteps = 2 + segments;
  38805. var totalYRotationSteps = 2 * totalZRotationSteps;
  38806. var indices = [];
  38807. var positions = [];
  38808. var normals = [];
  38809. var uvs = [];
  38810. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38811. var normalizedZ = zRotationStep / totalZRotationSteps;
  38812. var angleZ = normalizedZ * Math.PI * slice;
  38813. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38814. var normalizedY = yRotationStep / totalYRotationSteps;
  38815. var angleY = normalizedY * Math.PI * 2 * arc;
  38816. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38817. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38818. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38819. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38820. var vertex = complete.multiply(radius);
  38821. var normal = complete.divide(radius).normalize();
  38822. positions.push(vertex.x, vertex.y, vertex.z);
  38823. normals.push(normal.x, normal.y, normal.z);
  38824. uvs.push(normalizedY, normalizedZ);
  38825. }
  38826. if (zRotationStep > 0) {
  38827. var verticesCount = positions.length / 3;
  38828. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38829. indices.push((firstIndex));
  38830. indices.push((firstIndex + 1));
  38831. indices.push(firstIndex + totalYRotationSteps + 1);
  38832. indices.push((firstIndex + totalYRotationSteps + 1));
  38833. indices.push((firstIndex + 1));
  38834. indices.push((firstIndex + totalYRotationSteps + 2));
  38835. }
  38836. }
  38837. }
  38838. // Sides
  38839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38840. // Result
  38841. var vertexData = new VertexData();
  38842. vertexData.indices = indices;
  38843. vertexData.positions = positions;
  38844. vertexData.normals = normals;
  38845. vertexData.uvs = uvs;
  38846. return vertexData;
  38847. };
  38848. /**
  38849. * Creates the VertexData for a cylinder, cone or prism
  38850. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38851. * * height sets the height (y direction) of the cylinder, optional, default 2
  38852. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38853. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38854. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38855. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38856. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38857. * * 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
  38858. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38859. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38860. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38861. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38862. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38863. * * 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)
  38864. * * 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)
  38865. * @returns the VertexData of the cylinder, cone or prism
  38866. */
  38867. VertexData.CreateCylinder = function (options) {
  38868. var height = options.height || 2;
  38869. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38870. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38871. var tessellation = options.tessellation || 24;
  38872. var subdivisions = options.subdivisions || 1;
  38873. var hasRings = options.hasRings ? true : false;
  38874. var enclose = options.enclose ? true : false;
  38875. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38876. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38877. var faceUV = options.faceUV || new Array(3);
  38878. var faceColors = options.faceColors;
  38879. // default face colors and UV if undefined
  38880. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38881. var ringNb = (hasRings) ? subdivisions : 1;
  38882. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38883. var f;
  38884. for (f = 0; f < surfaceNb; f++) {
  38885. if (faceColors && faceColors[f] === undefined) {
  38886. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38887. }
  38888. }
  38889. for (f = 0; f < surfaceNb; f++) {
  38890. if (faceUV && faceUV[f] === undefined) {
  38891. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38892. }
  38893. }
  38894. var indices = new Array();
  38895. var positions = new Array();
  38896. var normals = new Array();
  38897. var uvs = new Array();
  38898. var colors = new Array();
  38899. var angle_step = Math.PI * 2 * arc / tessellation;
  38900. var angle;
  38901. var h;
  38902. var radius;
  38903. var tan = (diameterBottom - diameterTop) / 2 / height;
  38904. var ringVertex = BABYLON.Vector3.Zero();
  38905. var ringNormal = BABYLON.Vector3.Zero();
  38906. var ringFirstVertex = BABYLON.Vector3.Zero();
  38907. var ringFirstNormal = BABYLON.Vector3.Zero();
  38908. var quadNormal = BABYLON.Vector3.Zero();
  38909. var Y = BABYLON.Axis.Y;
  38910. // positions, normals, uvs
  38911. var i;
  38912. var j;
  38913. var r;
  38914. var ringIdx = 1;
  38915. var s = 1; // surface index
  38916. var cs = 0;
  38917. var v = 0;
  38918. for (i = 0; i <= subdivisions; i++) {
  38919. h = i / subdivisions;
  38920. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38921. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38922. for (r = 0; r < ringIdx; r++) {
  38923. if (hasRings) {
  38924. s += r;
  38925. }
  38926. if (enclose) {
  38927. s += 2 * r;
  38928. }
  38929. for (j = 0; j <= tessellation; j++) {
  38930. angle = j * angle_step;
  38931. // position
  38932. ringVertex.x = Math.cos(-angle) * radius;
  38933. ringVertex.y = -height / 2 + h * height;
  38934. ringVertex.z = Math.sin(-angle) * radius;
  38935. // normal
  38936. if (diameterTop === 0 && i === subdivisions) {
  38937. // if no top cap, reuse former normals
  38938. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38939. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38940. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38941. }
  38942. else {
  38943. ringNormal.x = ringVertex.x;
  38944. ringNormal.z = ringVertex.z;
  38945. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38946. ringNormal.normalize();
  38947. }
  38948. // keep first ring vertex values for enclose
  38949. if (j === 0) {
  38950. ringFirstVertex.copyFrom(ringVertex);
  38951. ringFirstNormal.copyFrom(ringNormal);
  38952. }
  38953. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38954. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38955. if (hasRings) {
  38956. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38957. }
  38958. else {
  38959. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38960. }
  38961. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38962. if (faceColors) {
  38963. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38964. }
  38965. }
  38966. // if enclose, add four vertices and their dedicated normals
  38967. if (arc !== 1 && enclose) {
  38968. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38969. positions.push(0, ringVertex.y, 0);
  38970. positions.push(0, ringVertex.y, 0);
  38971. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38972. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38973. quadNormal.normalize();
  38974. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38975. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38976. quadNormal.normalize();
  38977. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38978. if (hasRings) {
  38979. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38980. }
  38981. else {
  38982. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38983. }
  38984. uvs.push(faceUV[s + 1].x, v);
  38985. uvs.push(faceUV[s + 1].z, v);
  38986. if (hasRings) {
  38987. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38988. }
  38989. else {
  38990. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38991. }
  38992. uvs.push(faceUV[s + 2].x, v);
  38993. uvs.push(faceUV[s + 2].z, v);
  38994. if (faceColors) {
  38995. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38996. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38997. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38998. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38999. }
  39000. }
  39001. if (cs !== s) {
  39002. cs = s;
  39003. }
  39004. }
  39005. }
  39006. // indices
  39007. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39008. var s;
  39009. i = 0;
  39010. for (s = 0; s < subdivisions; s++) {
  39011. var i0 = 0;
  39012. var i1 = 0;
  39013. var i2 = 0;
  39014. var i3 = 0;
  39015. for (j = 0; j < tessellation; j++) {
  39016. i0 = i * (e + 1) + j;
  39017. i1 = (i + 1) * (e + 1) + j;
  39018. i2 = i * (e + 1) + (j + 1);
  39019. i3 = (i + 1) * (e + 1) + (j + 1);
  39020. indices.push(i0, i1, i2);
  39021. indices.push(i3, i2, i1);
  39022. }
  39023. if (arc !== 1 && enclose) { // if enclose, add two quads
  39024. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39025. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39026. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39027. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39028. }
  39029. i = (hasRings) ? (i + 2) : (i + 1);
  39030. }
  39031. // Caps
  39032. var createCylinderCap = function (isTop) {
  39033. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39034. if (radius === 0) {
  39035. return;
  39036. }
  39037. // Cap positions, normals & uvs
  39038. var angle;
  39039. var circleVector;
  39040. var i;
  39041. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39042. var c = null;
  39043. if (faceColors) {
  39044. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39045. }
  39046. // cap center
  39047. var vbase = positions.length / 3;
  39048. var offset = isTop ? height / 2 : -height / 2;
  39049. var center = new BABYLON.Vector3(0, offset, 0);
  39050. positions.push(center.x, center.y, center.z);
  39051. normals.push(0, isTop ? 1 : -1, 0);
  39052. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39053. if (c) {
  39054. colors.push(c.r, c.g, c.b, c.a);
  39055. }
  39056. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39057. for (i = 0; i <= tessellation; i++) {
  39058. angle = Math.PI * 2 * i * arc / tessellation;
  39059. var cos = Math.cos(-angle);
  39060. var sin = Math.sin(-angle);
  39061. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39062. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39063. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39064. normals.push(0, isTop ? 1 : -1, 0);
  39065. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39066. if (c) {
  39067. colors.push(c.r, c.g, c.b, c.a);
  39068. }
  39069. }
  39070. // Cap indices
  39071. for (i = 0; i < tessellation; i++) {
  39072. if (!isTop) {
  39073. indices.push(vbase);
  39074. indices.push(vbase + (i + 1));
  39075. indices.push(vbase + (i + 2));
  39076. }
  39077. else {
  39078. indices.push(vbase);
  39079. indices.push(vbase + (i + 2));
  39080. indices.push(vbase + (i + 1));
  39081. }
  39082. }
  39083. };
  39084. // add caps to geometry
  39085. createCylinderCap(false);
  39086. createCylinderCap(true);
  39087. // Sides
  39088. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39089. var vertexData = new VertexData();
  39090. vertexData.indices = indices;
  39091. vertexData.positions = positions;
  39092. vertexData.normals = normals;
  39093. vertexData.uvs = uvs;
  39094. if (faceColors) {
  39095. vertexData.colors = colors;
  39096. }
  39097. return vertexData;
  39098. };
  39099. /**
  39100. * Creates the VertexData for a torus
  39101. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39102. * * diameter the diameter of the torus, optional default 1
  39103. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39104. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39105. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39106. * * 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)
  39107. * * 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)
  39108. * @returns the VertexData of the torus
  39109. */
  39110. VertexData.CreateTorus = function (options) {
  39111. var indices = [];
  39112. var positions = [];
  39113. var normals = [];
  39114. var uvs = [];
  39115. var diameter = options.diameter || 1;
  39116. var thickness = options.thickness || 0.5;
  39117. var tessellation = options.tessellation || 16;
  39118. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39119. var stride = tessellation + 1;
  39120. for (var i = 0; i <= tessellation; i++) {
  39121. var u = i / tessellation;
  39122. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39123. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39124. for (var j = 0; j <= tessellation; j++) {
  39125. var v = 1 - j / tessellation;
  39126. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39127. var dx = Math.cos(innerAngle);
  39128. var dy = Math.sin(innerAngle);
  39129. // Create a vertex.
  39130. var normal = new BABYLON.Vector3(dx, dy, 0);
  39131. var position = normal.scale(thickness / 2);
  39132. var textureCoordinate = new BABYLON.Vector2(u, v);
  39133. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39134. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39135. positions.push(position.x, position.y, position.z);
  39136. normals.push(normal.x, normal.y, normal.z);
  39137. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39138. // And create indices for two triangles.
  39139. var nextI = (i + 1) % stride;
  39140. var nextJ = (j + 1) % stride;
  39141. indices.push(i * stride + j);
  39142. indices.push(i * stride + nextJ);
  39143. indices.push(nextI * stride + j);
  39144. indices.push(i * stride + nextJ);
  39145. indices.push(nextI * stride + nextJ);
  39146. indices.push(nextI * stride + j);
  39147. }
  39148. }
  39149. // Sides
  39150. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39151. // Result
  39152. var vertexData = new VertexData();
  39153. vertexData.indices = indices;
  39154. vertexData.positions = positions;
  39155. vertexData.normals = normals;
  39156. vertexData.uvs = uvs;
  39157. return vertexData;
  39158. };
  39159. /**
  39160. * Creates the VertexData of the LineSystem
  39161. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39162. * - lines an array of lines, each line being an array of successive Vector3
  39163. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39164. * @returns the VertexData of the LineSystem
  39165. */
  39166. VertexData.CreateLineSystem = function (options) {
  39167. var indices = [];
  39168. var positions = [];
  39169. var lines = options.lines;
  39170. var colors = options.colors;
  39171. var vertexColors = [];
  39172. var idx = 0;
  39173. for (var l = 0; l < lines.length; l++) {
  39174. var points = lines[l];
  39175. for (var index = 0; index < points.length; index++) {
  39176. positions.push(points[index].x, points[index].y, points[index].z);
  39177. if (colors) {
  39178. var color = colors[l];
  39179. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39180. }
  39181. if (index > 0) {
  39182. indices.push(idx - 1);
  39183. indices.push(idx);
  39184. }
  39185. idx++;
  39186. }
  39187. }
  39188. var vertexData = new VertexData();
  39189. vertexData.indices = indices;
  39190. vertexData.positions = positions;
  39191. if (colors) {
  39192. vertexData.colors = vertexColors;
  39193. }
  39194. return vertexData;
  39195. };
  39196. /**
  39197. * Create the VertexData for a DashedLines
  39198. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39199. * - points an array successive Vector3
  39200. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39201. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39202. * - dashNb the intended total number of dashes, optional, default 200
  39203. * @returns the VertexData for the DashedLines
  39204. */
  39205. VertexData.CreateDashedLines = function (options) {
  39206. var dashSize = options.dashSize || 3;
  39207. var gapSize = options.gapSize || 1;
  39208. var dashNb = options.dashNb || 200;
  39209. var points = options.points;
  39210. var positions = new Array();
  39211. var indices = new Array();
  39212. var curvect = BABYLON.Vector3.Zero();
  39213. var lg = 0;
  39214. var nb = 0;
  39215. var shft = 0;
  39216. var dashshft = 0;
  39217. var curshft = 0;
  39218. var idx = 0;
  39219. var i = 0;
  39220. for (i = 0; i < points.length - 1; i++) {
  39221. points[i + 1].subtractToRef(points[i], curvect);
  39222. lg += curvect.length();
  39223. }
  39224. shft = lg / dashNb;
  39225. dashshft = dashSize * shft / (dashSize + gapSize);
  39226. for (i = 0; i < points.length - 1; i++) {
  39227. points[i + 1].subtractToRef(points[i], curvect);
  39228. nb = Math.floor(curvect.length() / shft);
  39229. curvect.normalize();
  39230. for (var j = 0; j < nb; j++) {
  39231. curshft = shft * j;
  39232. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39233. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39234. indices.push(idx, idx + 1);
  39235. idx += 2;
  39236. }
  39237. }
  39238. // Result
  39239. var vertexData = new VertexData();
  39240. vertexData.positions = positions;
  39241. vertexData.indices = indices;
  39242. return vertexData;
  39243. };
  39244. /**
  39245. * Creates the VertexData for a Ground
  39246. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39247. * - width the width (x direction) of the ground, optional, default 1
  39248. * - height the height (z direction) of the ground, optional, default 1
  39249. * - subdivisions the number of subdivisions per side, optional, default 1
  39250. * @returns the VertexData of the Ground
  39251. */
  39252. VertexData.CreateGround = function (options) {
  39253. var indices = [];
  39254. var positions = [];
  39255. var normals = [];
  39256. var uvs = [];
  39257. var row, col;
  39258. var width = options.width || 1;
  39259. var height = options.height || 1;
  39260. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39261. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39262. for (row = 0; row <= subdivisionsY; row++) {
  39263. for (col = 0; col <= subdivisionsX; col++) {
  39264. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39265. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39266. positions.push(position.x, position.y, position.z);
  39267. normals.push(normal.x, normal.y, normal.z);
  39268. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39269. }
  39270. }
  39271. for (row = 0; row < subdivisionsY; row++) {
  39272. for (col = 0; col < subdivisionsX; col++) {
  39273. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39274. indices.push(col + 1 + row * (subdivisionsX + 1));
  39275. indices.push(col + row * (subdivisionsX + 1));
  39276. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39277. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39278. indices.push(col + row * (subdivisionsX + 1));
  39279. }
  39280. }
  39281. // Result
  39282. var vertexData = new VertexData();
  39283. vertexData.indices = indices;
  39284. vertexData.positions = positions;
  39285. vertexData.normals = normals;
  39286. vertexData.uvs = uvs;
  39287. return vertexData;
  39288. };
  39289. /**
  39290. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39291. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39292. * * xmin the ground minimum X coordinate, optional, default -1
  39293. * * zmin the ground minimum Z coordinate, optional, default -1
  39294. * * xmax the ground maximum X coordinate, optional, default 1
  39295. * * zmax the ground maximum Z coordinate, optional, default 1
  39296. * * 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}
  39297. * * 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}
  39298. * @returns the VertexData of the TiledGround
  39299. */
  39300. VertexData.CreateTiledGround = function (options) {
  39301. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39302. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39303. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39304. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39305. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39306. var precision = options.precision || { w: 1, h: 1 };
  39307. var indices = new Array();
  39308. var positions = new Array();
  39309. var normals = new Array();
  39310. var uvs = new Array();
  39311. var row, col, tileRow, tileCol;
  39312. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39313. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39314. precision.w = (precision.w < 1) ? 1 : precision.w;
  39315. precision.h = (precision.h < 1) ? 1 : precision.h;
  39316. var tileSize = {
  39317. 'w': (xmax - xmin) / subdivisions.w,
  39318. 'h': (zmax - zmin) / subdivisions.h
  39319. };
  39320. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39321. // Indices
  39322. var base = positions.length / 3;
  39323. var rowLength = precision.w + 1;
  39324. for (row = 0; row < precision.h; row++) {
  39325. for (col = 0; col < precision.w; col++) {
  39326. var square = [
  39327. base + col + row * rowLength,
  39328. base + (col + 1) + row * rowLength,
  39329. base + (col + 1) + (row + 1) * rowLength,
  39330. base + col + (row + 1) * rowLength
  39331. ];
  39332. indices.push(square[1]);
  39333. indices.push(square[2]);
  39334. indices.push(square[3]);
  39335. indices.push(square[0]);
  39336. indices.push(square[1]);
  39337. indices.push(square[3]);
  39338. }
  39339. }
  39340. // Position, normals and uvs
  39341. var position = BABYLON.Vector3.Zero();
  39342. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39343. for (row = 0; row <= precision.h; row++) {
  39344. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39345. for (col = 0; col <= precision.w; col++) {
  39346. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39347. position.y = 0;
  39348. positions.push(position.x, position.y, position.z);
  39349. normals.push(normal.x, normal.y, normal.z);
  39350. uvs.push(col / precision.w, row / precision.h);
  39351. }
  39352. }
  39353. }
  39354. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39355. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39356. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39357. }
  39358. }
  39359. // Result
  39360. var vertexData = new VertexData();
  39361. vertexData.indices = indices;
  39362. vertexData.positions = positions;
  39363. vertexData.normals = normals;
  39364. vertexData.uvs = uvs;
  39365. return vertexData;
  39366. };
  39367. /**
  39368. * Creates the VertexData of the Ground designed from a heightmap
  39369. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39370. * * width the width (x direction) of the ground
  39371. * * height the height (z direction) of the ground
  39372. * * subdivisions the number of subdivisions per side
  39373. * * minHeight the minimum altitude on the ground, optional, default 0
  39374. * * maxHeight the maximum altitude on the ground, optional default 1
  39375. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39376. * * buffer the array holding the image color data
  39377. * * bufferWidth the width of image
  39378. * * bufferHeight the height of image
  39379. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39380. * @returns the VertexData of the Ground designed from a heightmap
  39381. */
  39382. VertexData.CreateGroundFromHeightMap = function (options) {
  39383. var indices = [];
  39384. var positions = [];
  39385. var normals = [];
  39386. var uvs = [];
  39387. var row, col;
  39388. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39389. var alphaFilter = options.alphaFilter || 0.0;
  39390. // Vertices
  39391. for (row = 0; row <= options.subdivisions; row++) {
  39392. for (col = 0; col <= options.subdivisions; col++) {
  39393. 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));
  39394. // Compute height
  39395. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39396. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39397. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39398. var r = options.buffer[pos] / 255.0;
  39399. var g = options.buffer[pos + 1] / 255.0;
  39400. var b = options.buffer[pos + 2] / 255.0;
  39401. var a = options.buffer[pos + 3] / 255.0;
  39402. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39403. // If our alpha channel is not within our filter then we will assign a 'special' height
  39404. // Then when building the indices, we will ignore any vertex that is using the special height
  39405. if (a >= alphaFilter) {
  39406. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39407. }
  39408. else {
  39409. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39410. }
  39411. // Add vertex
  39412. positions.push(position.x, position.y, position.z);
  39413. normals.push(0, 0, 0);
  39414. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39415. }
  39416. }
  39417. // Indices
  39418. for (row = 0; row < options.subdivisions; row++) {
  39419. for (col = 0; col < options.subdivisions; col++) {
  39420. // Calculate Indices
  39421. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39422. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39423. var idx3 = (col + row * (options.subdivisions + 1));
  39424. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39425. // Check that all indices are visible (based on our special height)
  39426. // Only display the vertex if all Indices are visible
  39427. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39428. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39429. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39430. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39431. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39432. indices.push(idx1);
  39433. indices.push(idx2);
  39434. indices.push(idx3);
  39435. }
  39436. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39437. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39438. indices.push(idx4);
  39439. indices.push(idx1);
  39440. indices.push(idx3);
  39441. }
  39442. }
  39443. }
  39444. // Normals
  39445. VertexData.ComputeNormals(positions, indices, normals);
  39446. // Result
  39447. var vertexData = new VertexData();
  39448. vertexData.indices = indices;
  39449. vertexData.positions = positions;
  39450. vertexData.normals = normals;
  39451. vertexData.uvs = uvs;
  39452. return vertexData;
  39453. };
  39454. /**
  39455. * Creates the VertexData for a Plane
  39456. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39457. * * size sets the width and height of the plane to the value of size, optional default 1
  39458. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39459. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39460. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39461. * * 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)
  39462. * * 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)
  39463. * @returns the VertexData of the box
  39464. */
  39465. VertexData.CreatePlane = function (options) {
  39466. var indices = [];
  39467. var positions = [];
  39468. var normals = [];
  39469. var uvs = [];
  39470. var width = options.width || options.size || 1;
  39471. var height = options.height || options.size || 1;
  39472. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39473. // Vertices
  39474. var halfWidth = width / 2.0;
  39475. var halfHeight = height / 2.0;
  39476. positions.push(-halfWidth, -halfHeight, 0);
  39477. normals.push(0, 0, -1.0);
  39478. uvs.push(0.0, 0.0);
  39479. positions.push(halfWidth, -halfHeight, 0);
  39480. normals.push(0, 0, -1.0);
  39481. uvs.push(1.0, 0.0);
  39482. positions.push(halfWidth, halfHeight, 0);
  39483. normals.push(0, 0, -1.0);
  39484. uvs.push(1.0, 1.0);
  39485. positions.push(-halfWidth, halfHeight, 0);
  39486. normals.push(0, 0, -1.0);
  39487. uvs.push(0.0, 1.0);
  39488. // Indices
  39489. indices.push(0);
  39490. indices.push(1);
  39491. indices.push(2);
  39492. indices.push(0);
  39493. indices.push(2);
  39494. indices.push(3);
  39495. // Sides
  39496. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39497. // Result
  39498. var vertexData = new VertexData();
  39499. vertexData.indices = indices;
  39500. vertexData.positions = positions;
  39501. vertexData.normals = normals;
  39502. vertexData.uvs = uvs;
  39503. return vertexData;
  39504. };
  39505. /**
  39506. * Creates the VertexData of the Disc or regular Polygon
  39507. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39508. * * radius the radius of the disc, optional default 0.5
  39509. * * tessellation the number of polygon sides, optional, default 64
  39510. * * 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
  39511. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39512. * * 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)
  39513. * * 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)
  39514. * @returns the VertexData of the box
  39515. */
  39516. VertexData.CreateDisc = function (options) {
  39517. var positions = new Array();
  39518. var indices = new Array();
  39519. var normals = new Array();
  39520. var uvs = new Array();
  39521. var radius = options.radius || 0.5;
  39522. var tessellation = options.tessellation || 64;
  39523. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39524. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39525. // positions and uvs
  39526. positions.push(0, 0, 0); // disc center first
  39527. uvs.push(0.5, 0.5);
  39528. var theta = Math.PI * 2 * arc;
  39529. var step = theta / tessellation;
  39530. for (var a = 0; a < theta; a += step) {
  39531. var x = Math.cos(a);
  39532. var y = Math.sin(a);
  39533. var u = (x + 1) / 2;
  39534. var v = (1 - y) / 2;
  39535. positions.push(radius * x, radius * y, 0);
  39536. uvs.push(u, v);
  39537. }
  39538. if (arc === 1) {
  39539. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39540. uvs.push(uvs[2], uvs[3]);
  39541. }
  39542. //indices
  39543. var vertexNb = positions.length / 3;
  39544. for (var i = 1; i < vertexNb - 1; i++) {
  39545. indices.push(i + 1, 0, i);
  39546. }
  39547. // result
  39548. VertexData.ComputeNormals(positions, indices, normals);
  39549. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39550. var vertexData = new VertexData();
  39551. vertexData.indices = indices;
  39552. vertexData.positions = positions;
  39553. vertexData.normals = normals;
  39554. vertexData.uvs = uvs;
  39555. return vertexData;
  39556. };
  39557. /**
  39558. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39559. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39560. * @param polygon a mesh built from polygonTriangulation.build()
  39561. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39562. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39563. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39564. * @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)
  39565. * @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)
  39566. * @returns the VertexData of the Polygon
  39567. */
  39568. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39569. var faceUV = fUV || new Array(3);
  39570. var faceColors = fColors;
  39571. var colors = [];
  39572. // default face colors and UV if undefined
  39573. for (var f = 0; f < 3; f++) {
  39574. if (faceUV[f] === undefined) {
  39575. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39576. }
  39577. if (faceColors && faceColors[f] === undefined) {
  39578. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39579. }
  39580. }
  39581. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39582. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39583. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39584. var indices = polygon.getIndices();
  39585. // set face colours and textures
  39586. var idx = 0;
  39587. var face = 0;
  39588. for (var index = 0; index < normals.length; index += 3) {
  39589. //Edge Face no. 1
  39590. if (Math.abs(normals[index + 1]) < 0.001) {
  39591. face = 1;
  39592. }
  39593. //Top Face no. 0
  39594. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39595. face = 0;
  39596. }
  39597. //Bottom Face no. 2
  39598. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39599. face = 2;
  39600. }
  39601. idx = index / 3;
  39602. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39603. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39604. if (faceColors) {
  39605. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39606. }
  39607. }
  39608. // sides
  39609. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39610. // Result
  39611. var vertexData = new VertexData();
  39612. vertexData.indices = indices;
  39613. vertexData.positions = positions;
  39614. vertexData.normals = normals;
  39615. vertexData.uvs = uvs;
  39616. if (faceColors) {
  39617. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39618. vertexData.colors = totalColors;
  39619. }
  39620. return vertexData;
  39621. };
  39622. /**
  39623. * Creates the VertexData of the IcoSphere
  39624. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39625. * * radius the radius of the IcoSphere, optional default 1
  39626. * * radiusX allows stretching in the x direction, optional, default radius
  39627. * * radiusY allows stretching in the y direction, optional, default radius
  39628. * * radiusZ allows stretching in the z direction, optional, default radius
  39629. * * flat when true creates a flat shaded mesh, optional, default true
  39630. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39631. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39632. * * 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)
  39633. * * 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)
  39634. * @returns the VertexData of the IcoSphere
  39635. */
  39636. VertexData.CreateIcoSphere = function (options) {
  39637. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39638. var radius = options.radius || 1;
  39639. var flat = (options.flat === undefined) ? true : options.flat;
  39640. var subdivisions = options.subdivisions || 4;
  39641. var radiusX = options.radiusX || radius;
  39642. var radiusY = options.radiusY || radius;
  39643. var radiusZ = options.radiusZ || radius;
  39644. var t = (1 + Math.sqrt(5)) / 2;
  39645. // 12 vertex x,y,z
  39646. var ico_vertices = [
  39647. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39648. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39649. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39650. ];
  39651. // index of 3 vertex makes a face of icopshere
  39652. var ico_indices = [
  39653. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39654. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39655. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39656. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39657. ];
  39658. // vertex for uv have aliased position, not for UV
  39659. var vertices_unalias_id = [
  39660. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39661. // vertex alias
  39662. 0,
  39663. 2,
  39664. 3,
  39665. 3,
  39666. 3,
  39667. 4,
  39668. 7,
  39669. 8,
  39670. 9,
  39671. 9,
  39672. 10,
  39673. 11 // 23: B + 12
  39674. ];
  39675. // uv as integer step (not pixels !)
  39676. var ico_vertexuv = [
  39677. 5, 1, 3, 1, 6, 4, 0, 0,
  39678. 5, 3, 4, 2, 2, 2, 4, 0,
  39679. 2, 0, 1, 1, 6, 0, 6, 2,
  39680. // vertex alias (for same vertex on different faces)
  39681. 0, 4,
  39682. 3, 3,
  39683. 4, 4,
  39684. 3, 1,
  39685. 4, 2,
  39686. 4, 4,
  39687. 0, 2,
  39688. 1, 1,
  39689. 2, 2,
  39690. 3, 3,
  39691. 1, 3,
  39692. 2, 4 // 23: B + 12
  39693. ];
  39694. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39695. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39696. // First island of uv mapping
  39697. // v = 4h 3+ 2
  39698. // v = 3h 9+ 4
  39699. // v = 2h 9+ 5 B
  39700. // v = 1h 9 1 0
  39701. // v = 0h 3 8 7 A
  39702. // u = 0 1 2 3 4 5 6 *a
  39703. // Second island of uv mapping
  39704. // v = 4h 0+ B+ 4+
  39705. // v = 3h A+ 2+
  39706. // v = 2h 7+ 6 3+
  39707. // v = 1h 8+ 3+
  39708. // v = 0h
  39709. // u = 0 1 2 3 4 5 6 *a
  39710. // Face layout on texture UV mapping
  39711. // ============
  39712. // \ 4 /\ 16 / ======
  39713. // \ / \ / /\ 11 /
  39714. // \/ 7 \/ / \ /
  39715. // ======= / 10 \/
  39716. // /\ 17 /\ =======
  39717. // / \ / \ \ 15 /\
  39718. // / 8 \/ 12 \ \ / \
  39719. // ============ \/ 6 \
  39720. // \ 18 /\ ============
  39721. // \ / \ \ 5 /\ 0 /
  39722. // \/ 13 \ \ / \ /
  39723. // ======= \/ 1 \/
  39724. // =============
  39725. // /\ 19 /\ 2 /\
  39726. // / \ / \ / \
  39727. // / 14 \/ 9 \/ 3 \
  39728. // ===================
  39729. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39730. var ustep = 138 / 1024;
  39731. var vstep = 239 / 1024;
  39732. var uoffset = 60 / 1024;
  39733. var voffset = 26 / 1024;
  39734. // Second island should have margin, not to touch the first island
  39735. // avoid any borderline artefact in pixel rounding
  39736. var island_u_offset = -40 / 1024;
  39737. var island_v_offset = +20 / 1024;
  39738. // face is either island 0 or 1 :
  39739. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39740. var island = [
  39741. 0, 0, 0, 0, 1,
  39742. 0, 0, 1, 1, 0,
  39743. 0, 0, 1, 1, 0,
  39744. 0, 1, 1, 1, 0 // 15 - 19
  39745. ];
  39746. var indices = new Array();
  39747. var positions = new Array();
  39748. var normals = new Array();
  39749. var uvs = new Array();
  39750. var current_indice = 0;
  39751. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39752. var face_vertex_pos = new Array(3);
  39753. var face_vertex_uv = new Array(3);
  39754. var v012;
  39755. for (v012 = 0; v012 < 3; v012++) {
  39756. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39757. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39758. }
  39759. // create all with normals
  39760. for (var face = 0; face < 20; face++) {
  39761. // 3 vertex per face
  39762. for (v012 = 0; v012 < 3; v012++) {
  39763. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39764. var v_id = ico_indices[3 * face + v012];
  39765. // vertex have 3D position (x,y,z)
  39766. 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]);
  39767. // Normalize to get normal, then scale to radius
  39768. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39769. // uv Coordinates from vertex ID
  39770. 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);
  39771. }
  39772. // Subdivide the face (interpolate pos, norm, uv)
  39773. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39774. // - norm is linear interpolation of vertex corner normal
  39775. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39776. // - uv is linear interpolation
  39777. //
  39778. // Topology is as below for sub-divide by 2
  39779. // vertex shown as v0,v1,v2
  39780. // interp index is i1 to progress in range [v0,v1[
  39781. // interp index is i2 to progress in range [v0,v2[
  39782. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39783. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39784. //
  39785. //
  39786. // i2 v2
  39787. // ^ ^
  39788. // / / \
  39789. // / / \
  39790. // / / \
  39791. // / / (0,1) \
  39792. // / #---------\
  39793. // / / \ (0,0)'/ \
  39794. // / / \ / \
  39795. // / / \ / \
  39796. // / / (0,0) \ / (1,0) \
  39797. // / #---------#---------\
  39798. // v0 v1
  39799. //
  39800. // --------------------> i1
  39801. //
  39802. // interp of (i1,i2):
  39803. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39804. // along i1 : lerp(x0,x1, i1/(S-i2))
  39805. //
  39806. // centroid of triangle is needed to get help normal computation
  39807. // (c1,c2) are used for centroid location
  39808. var interp_vertex = function (i1, i2, c1, c2) {
  39809. // vertex is interpolated from
  39810. // - face_vertex_pos[0..2]
  39811. // - face_vertex_uv[0..2]
  39812. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39813. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39814. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39815. pos_interp.normalize();
  39816. var vertex_normal;
  39817. if (flat) {
  39818. // in flat mode, recalculate normal as face centroid normal
  39819. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39820. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39821. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39822. }
  39823. else {
  39824. // in smooth mode, recalculate normal from each single vertex position
  39825. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39826. }
  39827. // Vertex normal need correction due to X,Y,Z radius scaling
  39828. vertex_normal.x /= radiusX;
  39829. vertex_normal.y /= radiusY;
  39830. vertex_normal.z /= radiusZ;
  39831. vertex_normal.normalize();
  39832. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39833. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39834. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39835. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39836. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39837. uvs.push(uv_interp.x, uv_interp.y);
  39838. // push each vertex has member of a face
  39839. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39840. indices.push(current_indice);
  39841. current_indice++;
  39842. };
  39843. for (var i2 = 0; i2 < subdivisions; i2++) {
  39844. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39845. // face : (i1,i2) for /\ :
  39846. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39847. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39848. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39849. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39850. if (i1 + i2 + 1 < subdivisions) {
  39851. // face : (i1,i2)' for \/ :
  39852. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39853. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39854. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39855. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39856. }
  39857. }
  39858. }
  39859. }
  39860. // Sides
  39861. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39862. // Result
  39863. var vertexData = new VertexData();
  39864. vertexData.indices = indices;
  39865. vertexData.positions = positions;
  39866. vertexData.normals = normals;
  39867. vertexData.uvs = uvs;
  39868. return vertexData;
  39869. };
  39870. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39871. /**
  39872. * Creates the VertexData for a Polyhedron
  39873. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39874. * * type provided types are:
  39875. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39876. * * 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)
  39877. * * size the size of the IcoSphere, optional default 1
  39878. * * sizeX allows stretching in the x direction, optional, default size
  39879. * * sizeY allows stretching in the y direction, optional, default size
  39880. * * sizeZ allows stretching in the z direction, optional, default size
  39881. * * 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
  39882. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39883. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39884. * * flat when true creates a flat shaded mesh, optional, default true
  39885. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39886. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39887. * * 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)
  39888. * * 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)
  39889. * @returns the VertexData of the Polyhedron
  39890. */
  39891. VertexData.CreatePolyhedron = function (options) {
  39892. // provided polyhedron types :
  39893. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39894. // 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)
  39895. var polyhedra = [];
  39896. 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]] };
  39897. 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]] };
  39898. polyhedra[2] = {
  39899. 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]],
  39900. 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]]
  39901. };
  39902. polyhedra[3] = {
  39903. 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]],
  39904. 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]]
  39905. };
  39906. polyhedra[4] = {
  39907. 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]],
  39908. 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]]
  39909. };
  39910. 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]] };
  39911. 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]] };
  39912. 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]] };
  39913. 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]] };
  39914. 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]] };
  39915. 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]] };
  39916. 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]] };
  39917. 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]] };
  39918. 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]] };
  39919. polyhedra[14] = {
  39920. 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]],
  39921. 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]]
  39922. };
  39923. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39924. var size = options.size;
  39925. var sizeX = options.sizeX || size || 1;
  39926. var sizeY = options.sizeY || size || 1;
  39927. var sizeZ = options.sizeZ || size || 1;
  39928. var data = options.custom || polyhedra[type];
  39929. var nbfaces = data.face.length;
  39930. var faceUV = options.faceUV || new Array(nbfaces);
  39931. var faceColors = options.faceColors;
  39932. var flat = (options.flat === undefined) ? true : options.flat;
  39933. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39934. var positions = new Array();
  39935. var indices = new Array();
  39936. var normals = new Array();
  39937. var uvs = new Array();
  39938. var colors = new Array();
  39939. var index = 0;
  39940. var faceIdx = 0; // face cursor in the array "indexes"
  39941. var indexes = new Array();
  39942. var i = 0;
  39943. var f = 0;
  39944. var u, v, ang, x, y, tmp;
  39945. // default face colors and UV if undefined
  39946. if (flat) {
  39947. for (f = 0; f < nbfaces; f++) {
  39948. if (faceColors && faceColors[f] === undefined) {
  39949. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39950. }
  39951. if (faceUV && faceUV[f] === undefined) {
  39952. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39953. }
  39954. }
  39955. }
  39956. if (!flat) {
  39957. for (i = 0; i < data.vertex.length; i++) {
  39958. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39959. uvs.push(0, 0);
  39960. }
  39961. for (f = 0; f < nbfaces; f++) {
  39962. for (i = 0; i < data.face[f].length - 2; i++) {
  39963. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39964. }
  39965. }
  39966. }
  39967. else {
  39968. for (f = 0; f < nbfaces; f++) {
  39969. var fl = data.face[f].length; // number of vertices of the current face
  39970. ang = 2 * Math.PI / fl;
  39971. x = 0.5 * Math.tan(ang / 2);
  39972. y = 0.5;
  39973. // positions, uvs, colors
  39974. for (i = 0; i < fl; i++) {
  39975. // positions
  39976. 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);
  39977. indexes.push(index);
  39978. index++;
  39979. // uvs
  39980. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39981. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39982. uvs.push(u, v);
  39983. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39984. y = x * Math.sin(ang) + y * Math.cos(ang);
  39985. x = tmp;
  39986. // colors
  39987. if (faceColors) {
  39988. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39989. }
  39990. }
  39991. // indices from indexes
  39992. for (i = 0; i < fl - 2; i++) {
  39993. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39994. }
  39995. faceIdx += fl;
  39996. }
  39997. }
  39998. VertexData.ComputeNormals(positions, indices, normals);
  39999. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40000. var vertexData = new VertexData();
  40001. vertexData.positions = positions;
  40002. vertexData.indices = indices;
  40003. vertexData.normals = normals;
  40004. vertexData.uvs = uvs;
  40005. if (faceColors && flat) {
  40006. vertexData.colors = colors;
  40007. }
  40008. return vertexData;
  40009. };
  40010. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40011. /**
  40012. * Creates the VertexData for a TorusKnot
  40013. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  40014. * * radius the radius of the torus knot, optional, default 2
  40015. * * tube the thickness of the tube, optional, default 0.5
  40016. * * radialSegments the number of sides on each tube segments, optional, default 32
  40017. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  40018. * * p the number of windings around the z axis, optional, default 2
  40019. * * q the number of windings around the x axis, optional, default 3
  40020. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40021. * * 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)
  40022. * * 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)
  40023. * @returns the VertexData of the Torus Knot
  40024. */
  40025. VertexData.CreateTorusKnot = function (options) {
  40026. var indices = new Array();
  40027. var positions = new Array();
  40028. var normals = new Array();
  40029. var uvs = new Array();
  40030. var radius = options.radius || 2;
  40031. var tube = options.tube || 0.5;
  40032. var radialSegments = options.radialSegments || 32;
  40033. var tubularSegments = options.tubularSegments || 32;
  40034. var p = options.p || 2;
  40035. var q = options.q || 3;
  40036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40037. // Helper
  40038. var getPos = function (angle) {
  40039. var cu = Math.cos(angle);
  40040. var su = Math.sin(angle);
  40041. var quOverP = q / p * angle;
  40042. var cs = Math.cos(quOverP);
  40043. var tx = radius * (2 + cs) * 0.5 * cu;
  40044. var ty = radius * (2 + cs) * su * 0.5;
  40045. var tz = radius * Math.sin(quOverP) * 0.5;
  40046. return new BABYLON.Vector3(tx, ty, tz);
  40047. };
  40048. // Vertices
  40049. var i;
  40050. var j;
  40051. for (i = 0; i <= radialSegments; i++) {
  40052. var modI = i % radialSegments;
  40053. var u = modI / radialSegments * 2 * p * Math.PI;
  40054. var p1 = getPos(u);
  40055. var p2 = getPos(u + 0.01);
  40056. var tang = p2.subtract(p1);
  40057. var n = p2.add(p1);
  40058. var bitan = BABYLON.Vector3.Cross(tang, n);
  40059. n = BABYLON.Vector3.Cross(bitan, tang);
  40060. bitan.normalize();
  40061. n.normalize();
  40062. for (j = 0; j < tubularSegments; j++) {
  40063. var modJ = j % tubularSegments;
  40064. var v = modJ / tubularSegments * 2 * Math.PI;
  40065. var cx = -tube * Math.cos(v);
  40066. var cy = tube * Math.sin(v);
  40067. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40068. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40069. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40070. uvs.push(i / radialSegments);
  40071. uvs.push(j / tubularSegments);
  40072. }
  40073. }
  40074. for (i = 0; i < radialSegments; i++) {
  40075. for (j = 0; j < tubularSegments; j++) {
  40076. var jNext = (j + 1) % tubularSegments;
  40077. var a = i * tubularSegments + j;
  40078. var b = (i + 1) * tubularSegments + j;
  40079. var c = (i + 1) * tubularSegments + jNext;
  40080. var d = i * tubularSegments + jNext;
  40081. indices.push(d);
  40082. indices.push(b);
  40083. indices.push(a);
  40084. indices.push(d);
  40085. indices.push(c);
  40086. indices.push(b);
  40087. }
  40088. }
  40089. // Normals
  40090. VertexData.ComputeNormals(positions, indices, normals);
  40091. // Sides
  40092. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40093. // Result
  40094. var vertexData = new VertexData();
  40095. vertexData.indices = indices;
  40096. vertexData.positions = positions;
  40097. vertexData.normals = normals;
  40098. vertexData.uvs = uvs;
  40099. return vertexData;
  40100. };
  40101. // Tools
  40102. /**
  40103. * Compute normals for given positions and indices
  40104. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40105. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40106. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40107. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40108. * * facetNormals : optional array of facet normals (vector3)
  40109. * * facetPositions : optional array of facet positions (vector3)
  40110. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40111. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40112. * * bInfo : optional bounding info, required for facetPartitioning computation
  40113. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40114. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40115. * * useRightHandedSystem: optional boolean to for right handed system computation
  40116. * * depthSort : optional boolean to enable the facet depth sort computation
  40117. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40118. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40119. */
  40120. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40121. // temporary scalar variables
  40122. var index = 0; // facet index
  40123. var p1p2x = 0.0; // p1p2 vector x coordinate
  40124. var p1p2y = 0.0; // p1p2 vector y coordinate
  40125. var p1p2z = 0.0; // p1p2 vector z coordinate
  40126. var p3p2x = 0.0; // p3p2 vector x coordinate
  40127. var p3p2y = 0.0; // p3p2 vector y coordinate
  40128. var p3p2z = 0.0; // p3p2 vector z coordinate
  40129. var faceNormalx = 0.0; // facet normal x coordinate
  40130. var faceNormaly = 0.0; // facet normal y coordinate
  40131. var faceNormalz = 0.0; // facet normal z coordinate
  40132. var length = 0.0; // facet normal length before normalization
  40133. var v1x = 0; // vector1 x index in the positions array
  40134. var v1y = 0; // vector1 y index in the positions array
  40135. var v1z = 0; // vector1 z index in the positions array
  40136. var v2x = 0; // vector2 x index in the positions array
  40137. var v2y = 0; // vector2 y index in the positions array
  40138. var v2z = 0; // vector2 z index in the positions array
  40139. var v3x = 0; // vector3 x index in the positions array
  40140. var v3y = 0; // vector3 y index in the positions array
  40141. var v3z = 0; // vector3 z index in the positions array
  40142. var computeFacetNormals = false;
  40143. var computeFacetPositions = false;
  40144. var computeFacetPartitioning = false;
  40145. var computeDepthSort = false;
  40146. var faceNormalSign = 1;
  40147. var ratio = 0;
  40148. var distanceTo = null;
  40149. if (options) {
  40150. computeFacetNormals = (options.facetNormals) ? true : false;
  40151. computeFacetPositions = (options.facetPositions) ? true : false;
  40152. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40153. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40154. ratio = options.ratio || 0;
  40155. computeDepthSort = (options.depthSort) ? true : false;
  40156. distanceTo = (options.distanceTo);
  40157. if (computeDepthSort) {
  40158. if (distanceTo === undefined) {
  40159. distanceTo = BABYLON.Vector3.Zero();
  40160. }
  40161. var depthSortedFacets = options.depthSortedFacets;
  40162. }
  40163. }
  40164. // facetPartitioning reinit if needed
  40165. var xSubRatio = 0;
  40166. var ySubRatio = 0;
  40167. var zSubRatio = 0;
  40168. var subSq = 0;
  40169. if (computeFacetPartitioning && options && options.bbSize) {
  40170. var ox = 0; // X partitioning index for facet position
  40171. var oy = 0; // Y partinioning index for facet position
  40172. var oz = 0; // Z partinioning index for facet position
  40173. var b1x = 0; // X partitioning index for facet v1 vertex
  40174. var b1y = 0; // Y partitioning index for facet v1 vertex
  40175. var b1z = 0; // z partitioning index for facet v1 vertex
  40176. var b2x = 0; // X partitioning index for facet v2 vertex
  40177. var b2y = 0; // Y partitioning index for facet v2 vertex
  40178. var b2z = 0; // Z partitioning index for facet v2 vertex
  40179. var b3x = 0; // X partitioning index for facet v3 vertex
  40180. var b3y = 0; // Y partitioning index for facet v3 vertex
  40181. var b3z = 0; // Z partitioning index for facet v3 vertex
  40182. var block_idx_o = 0; // facet barycenter block index
  40183. var block_idx_v1 = 0; // v1 vertex block index
  40184. var block_idx_v2 = 0; // v2 vertex block index
  40185. var block_idx_v3 = 0; // v3 vertex block index
  40186. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40187. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40188. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40189. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40190. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40191. subSq = options.subDiv.max * options.subDiv.max;
  40192. options.facetPartitioning.length = 0;
  40193. }
  40194. // reset the normals
  40195. for (index = 0; index < positions.length; index++) {
  40196. normals[index] = 0.0;
  40197. }
  40198. // Loop : 1 indice triplet = 1 facet
  40199. var nbFaces = (indices.length / 3) | 0;
  40200. for (index = 0; index < nbFaces; index++) {
  40201. // get the indexes of the coordinates of each vertex of the facet
  40202. v1x = indices[index * 3] * 3;
  40203. v1y = v1x + 1;
  40204. v1z = v1x + 2;
  40205. v2x = indices[index * 3 + 1] * 3;
  40206. v2y = v2x + 1;
  40207. v2z = v2x + 2;
  40208. v3x = indices[index * 3 + 2] * 3;
  40209. v3y = v3x + 1;
  40210. v3z = v3x + 2;
  40211. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40212. p1p2y = positions[v1y] - positions[v2y];
  40213. p1p2z = positions[v1z] - positions[v2z];
  40214. p3p2x = positions[v3x] - positions[v2x];
  40215. p3p2y = positions[v3y] - positions[v2y];
  40216. p3p2z = positions[v3z] - positions[v2z];
  40217. // compute the face normal with the cross product
  40218. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40219. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40220. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40221. // normalize this normal and store it in the array facetData
  40222. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40223. length = (length === 0) ? 1.0 : length;
  40224. faceNormalx /= length;
  40225. faceNormaly /= length;
  40226. faceNormalz /= length;
  40227. if (computeFacetNormals && options) {
  40228. options.facetNormals[index].x = faceNormalx;
  40229. options.facetNormals[index].y = faceNormaly;
  40230. options.facetNormals[index].z = faceNormalz;
  40231. }
  40232. if (computeFacetPositions && options) {
  40233. // compute and the facet barycenter coordinates in the array facetPositions
  40234. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40235. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40236. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40237. }
  40238. if (computeFacetPartitioning && options) {
  40239. // store the facet indexes in arrays in the main facetPartitioning array :
  40240. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40241. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40242. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40243. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40244. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40245. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40246. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40247. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40248. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40249. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40250. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40251. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40252. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40253. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40254. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40255. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40256. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40257. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40258. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40259. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40260. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40261. // push each facet index in each block containing the vertex
  40262. options.facetPartitioning[block_idx_v1].push(index);
  40263. if (block_idx_v2 != block_idx_v1) {
  40264. options.facetPartitioning[block_idx_v2].push(index);
  40265. }
  40266. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40267. options.facetPartitioning[block_idx_v3].push(index);
  40268. }
  40269. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40270. options.facetPartitioning[block_idx_o].push(index);
  40271. }
  40272. }
  40273. if (computeDepthSort && options && options.facetPositions) {
  40274. var dsf = depthSortedFacets[index];
  40275. dsf.ind = index * 3;
  40276. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40277. }
  40278. // compute the normals anyway
  40279. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40280. normals[v1y] += faceNormaly;
  40281. normals[v1z] += faceNormalz;
  40282. normals[v2x] += faceNormalx;
  40283. normals[v2y] += faceNormaly;
  40284. normals[v2z] += faceNormalz;
  40285. normals[v3x] += faceNormalx;
  40286. normals[v3y] += faceNormaly;
  40287. normals[v3z] += faceNormalz;
  40288. }
  40289. // last normalization of each normal
  40290. for (index = 0; index < normals.length / 3; index++) {
  40291. faceNormalx = normals[index * 3];
  40292. faceNormaly = normals[index * 3 + 1];
  40293. faceNormalz = normals[index * 3 + 2];
  40294. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40295. length = (length === 0) ? 1.0 : length;
  40296. faceNormalx /= length;
  40297. faceNormaly /= length;
  40298. faceNormalz /= length;
  40299. normals[index * 3] = faceNormalx;
  40300. normals[index * 3 + 1] = faceNormaly;
  40301. normals[index * 3 + 2] = faceNormalz;
  40302. }
  40303. };
  40304. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40305. var li = indices.length;
  40306. var ln = normals.length;
  40307. var i;
  40308. var n;
  40309. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40310. switch (sideOrientation) {
  40311. case BABYLON.Mesh.FRONTSIDE:
  40312. // nothing changed
  40313. break;
  40314. case BABYLON.Mesh.BACKSIDE:
  40315. var tmp;
  40316. // indices
  40317. for (i = 0; i < li; i += 3) {
  40318. tmp = indices[i];
  40319. indices[i] = indices[i + 2];
  40320. indices[i + 2] = tmp;
  40321. }
  40322. // normals
  40323. for (n = 0; n < ln; n++) {
  40324. normals[n] = -normals[n];
  40325. }
  40326. break;
  40327. case BABYLON.Mesh.DOUBLESIDE:
  40328. // positions
  40329. var lp = positions.length;
  40330. var l = lp / 3;
  40331. for (var p = 0; p < lp; p++) {
  40332. positions[lp + p] = positions[p];
  40333. }
  40334. // indices
  40335. for (i = 0; i < li; i += 3) {
  40336. indices[i + li] = indices[i + 2] + l;
  40337. indices[i + 1 + li] = indices[i + 1] + l;
  40338. indices[i + 2 + li] = indices[i] + l;
  40339. }
  40340. // normals
  40341. for (n = 0; n < ln; n++) {
  40342. normals[ln + n] = -normals[n];
  40343. }
  40344. // uvs
  40345. var lu = uvs.length;
  40346. var u = 0;
  40347. for (u = 0; u < lu; u++) {
  40348. uvs[u + lu] = uvs[u];
  40349. }
  40350. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40351. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40352. u = 0;
  40353. for (i = 0; i < lu / 2; i++) {
  40354. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40355. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40356. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40357. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40358. u += 2;
  40359. }
  40360. break;
  40361. }
  40362. };
  40363. /**
  40364. * Applies VertexData created from the imported parameters to the geometry
  40365. * @param parsedVertexData the parsed data from an imported file
  40366. * @param geometry the geometry to apply the VertexData to
  40367. */
  40368. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40369. var vertexData = new VertexData();
  40370. // positions
  40371. var positions = parsedVertexData.positions;
  40372. if (positions) {
  40373. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40374. }
  40375. // normals
  40376. var normals = parsedVertexData.normals;
  40377. if (normals) {
  40378. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40379. }
  40380. // tangents
  40381. var tangents = parsedVertexData.tangents;
  40382. if (tangents) {
  40383. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40384. }
  40385. // uvs
  40386. var uvs = parsedVertexData.uvs;
  40387. if (uvs) {
  40388. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40389. }
  40390. // uv2s
  40391. var uv2s = parsedVertexData.uv2s;
  40392. if (uv2s) {
  40393. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40394. }
  40395. // uv3s
  40396. var uv3s = parsedVertexData.uv3s;
  40397. if (uv3s) {
  40398. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40399. }
  40400. // uv4s
  40401. var uv4s = parsedVertexData.uv4s;
  40402. if (uv4s) {
  40403. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40404. }
  40405. // uv5s
  40406. var uv5s = parsedVertexData.uv5s;
  40407. if (uv5s) {
  40408. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40409. }
  40410. // uv6s
  40411. var uv6s = parsedVertexData.uv6s;
  40412. if (uv6s) {
  40413. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40414. }
  40415. // colors
  40416. var colors = parsedVertexData.colors;
  40417. if (colors) {
  40418. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40419. }
  40420. // matricesIndices
  40421. var matricesIndices = parsedVertexData.matricesIndices;
  40422. if (matricesIndices) {
  40423. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40424. }
  40425. // matricesWeights
  40426. var matricesWeights = parsedVertexData.matricesWeights;
  40427. if (matricesWeights) {
  40428. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40429. }
  40430. // indices
  40431. var indices = parsedVertexData.indices;
  40432. if (indices) {
  40433. vertexData.indices = indices;
  40434. }
  40435. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40436. };
  40437. return VertexData;
  40438. }());
  40439. BABYLON.VertexData = VertexData;
  40440. })(BABYLON || (BABYLON = {}));
  40441. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40442. var BABYLON;
  40443. (function (BABYLON) {
  40444. /**
  40445. * Class used to store geometry data (vertex buffers + index buffer)
  40446. */
  40447. var Geometry = /** @class */ (function () {
  40448. /**
  40449. * Creates a new geometry
  40450. * @param id defines the unique ID
  40451. * @param scene defines the hosting scene
  40452. * @param vertexData defines the VertexData used to get geometry data
  40453. * @param updatable defines if geometry must be updatable (false by default)
  40454. * @param mesh defines the mesh that will be associated with the geometry
  40455. */
  40456. function Geometry(id, scene, vertexData, updatable, mesh) {
  40457. if (updatable === void 0) { updatable = false; }
  40458. if (mesh === void 0) { mesh = null; }
  40459. /**
  40460. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40461. */
  40462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40463. this._totalVertices = 0;
  40464. this._isDisposed = false;
  40465. this._indexBufferIsUpdatable = false;
  40466. this.id = id;
  40467. this._engine = scene.getEngine();
  40468. this._meshes = [];
  40469. this._scene = scene;
  40470. //Init vertex buffer cache
  40471. this._vertexBuffers = {};
  40472. this._indices = [];
  40473. this._updatable = updatable;
  40474. // vertexData
  40475. if (vertexData) {
  40476. this.setAllVerticesData(vertexData, updatable);
  40477. }
  40478. else {
  40479. this._totalVertices = 0;
  40480. this._indices = [];
  40481. }
  40482. if (this._engine.getCaps().vertexArrayObject) {
  40483. this._vertexArrayObjects = {};
  40484. }
  40485. // applyToMesh
  40486. if (mesh) {
  40487. this.applyToMesh(mesh);
  40488. mesh.computeWorldMatrix(true);
  40489. }
  40490. }
  40491. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40492. /**
  40493. * 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
  40494. */
  40495. get: function () {
  40496. return this._boundingBias;
  40497. },
  40498. /**
  40499. * 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
  40500. */
  40501. set: function (value) {
  40502. if (this._boundingBias) {
  40503. this._boundingBias.copyFrom(value);
  40504. }
  40505. else {
  40506. this._boundingBias = value.clone();
  40507. }
  40508. this._updateBoundingInfo(true, null);
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. /**
  40514. * Static function used to attach a new empty geometry to a mesh
  40515. * @param mesh defines the mesh to attach the geometry to
  40516. * @returns the new Geometry
  40517. */
  40518. Geometry.CreateGeometryForMesh = function (mesh) {
  40519. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40520. geometry.applyToMesh(mesh);
  40521. return geometry;
  40522. };
  40523. Object.defineProperty(Geometry.prototype, "extend", {
  40524. /**
  40525. * Gets the current extend of the geometry
  40526. */
  40527. get: function () {
  40528. return this._extend;
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. /**
  40534. * Gets the hosting scene
  40535. * @returns the hosting Scene
  40536. */
  40537. Geometry.prototype.getScene = function () {
  40538. return this._scene;
  40539. };
  40540. /**
  40541. * Gets the hosting engine
  40542. * @returns the hosting Engine
  40543. */
  40544. Geometry.prototype.getEngine = function () {
  40545. return this._engine;
  40546. };
  40547. /**
  40548. * Defines if the geometry is ready to use
  40549. * @returns true if the geometry is ready to be used
  40550. */
  40551. Geometry.prototype.isReady = function () {
  40552. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40553. };
  40554. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40555. /**
  40556. * Gets a value indicating that the geometry should not be serialized
  40557. */
  40558. get: function () {
  40559. for (var index = 0; index < this._meshes.length; index++) {
  40560. if (!this._meshes[index].doNotSerialize) {
  40561. return false;
  40562. }
  40563. }
  40564. return true;
  40565. },
  40566. enumerable: true,
  40567. configurable: true
  40568. });
  40569. /** @hidden */
  40570. Geometry.prototype._rebuild = function () {
  40571. if (this._vertexArrayObjects) {
  40572. this._vertexArrayObjects = {};
  40573. }
  40574. // Index buffer
  40575. if (this._meshes.length !== 0 && this._indices) {
  40576. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40577. }
  40578. // Vertex buffers
  40579. for (var key in this._vertexBuffers) {
  40580. var vertexBuffer = this._vertexBuffers[key];
  40581. vertexBuffer._rebuild();
  40582. }
  40583. };
  40584. /**
  40585. * Affects all geometry data in one call
  40586. * @param vertexData defines the geometry data
  40587. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40588. */
  40589. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40590. vertexData.applyToGeometry(this, updatable);
  40591. this.notifyUpdate();
  40592. };
  40593. /**
  40594. * Set specific vertex data
  40595. * @param kind defines the data kind (Position, normal, etc...)
  40596. * @param data defines the vertex data to use
  40597. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40598. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40599. */
  40600. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40601. if (updatable === void 0) { updatable = false; }
  40602. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40603. this.setVerticesBuffer(buffer);
  40604. };
  40605. /**
  40606. * Removes a specific vertex data
  40607. * @param kind defines the data kind (Position, normal, etc...)
  40608. */
  40609. Geometry.prototype.removeVerticesData = function (kind) {
  40610. if (this._vertexBuffers[kind]) {
  40611. this._vertexBuffers[kind].dispose();
  40612. delete this._vertexBuffers[kind];
  40613. }
  40614. };
  40615. /**
  40616. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40617. * @param buffer defines the vertex buffer to use
  40618. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40619. */
  40620. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40621. if (totalVertices === void 0) { totalVertices = null; }
  40622. var kind = buffer.getKind();
  40623. if (this._vertexBuffers[kind]) {
  40624. this._vertexBuffers[kind].dispose();
  40625. }
  40626. this._vertexBuffers[kind] = buffer;
  40627. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40628. var data = buffer.getData();
  40629. if (totalVertices != null) {
  40630. this._totalVertices = totalVertices;
  40631. }
  40632. else {
  40633. if (data != null) {
  40634. this._totalVertices = data.length / (buffer.byteStride / 4);
  40635. }
  40636. }
  40637. this._updateExtend(data);
  40638. this._resetPointsArrayCache();
  40639. var meshes = this._meshes;
  40640. var numOfMeshes = meshes.length;
  40641. for (var index = 0; index < numOfMeshes; index++) {
  40642. var mesh = meshes[index];
  40643. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40644. mesh._createGlobalSubMesh(false);
  40645. mesh.computeWorldMatrix(true);
  40646. }
  40647. }
  40648. this.notifyUpdate(kind);
  40649. if (this._vertexArrayObjects) {
  40650. this._disposeVertexArrayObjects();
  40651. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40652. }
  40653. };
  40654. /**
  40655. * Update a specific vertex buffer
  40656. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40657. * It will do nothing if the buffer is not updatable
  40658. * @param kind defines the data kind (Position, normal, etc...)
  40659. * @param data defines the data to use
  40660. * @param offset defines the offset in the target buffer where to store the data
  40661. * @param useBytes set to true if the offset is in bytes
  40662. */
  40663. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40664. if (useBytes === void 0) { useBytes = false; }
  40665. var vertexBuffer = this.getVertexBuffer(kind);
  40666. if (!vertexBuffer) {
  40667. return;
  40668. }
  40669. vertexBuffer.updateDirectly(data, offset, useBytes);
  40670. this.notifyUpdate(kind);
  40671. };
  40672. /**
  40673. * Update a specific vertex buffer
  40674. * This function will create a new buffer if the current one is not updatable
  40675. * @param kind defines the data kind (Position, normal, etc...)
  40676. * @param data defines the data to use
  40677. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40678. */
  40679. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40680. if (updateExtends === void 0) { updateExtends = false; }
  40681. var vertexBuffer = this.getVertexBuffer(kind);
  40682. if (!vertexBuffer) {
  40683. return;
  40684. }
  40685. vertexBuffer.update(data);
  40686. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40687. this._updateBoundingInfo(updateExtends, data);
  40688. }
  40689. this.notifyUpdate(kind);
  40690. };
  40691. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40692. if (updateExtends) {
  40693. this._updateExtend(data);
  40694. }
  40695. this._resetPointsArrayCache();
  40696. if (updateExtends) {
  40697. var meshes = this._meshes;
  40698. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  40699. var mesh = meshes_1[_i];
  40700. if (mesh._boundingInfo) {
  40701. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  40702. }
  40703. else {
  40704. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40705. }
  40706. var subMeshes = mesh.subMeshes;
  40707. for (var _a = 0, subMeshes_1 = subMeshes; _a < subMeshes_1.length; _a++) {
  40708. var subMesh = subMeshes_1[_a];
  40709. subMesh.refreshBoundingInfo();
  40710. }
  40711. }
  40712. }
  40713. };
  40714. /** @hidden */
  40715. Geometry.prototype._bind = function (effect, indexToBind) {
  40716. if (!effect) {
  40717. return;
  40718. }
  40719. if (indexToBind === undefined) {
  40720. indexToBind = this._indexBuffer;
  40721. }
  40722. var vbs = this.getVertexBuffers();
  40723. if (!vbs) {
  40724. return;
  40725. }
  40726. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40727. this._engine.bindBuffers(vbs, indexToBind, effect);
  40728. return;
  40729. }
  40730. // Using VAO
  40731. if (!this._vertexArrayObjects[effect.key]) {
  40732. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40733. }
  40734. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40735. };
  40736. /**
  40737. * Gets total number of vertices
  40738. * @returns the total number of vertices
  40739. */
  40740. Geometry.prototype.getTotalVertices = function () {
  40741. if (!this.isReady()) {
  40742. return 0;
  40743. }
  40744. return this._totalVertices;
  40745. };
  40746. /**
  40747. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40748. * @param kind defines the data kind (Position, normal, etc...)
  40749. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40750. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40751. * @returns a float array containing vertex data
  40752. */
  40753. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40754. var vertexBuffer = this.getVertexBuffer(kind);
  40755. if (!vertexBuffer) {
  40756. return null;
  40757. }
  40758. var data = vertexBuffer.getData();
  40759. if (!data) {
  40760. return null;
  40761. }
  40762. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40763. var count = this._totalVertices * vertexBuffer.getSize();
  40764. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40765. var copy_1 = [];
  40766. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  40767. return copy_1;
  40768. }
  40769. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40770. if (data instanceof Array) {
  40771. var offset = vertexBuffer.byteOffset / 4;
  40772. return BABYLON.Tools.Slice(data, offset, offset + count);
  40773. }
  40774. else if (data instanceof ArrayBuffer) {
  40775. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40776. }
  40777. else {
  40778. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40779. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40780. var result = new Float32Array(count);
  40781. var source = new Float32Array(data.buffer, offset, count);
  40782. result.set(source);
  40783. return result;
  40784. }
  40785. return new Float32Array(data.buffer, offset, count);
  40786. }
  40787. }
  40788. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40789. return BABYLON.Tools.Slice(data);
  40790. }
  40791. return data;
  40792. };
  40793. /**
  40794. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40795. * @param kind defines the data kind (Position, normal, etc...)
  40796. * @returns true if the vertex buffer with the specified kind is updatable
  40797. */
  40798. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40799. var vb = this._vertexBuffers[kind];
  40800. if (!vb) {
  40801. return false;
  40802. }
  40803. return vb.isUpdatable();
  40804. };
  40805. /**
  40806. * Gets a specific vertex buffer
  40807. * @param kind defines the data kind (Position, normal, etc...)
  40808. * @returns a VertexBuffer
  40809. */
  40810. Geometry.prototype.getVertexBuffer = function (kind) {
  40811. if (!this.isReady()) {
  40812. return null;
  40813. }
  40814. return this._vertexBuffers[kind];
  40815. };
  40816. /**
  40817. * Returns all vertex buffers
  40818. * @return an object holding all vertex buffers indexed by kind
  40819. */
  40820. Geometry.prototype.getVertexBuffers = function () {
  40821. if (!this.isReady()) {
  40822. return null;
  40823. }
  40824. return this._vertexBuffers;
  40825. };
  40826. /**
  40827. * Gets a boolean indicating if specific vertex buffer is present
  40828. * @param kind defines the data kind (Position, normal, etc...)
  40829. * @returns true if data is present
  40830. */
  40831. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40832. if (!this._vertexBuffers) {
  40833. if (this._delayInfo) {
  40834. return this._delayInfo.indexOf(kind) !== -1;
  40835. }
  40836. return false;
  40837. }
  40838. return this._vertexBuffers[kind] !== undefined;
  40839. };
  40840. /**
  40841. * Gets a list of all attached data kinds (Position, normal, etc...)
  40842. * @returns a list of string containing all kinds
  40843. */
  40844. Geometry.prototype.getVerticesDataKinds = function () {
  40845. var result = [];
  40846. var kind;
  40847. if (!this._vertexBuffers && this._delayInfo) {
  40848. for (kind in this._delayInfo) {
  40849. result.push(kind);
  40850. }
  40851. }
  40852. else {
  40853. for (kind in this._vertexBuffers) {
  40854. result.push(kind);
  40855. }
  40856. }
  40857. return result;
  40858. };
  40859. /**
  40860. * Update index buffer
  40861. * @param indices defines the indices to store in the index buffer
  40862. * @param offset defines the offset in the target buffer where to store the data
  40863. */
  40864. Geometry.prototype.updateIndices = function (indices, offset) {
  40865. if (!this._indexBuffer) {
  40866. return;
  40867. }
  40868. if (!this._indexBufferIsUpdatable) {
  40869. this.setIndices(indices, null, true);
  40870. }
  40871. else {
  40872. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40873. }
  40874. };
  40875. /**
  40876. * Creates a new index buffer
  40877. * @param indices defines the indices to store in the index buffer
  40878. * @param totalVertices defines the total number of vertices (could be null)
  40879. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40880. */
  40881. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40882. if (totalVertices === void 0) { totalVertices = null; }
  40883. if (updatable === void 0) { updatable = false; }
  40884. if (this._indexBuffer) {
  40885. this._engine._releaseBuffer(this._indexBuffer);
  40886. }
  40887. this._disposeVertexArrayObjects();
  40888. this._indices = indices;
  40889. this._indexBufferIsUpdatable = updatable;
  40890. if (this._meshes.length !== 0 && this._indices) {
  40891. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40892. }
  40893. if (totalVertices != undefined) { // including null and undefined
  40894. this._totalVertices = totalVertices;
  40895. }
  40896. var meshes = this._meshes;
  40897. var numOfMeshes = meshes.length;
  40898. for (var index = 0; index < numOfMeshes; index++) {
  40899. meshes[index]._createGlobalSubMesh(true);
  40900. }
  40901. this.notifyUpdate();
  40902. };
  40903. /**
  40904. * Return the total number of indices
  40905. * @returns the total number of indices
  40906. */
  40907. Geometry.prototype.getTotalIndices = function () {
  40908. if (!this.isReady()) {
  40909. return 0;
  40910. }
  40911. return this._indices.length;
  40912. };
  40913. /**
  40914. * Gets the index buffer array
  40915. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40916. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40917. * @returns the index buffer array
  40918. */
  40919. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40920. if (!this.isReady()) {
  40921. return null;
  40922. }
  40923. var orig = this._indices;
  40924. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40925. return orig;
  40926. }
  40927. else {
  40928. var len = orig.length;
  40929. var copy = [];
  40930. for (var i = 0; i < len; i++) {
  40931. copy.push(orig[i]);
  40932. }
  40933. return copy;
  40934. }
  40935. };
  40936. /**
  40937. * Gets the index buffer
  40938. * @return the index buffer
  40939. */
  40940. Geometry.prototype.getIndexBuffer = function () {
  40941. if (!this.isReady()) {
  40942. return null;
  40943. }
  40944. return this._indexBuffer;
  40945. };
  40946. /** @hidden */
  40947. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40948. if (effect === void 0) { effect = null; }
  40949. if (!effect || !this._vertexArrayObjects) {
  40950. return;
  40951. }
  40952. if (this._vertexArrayObjects[effect.key]) {
  40953. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40954. delete this._vertexArrayObjects[effect.key];
  40955. }
  40956. };
  40957. /**
  40958. * Release the associated resources for a specific mesh
  40959. * @param mesh defines the source mesh
  40960. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40961. */
  40962. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40963. var meshes = this._meshes;
  40964. var index = meshes.indexOf(mesh);
  40965. if (index === -1) {
  40966. return;
  40967. }
  40968. meshes.splice(index, 1);
  40969. mesh._geometry = null;
  40970. if (meshes.length === 0 && shouldDispose) {
  40971. this.dispose();
  40972. }
  40973. };
  40974. /**
  40975. * Apply current geometry to a given mesh
  40976. * @param mesh defines the mesh to apply geometry to
  40977. */
  40978. Geometry.prototype.applyToMesh = function (mesh) {
  40979. if (mesh._geometry === this) {
  40980. return;
  40981. }
  40982. var previousGeometry = mesh._geometry;
  40983. if (previousGeometry) {
  40984. previousGeometry.releaseForMesh(mesh);
  40985. }
  40986. var meshes = this._meshes;
  40987. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40988. mesh._geometry = this;
  40989. this._scene.pushGeometry(this);
  40990. meshes.push(mesh);
  40991. if (this.isReady()) {
  40992. this._applyToMesh(mesh);
  40993. }
  40994. else {
  40995. mesh._boundingInfo = this._boundingInfo;
  40996. }
  40997. };
  40998. Geometry.prototype._updateExtend = function (data) {
  40999. if (data === void 0) { data = null; }
  41000. if (!data) {
  41001. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41002. }
  41003. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  41004. };
  41005. Geometry.prototype._applyToMesh = function (mesh) {
  41006. var numOfMeshes = this._meshes.length;
  41007. // vertexBuffers
  41008. for (var kind in this._vertexBuffers) {
  41009. if (numOfMeshes === 1) {
  41010. this._vertexBuffers[kind].create();
  41011. }
  41012. var buffer = this._vertexBuffers[kind].getBuffer();
  41013. if (buffer) {
  41014. buffer.references = numOfMeshes;
  41015. }
  41016. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41017. if (!this._extend) {
  41018. this._updateExtend();
  41019. }
  41020. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41021. mesh._createGlobalSubMesh(false);
  41022. //bounding info was just created again, world matrix should be applied again.
  41023. mesh._updateBoundingInfo();
  41024. }
  41025. }
  41026. // indexBuffer
  41027. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41028. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41029. }
  41030. if (this._indexBuffer) {
  41031. this._indexBuffer.references = numOfMeshes;
  41032. }
  41033. // morphTargets
  41034. mesh._syncGeometryWithMorphTargetManager();
  41035. };
  41036. Geometry.prototype.notifyUpdate = function (kind) {
  41037. if (this.onGeometryUpdated) {
  41038. this.onGeometryUpdated(this, kind);
  41039. }
  41040. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41041. var mesh = _a[_i];
  41042. mesh._markSubMeshesAsAttributesDirty();
  41043. }
  41044. };
  41045. /**
  41046. * Load the geometry if it was flagged as delay loaded
  41047. * @param scene defines the hosting scene
  41048. * @param onLoaded defines a callback called when the geometry is loaded
  41049. */
  41050. Geometry.prototype.load = function (scene, onLoaded) {
  41051. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41052. return;
  41053. }
  41054. if (this.isReady()) {
  41055. if (onLoaded) {
  41056. onLoaded();
  41057. }
  41058. return;
  41059. }
  41060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41061. this._queueLoad(scene, onLoaded);
  41062. };
  41063. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41064. var _this = this;
  41065. if (!this.delayLoadingFile) {
  41066. return;
  41067. }
  41068. scene._addPendingData(this);
  41069. scene._loadFile(this.delayLoadingFile, function (data) {
  41070. if (!_this._delayLoadingFunction) {
  41071. return;
  41072. }
  41073. _this._delayLoadingFunction(JSON.parse(data), _this);
  41074. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41075. _this._delayInfo = [];
  41076. scene._removePendingData(_this);
  41077. var meshes = _this._meshes;
  41078. var numOfMeshes = meshes.length;
  41079. for (var index = 0; index < numOfMeshes; index++) {
  41080. _this._applyToMesh(meshes[index]);
  41081. }
  41082. if (onLoaded) {
  41083. onLoaded();
  41084. }
  41085. }, undefined, true);
  41086. };
  41087. /**
  41088. * Invert the geometry to move from a right handed system to a left handed one.
  41089. */
  41090. Geometry.prototype.toLeftHanded = function () {
  41091. // Flip faces
  41092. var tIndices = this.getIndices(false);
  41093. if (tIndices != null && tIndices.length > 0) {
  41094. for (var i = 0; i < tIndices.length; i += 3) {
  41095. var tTemp = tIndices[i + 0];
  41096. tIndices[i + 0] = tIndices[i + 2];
  41097. tIndices[i + 2] = tTemp;
  41098. }
  41099. this.setIndices(tIndices);
  41100. }
  41101. // Negate position.z
  41102. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41103. if (tPositions != null && tPositions.length > 0) {
  41104. for (var i = 0; i < tPositions.length; i += 3) {
  41105. tPositions[i + 2] = -tPositions[i + 2];
  41106. }
  41107. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41108. }
  41109. // Negate normal.z
  41110. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41111. if (tNormals != null && tNormals.length > 0) {
  41112. for (var i = 0; i < tNormals.length; i += 3) {
  41113. tNormals[i + 2] = -tNormals[i + 2];
  41114. }
  41115. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41116. }
  41117. };
  41118. // Cache
  41119. /** @hidden */
  41120. Geometry.prototype._resetPointsArrayCache = function () {
  41121. this._positions = null;
  41122. };
  41123. /** @hidden */
  41124. Geometry.prototype._generatePointsArray = function () {
  41125. if (this._positions) {
  41126. return true;
  41127. }
  41128. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41129. if (!data || data.length === 0) {
  41130. return false;
  41131. }
  41132. this._positions = [];
  41133. for (var index = 0; index < data.length; index += 3) {
  41134. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41135. }
  41136. return true;
  41137. };
  41138. /**
  41139. * Gets a value indicating if the geometry is disposed
  41140. * @returns true if the geometry was disposed
  41141. */
  41142. Geometry.prototype.isDisposed = function () {
  41143. return this._isDisposed;
  41144. };
  41145. Geometry.prototype._disposeVertexArrayObjects = function () {
  41146. if (this._vertexArrayObjects) {
  41147. for (var kind in this._vertexArrayObjects) {
  41148. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41149. }
  41150. this._vertexArrayObjects = {};
  41151. }
  41152. };
  41153. /**
  41154. * Free all associated resources
  41155. */
  41156. Geometry.prototype.dispose = function () {
  41157. var meshes = this._meshes;
  41158. var numOfMeshes = meshes.length;
  41159. var index;
  41160. for (index = 0; index < numOfMeshes; index++) {
  41161. this.releaseForMesh(meshes[index]);
  41162. }
  41163. this._meshes = [];
  41164. this._disposeVertexArrayObjects();
  41165. for (var kind in this._vertexBuffers) {
  41166. this._vertexBuffers[kind].dispose();
  41167. }
  41168. this._vertexBuffers = {};
  41169. this._totalVertices = 0;
  41170. if (this._indexBuffer) {
  41171. this._engine._releaseBuffer(this._indexBuffer);
  41172. }
  41173. this._indexBuffer = null;
  41174. this._indices = [];
  41175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41176. this.delayLoadingFile = null;
  41177. this._delayLoadingFunction = null;
  41178. this._delayInfo = [];
  41179. this._boundingInfo = null;
  41180. this._scene.removeGeometry(this);
  41181. this._isDisposed = true;
  41182. };
  41183. /**
  41184. * Clone the current geometry into a new geometry
  41185. * @param id defines the unique ID of the new geometry
  41186. * @returns a new geometry object
  41187. */
  41188. Geometry.prototype.copy = function (id) {
  41189. var vertexData = new BABYLON.VertexData();
  41190. vertexData.indices = [];
  41191. var indices = this.getIndices();
  41192. if (indices) {
  41193. for (var index = 0; index < indices.length; index++) {
  41194. vertexData.indices.push(indices[index]);
  41195. }
  41196. }
  41197. var updatable = false;
  41198. var stopChecking = false;
  41199. var kind;
  41200. for (kind in this._vertexBuffers) {
  41201. // using slice() to make a copy of the array and not just reference it
  41202. var data = this.getVerticesData(kind);
  41203. if (data instanceof Float32Array) {
  41204. vertexData.set(new Float32Array(data), kind);
  41205. }
  41206. else {
  41207. vertexData.set(data.slice(0), kind);
  41208. }
  41209. if (!stopChecking) {
  41210. var vb = this.getVertexBuffer(kind);
  41211. if (vb) {
  41212. updatable = vb.isUpdatable();
  41213. stopChecking = !updatable;
  41214. }
  41215. }
  41216. }
  41217. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41218. geometry.delayLoadState = this.delayLoadState;
  41219. geometry.delayLoadingFile = this.delayLoadingFile;
  41220. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41221. for (kind in this._delayInfo) {
  41222. geometry._delayInfo = geometry._delayInfo || [];
  41223. geometry._delayInfo.push(kind);
  41224. }
  41225. // Bounding info
  41226. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41227. return geometry;
  41228. };
  41229. /**
  41230. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41231. * @return a JSON representation of the current geometry data (without the vertices data)
  41232. */
  41233. Geometry.prototype.serialize = function () {
  41234. var serializationObject = {};
  41235. serializationObject.id = this.id;
  41236. serializationObject.updatable = this._updatable;
  41237. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41238. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41239. }
  41240. return serializationObject;
  41241. };
  41242. Geometry.prototype.toNumberArray = function (origin) {
  41243. if (Array.isArray(origin)) {
  41244. return origin;
  41245. }
  41246. else {
  41247. return Array.prototype.slice.call(origin);
  41248. }
  41249. };
  41250. /**
  41251. * Serialize all vertices data into a JSON oject
  41252. * @returns a JSON representation of the current geometry data
  41253. */
  41254. Geometry.prototype.serializeVerticeData = function () {
  41255. var serializationObject = this.serialize();
  41256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41257. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41258. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41259. serializationObject.positions._updatable = true;
  41260. }
  41261. }
  41262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41263. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41264. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41265. serializationObject.normals._updatable = true;
  41266. }
  41267. }
  41268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41269. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41270. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41271. serializationObject.tangets._updatable = true;
  41272. }
  41273. }
  41274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41275. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41276. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41277. serializationObject.uvs._updatable = true;
  41278. }
  41279. }
  41280. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41281. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41282. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41283. serializationObject.uv2s._updatable = true;
  41284. }
  41285. }
  41286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41287. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41288. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41289. serializationObject.uv3s._updatable = true;
  41290. }
  41291. }
  41292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41293. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41294. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41295. serializationObject.uv4s._updatable = true;
  41296. }
  41297. }
  41298. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41299. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41300. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41301. serializationObject.uv5s._updatable = true;
  41302. }
  41303. }
  41304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41305. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41306. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41307. serializationObject.uv6s._updatable = true;
  41308. }
  41309. }
  41310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41311. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41312. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41313. serializationObject.colors._updatable = true;
  41314. }
  41315. }
  41316. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41317. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41318. serializationObject.matricesIndices._isExpanded = true;
  41319. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41320. serializationObject.matricesIndices._updatable = true;
  41321. }
  41322. }
  41323. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41324. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41325. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41326. serializationObject.matricesWeights._updatable = true;
  41327. }
  41328. }
  41329. serializationObject.indices = this.toNumberArray(this.getIndices());
  41330. return serializationObject;
  41331. };
  41332. // Statics
  41333. /**
  41334. * Extracts a clone of a mesh geometry
  41335. * @param mesh defines the source mesh
  41336. * @param id defines the unique ID of the new geometry object
  41337. * @returns the new geometry object
  41338. */
  41339. Geometry.ExtractFromMesh = function (mesh, id) {
  41340. var geometry = mesh._geometry;
  41341. if (!geometry) {
  41342. return null;
  41343. }
  41344. return geometry.copy(id);
  41345. };
  41346. /**
  41347. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41348. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41349. * Be aware Math.random() could cause collisions, but:
  41350. * "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"
  41351. * @returns a string containing a new GUID
  41352. */
  41353. Geometry.RandomId = function () {
  41354. return BABYLON.Tools.RandomId();
  41355. };
  41356. /** @hidden */
  41357. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41358. var scene = mesh.getScene();
  41359. // Geometry
  41360. var geometryId = parsedGeometry.geometryId;
  41361. if (geometryId) {
  41362. var geometry = scene.getGeometryByID(geometryId);
  41363. if (geometry) {
  41364. geometry.applyToMesh(mesh);
  41365. }
  41366. }
  41367. else if (parsedGeometry instanceof ArrayBuffer) {
  41368. var binaryInfo = mesh._binaryInfo;
  41369. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41370. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41371. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41372. }
  41373. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41374. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41375. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41376. }
  41377. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41378. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41379. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41380. }
  41381. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41382. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41383. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41384. }
  41385. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41386. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41387. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41388. }
  41389. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41390. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41391. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41392. }
  41393. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41394. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41395. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41396. }
  41397. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41398. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41399. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41400. }
  41401. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41402. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41403. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41404. }
  41405. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41406. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41407. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41408. }
  41409. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41410. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41411. var floatIndices = [];
  41412. for (var i = 0; i < matricesIndicesData.length; i++) {
  41413. var index = matricesIndicesData[i];
  41414. floatIndices.push(index & 0x000000FF);
  41415. floatIndices.push((index & 0x0000FF00) >> 8);
  41416. floatIndices.push((index & 0x00FF0000) >> 16);
  41417. floatIndices.push(index >> 24);
  41418. }
  41419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41420. }
  41421. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41422. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41423. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41424. }
  41425. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41426. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41427. mesh.setIndices(indicesData, null);
  41428. }
  41429. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41430. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41431. mesh.subMeshes = [];
  41432. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41433. var materialIndex = subMeshesData[(i * 5) + 0];
  41434. var verticesStart = subMeshesData[(i * 5) + 1];
  41435. var verticesCount = subMeshesData[(i * 5) + 2];
  41436. var indexStart = subMeshesData[(i * 5) + 3];
  41437. var indexCount = subMeshesData[(i * 5) + 4];
  41438. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41439. }
  41440. }
  41441. }
  41442. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41443. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41444. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41445. if (parsedGeometry.tangents) {
  41446. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41447. }
  41448. if (parsedGeometry.uvs) {
  41449. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41450. }
  41451. if (parsedGeometry.uvs2) {
  41452. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41453. }
  41454. if (parsedGeometry.uvs3) {
  41455. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41456. }
  41457. if (parsedGeometry.uvs4) {
  41458. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41459. }
  41460. if (parsedGeometry.uvs5) {
  41461. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41462. }
  41463. if (parsedGeometry.uvs6) {
  41464. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41465. }
  41466. if (parsedGeometry.colors) {
  41467. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41468. }
  41469. if (parsedGeometry.matricesIndices) {
  41470. if (!parsedGeometry.matricesIndices._isExpanded) {
  41471. var floatIndices = [];
  41472. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41473. var matricesIndex = parsedGeometry.matricesIndices[i];
  41474. floatIndices.push(matricesIndex & 0x000000FF);
  41475. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41476. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41477. floatIndices.push(matricesIndex >> 24);
  41478. }
  41479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41480. }
  41481. else {
  41482. delete parsedGeometry.matricesIndices._isExpanded;
  41483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41484. }
  41485. }
  41486. if (parsedGeometry.matricesIndicesExtra) {
  41487. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41488. var floatIndices = [];
  41489. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41490. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41491. floatIndices.push(matricesIndex & 0x000000FF);
  41492. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41493. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41494. floatIndices.push(matricesIndex >> 24);
  41495. }
  41496. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41497. }
  41498. else {
  41499. delete parsedGeometry.matricesIndices._isExpanded;
  41500. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41501. }
  41502. }
  41503. if (parsedGeometry.matricesWeights) {
  41504. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41505. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41506. }
  41507. if (parsedGeometry.matricesWeightsExtra) {
  41508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41509. }
  41510. mesh.setIndices(parsedGeometry.indices, null);
  41511. }
  41512. // SubMeshes
  41513. if (parsedGeometry.subMeshes) {
  41514. mesh.subMeshes = [];
  41515. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41516. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41517. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41518. }
  41519. }
  41520. // Flat shading
  41521. if (mesh._shouldGenerateFlatShading) {
  41522. mesh.convertToFlatShadedMesh();
  41523. delete mesh._shouldGenerateFlatShading;
  41524. }
  41525. // Update
  41526. mesh.computeWorldMatrix(true);
  41527. scene.onMeshImportedObservable.notifyObservers(mesh);
  41528. };
  41529. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41530. var epsilon = 1e-3;
  41531. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41532. return;
  41533. }
  41534. var noInfluenceBoneIndex = 0.0;
  41535. if (parsedGeometry.skeletonId > -1) {
  41536. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41537. if (!skeleton) {
  41538. return;
  41539. }
  41540. noInfluenceBoneIndex = skeleton.bones.length;
  41541. }
  41542. else {
  41543. return;
  41544. }
  41545. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41546. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41547. var matricesWeights = parsedGeometry.matricesWeights;
  41548. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41549. var influencers = parsedGeometry.numBoneInfluencer;
  41550. var size = matricesWeights.length;
  41551. for (var i = 0; i < size; i += 4) {
  41552. var weight = 0.0;
  41553. var firstZeroWeight = -1;
  41554. for (var j = 0; j < 4; j++) {
  41555. var w = matricesWeights[i + j];
  41556. weight += w;
  41557. if (w < epsilon && firstZeroWeight < 0) {
  41558. firstZeroWeight = j;
  41559. }
  41560. }
  41561. if (matricesWeightsExtra) {
  41562. for (var j = 0; j < 4; j++) {
  41563. var w = matricesWeightsExtra[i + j];
  41564. weight += w;
  41565. if (w < epsilon && firstZeroWeight < 0) {
  41566. firstZeroWeight = j + 4;
  41567. }
  41568. }
  41569. }
  41570. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41571. firstZeroWeight = influencers - 1;
  41572. }
  41573. if (weight > epsilon) {
  41574. var mweight = 1.0 / weight;
  41575. for (var j = 0; j < 4; j++) {
  41576. matricesWeights[i + j] *= mweight;
  41577. }
  41578. if (matricesWeightsExtra) {
  41579. for (var j = 0; j < 4; j++) {
  41580. matricesWeightsExtra[i + j] *= mweight;
  41581. }
  41582. }
  41583. }
  41584. else {
  41585. if (firstZeroWeight >= 4) {
  41586. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41587. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41588. }
  41589. else {
  41590. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41591. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41592. }
  41593. }
  41594. }
  41595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41596. if (parsedGeometry.matricesWeightsExtra) {
  41597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41598. }
  41599. };
  41600. /**
  41601. * Create a new geometry from persisted data (Using .babylon file format)
  41602. * @param parsedVertexData defines the persisted data
  41603. * @param scene defines the hosting scene
  41604. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41605. * @returns the new geometry object
  41606. */
  41607. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41608. if (scene.getGeometryByID(parsedVertexData.id)) {
  41609. return null; // null since geometry could be something else than a box...
  41610. }
  41611. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41612. if (BABYLON.Tags) {
  41613. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41614. }
  41615. if (parsedVertexData.delayLoadingFile) {
  41616. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41617. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41618. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41619. geometry._delayInfo = [];
  41620. if (parsedVertexData.hasUVs) {
  41621. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41622. }
  41623. if (parsedVertexData.hasUVs2) {
  41624. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41625. }
  41626. if (parsedVertexData.hasUVs3) {
  41627. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41628. }
  41629. if (parsedVertexData.hasUVs4) {
  41630. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41631. }
  41632. if (parsedVertexData.hasUVs5) {
  41633. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41634. }
  41635. if (parsedVertexData.hasUVs6) {
  41636. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41637. }
  41638. if (parsedVertexData.hasColors) {
  41639. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41640. }
  41641. if (parsedVertexData.hasMatricesIndices) {
  41642. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41643. }
  41644. if (parsedVertexData.hasMatricesWeights) {
  41645. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41646. }
  41647. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41648. }
  41649. else {
  41650. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41651. }
  41652. scene.pushGeometry(geometry, true);
  41653. return geometry;
  41654. };
  41655. return Geometry;
  41656. }());
  41657. BABYLON.Geometry = Geometry;
  41658. // Primitives
  41659. /// Abstract class
  41660. /**
  41661. * Abstract class used to provide common services for all typed geometries
  41662. * @hidden
  41663. */
  41664. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41665. __extends(_PrimitiveGeometry, _super);
  41666. /**
  41667. * Creates a new typed geometry
  41668. * @param id defines the unique ID of the geometry
  41669. * @param scene defines the hosting scene
  41670. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41671. * @param mesh defines the hosting mesh (can be null)
  41672. */
  41673. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41674. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41675. if (mesh === void 0) { mesh = null; }
  41676. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41677. _this._canBeRegenerated = _canBeRegenerated;
  41678. _this._beingRegenerated = true;
  41679. _this.regenerate();
  41680. _this._beingRegenerated = false;
  41681. return _this;
  41682. }
  41683. /**
  41684. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41685. * @returns true if the geometry can be regenerated
  41686. */
  41687. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41688. return this._canBeRegenerated;
  41689. };
  41690. /**
  41691. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41692. */
  41693. _PrimitiveGeometry.prototype.regenerate = function () {
  41694. if (!this._canBeRegenerated) {
  41695. return;
  41696. }
  41697. this._beingRegenerated = true;
  41698. this.setAllVerticesData(this._regenerateVertexData(), false);
  41699. this._beingRegenerated = false;
  41700. };
  41701. /**
  41702. * Clone the geometry
  41703. * @param id defines the unique ID of the new geometry
  41704. * @returns the new geometry
  41705. */
  41706. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41707. return _super.prototype.copy.call(this, id);
  41708. };
  41709. // overrides
  41710. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41711. if (!this._beingRegenerated) {
  41712. return;
  41713. }
  41714. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41715. };
  41716. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41717. if (!this._beingRegenerated) {
  41718. return;
  41719. }
  41720. _super.prototype.setVerticesData.call(this, kind, data, false);
  41721. };
  41722. // to override
  41723. /** @hidden */
  41724. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41725. throw new Error("Abstract method");
  41726. };
  41727. _PrimitiveGeometry.prototype.copy = function (id) {
  41728. throw new Error("Must be overriden in sub-classes.");
  41729. };
  41730. _PrimitiveGeometry.prototype.serialize = function () {
  41731. var serializationObject = _super.prototype.serialize.call(this);
  41732. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41733. return serializationObject;
  41734. };
  41735. return _PrimitiveGeometry;
  41736. }(Geometry));
  41737. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41738. /**
  41739. * Creates a ribbon geometry
  41740. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41741. */
  41742. var RibbonGeometry = /** @class */ (function (_super) {
  41743. __extends(RibbonGeometry, _super);
  41744. /**
  41745. * Creates a ribbon geometry
  41746. * @param id defines the unique ID of the geometry
  41747. * @param scene defines the hosting scene
  41748. * @param pathArray defines the array of paths to use
  41749. * @param closeArray defines if the last path and the first path must be joined
  41750. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41751. * @param offset defines the offset between points
  41752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41753. * @param mesh defines the hosting mesh (can be null)
  41754. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41755. */
  41756. function RibbonGeometry(id, scene,
  41757. /**
  41758. * Defines the array of paths to use
  41759. */
  41760. pathArray,
  41761. /**
  41762. * Defines if the last and first points of each path in your pathArray must be joined
  41763. */
  41764. closeArray,
  41765. /**
  41766. * Defines if the last and first points of each path in your pathArray must be joined
  41767. */
  41768. closePath,
  41769. /**
  41770. * Defines the offset between points
  41771. */
  41772. offset, canBeRegenerated, mesh,
  41773. /**
  41774. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41775. */
  41776. side) {
  41777. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41778. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41779. _this.pathArray = pathArray;
  41780. _this.closeArray = closeArray;
  41781. _this.closePath = closePath;
  41782. _this.offset = offset;
  41783. _this.side = side;
  41784. return _this;
  41785. }
  41786. /** @hidden */
  41787. RibbonGeometry.prototype._regenerateVertexData = function () {
  41788. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41789. };
  41790. RibbonGeometry.prototype.copy = function (id) {
  41791. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41792. };
  41793. return RibbonGeometry;
  41794. }(_PrimitiveGeometry));
  41795. BABYLON.RibbonGeometry = RibbonGeometry;
  41796. /**
  41797. * Creates a box geometry
  41798. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41799. */
  41800. var BoxGeometry = /** @class */ (function (_super) {
  41801. __extends(BoxGeometry, _super);
  41802. /**
  41803. * Creates a box geometry
  41804. * @param id defines the unique ID of the geometry
  41805. * @param scene defines the hosting scene
  41806. * @param size defines the zise of the box (width, height and depth are the same)
  41807. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41808. * @param mesh defines the hosting mesh (can be null)
  41809. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41810. */
  41811. function BoxGeometry(id, scene,
  41812. /**
  41813. * Defines the zise of the box (width, height and depth are the same)
  41814. */
  41815. size, canBeRegenerated, mesh,
  41816. /**
  41817. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41818. */
  41819. side) {
  41820. if (mesh === void 0) { mesh = null; }
  41821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41822. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41823. _this.size = size;
  41824. _this.side = side;
  41825. return _this;
  41826. }
  41827. /** @hidden */
  41828. BoxGeometry.prototype._regenerateVertexData = function () {
  41829. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41830. };
  41831. BoxGeometry.prototype.copy = function (id) {
  41832. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41833. };
  41834. BoxGeometry.prototype.serialize = function () {
  41835. var serializationObject = _super.prototype.serialize.call(this);
  41836. serializationObject.size = this.size;
  41837. return serializationObject;
  41838. };
  41839. BoxGeometry.Parse = function (parsedBox, scene) {
  41840. if (scene.getGeometryByID(parsedBox.id)) {
  41841. return null; // null since geometry could be something else than a box...
  41842. }
  41843. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41844. if (BABYLON.Tags) {
  41845. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41846. }
  41847. scene.pushGeometry(box, true);
  41848. return box;
  41849. };
  41850. return BoxGeometry;
  41851. }(_PrimitiveGeometry));
  41852. BABYLON.BoxGeometry = BoxGeometry;
  41853. /**
  41854. * Creates a sphere geometry
  41855. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41856. */
  41857. var SphereGeometry = /** @class */ (function (_super) {
  41858. __extends(SphereGeometry, _super);
  41859. /**
  41860. * Create a new sphere geometry
  41861. * @param id defines the unique ID of the geometry
  41862. * @param scene defines the hosting scene
  41863. * @param segments defines the number of segments to use to create the sphere
  41864. * @param diameter defines the diameter of the sphere
  41865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41866. * @param mesh defines the hosting mesh (can be null)
  41867. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41868. */
  41869. function SphereGeometry(id, scene,
  41870. /**
  41871. * Defines the number of segments to use to create the sphere
  41872. */
  41873. segments,
  41874. /**
  41875. * Defines the diameter of the sphere
  41876. */
  41877. diameter, canBeRegenerated, mesh,
  41878. /**
  41879. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41880. */
  41881. side) {
  41882. if (mesh === void 0) { mesh = null; }
  41883. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41884. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41885. _this.segments = segments;
  41886. _this.diameter = diameter;
  41887. _this.side = side;
  41888. return _this;
  41889. }
  41890. /** @hidden */
  41891. SphereGeometry.prototype._regenerateVertexData = function () {
  41892. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41893. };
  41894. SphereGeometry.prototype.copy = function (id) {
  41895. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41896. };
  41897. SphereGeometry.prototype.serialize = function () {
  41898. var serializationObject = _super.prototype.serialize.call(this);
  41899. serializationObject.segments = this.segments;
  41900. serializationObject.diameter = this.diameter;
  41901. return serializationObject;
  41902. };
  41903. SphereGeometry.Parse = function (parsedSphere, scene) {
  41904. if (scene.getGeometryByID(parsedSphere.id)) {
  41905. return null; // null since geometry could be something else than a sphere...
  41906. }
  41907. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41908. if (BABYLON.Tags) {
  41909. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41910. }
  41911. scene.pushGeometry(sphere, true);
  41912. return sphere;
  41913. };
  41914. return SphereGeometry;
  41915. }(_PrimitiveGeometry));
  41916. BABYLON.SphereGeometry = SphereGeometry;
  41917. /**
  41918. * Creates a disc geometry
  41919. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41920. */
  41921. var DiscGeometry = /** @class */ (function (_super) {
  41922. __extends(DiscGeometry, _super);
  41923. /**
  41924. * Creates a new disc geometry
  41925. * @param id defines the unique ID of the geometry
  41926. * @param scene defines the hosting scene
  41927. * @param radius defines the radius of the disc
  41928. * @param tessellation defines the tesselation factor to apply to the disc
  41929. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41930. * @param mesh defines the hosting mesh (can be null)
  41931. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41932. */
  41933. function DiscGeometry(id, scene,
  41934. /**
  41935. * Defines the radius of the disc
  41936. */
  41937. radius,
  41938. /**
  41939. * Defines the tesselation factor to apply to the disc
  41940. */
  41941. tessellation, canBeRegenerated, mesh,
  41942. /**
  41943. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41944. */
  41945. side) {
  41946. if (mesh === void 0) { mesh = null; }
  41947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41948. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41949. _this.radius = radius;
  41950. _this.tessellation = tessellation;
  41951. _this.side = side;
  41952. return _this;
  41953. }
  41954. /** @hidden */
  41955. DiscGeometry.prototype._regenerateVertexData = function () {
  41956. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41957. };
  41958. DiscGeometry.prototype.copy = function (id) {
  41959. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41960. };
  41961. return DiscGeometry;
  41962. }(_PrimitiveGeometry));
  41963. BABYLON.DiscGeometry = DiscGeometry;
  41964. /**
  41965. * Creates a new cylinder geometry
  41966. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41967. */
  41968. var CylinderGeometry = /** @class */ (function (_super) {
  41969. __extends(CylinderGeometry, _super);
  41970. /**
  41971. * Creates a new cylinder geometry
  41972. * @param id defines the unique ID of the geometry
  41973. * @param scene defines the hosting scene
  41974. * @param height defines the height of the cylinder
  41975. * @param diameterTop defines the diameter of the cylinder's top cap
  41976. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41977. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41978. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41979. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41980. * @param mesh defines the hosting mesh (can be null)
  41981. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41982. */
  41983. function CylinderGeometry(id, scene,
  41984. /**
  41985. * Defines the height of the cylinder
  41986. */
  41987. height,
  41988. /**
  41989. * Defines the diameter of the cylinder's top cap
  41990. */
  41991. diameterTop,
  41992. /**
  41993. * Defines the diameter of the cylinder's bottom cap
  41994. */
  41995. diameterBottom,
  41996. /**
  41997. * Defines the tessellation factor to apply to the cylinder
  41998. */
  41999. tessellation,
  42000. /**
  42001. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  42002. */
  42003. subdivisions, canBeRegenerated, mesh,
  42004. /**
  42005. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42006. */
  42007. side) {
  42008. if (subdivisions === void 0) { subdivisions = 1; }
  42009. if (mesh === void 0) { mesh = null; }
  42010. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42011. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42012. _this.height = height;
  42013. _this.diameterTop = diameterTop;
  42014. _this.diameterBottom = diameterBottom;
  42015. _this.tessellation = tessellation;
  42016. _this.subdivisions = subdivisions;
  42017. _this.side = side;
  42018. return _this;
  42019. }
  42020. /** @hidden */
  42021. CylinderGeometry.prototype._regenerateVertexData = function () {
  42022. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42023. };
  42024. CylinderGeometry.prototype.copy = function (id) {
  42025. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42026. };
  42027. CylinderGeometry.prototype.serialize = function () {
  42028. var serializationObject = _super.prototype.serialize.call(this);
  42029. serializationObject.height = this.height;
  42030. serializationObject.diameterTop = this.diameterTop;
  42031. serializationObject.diameterBottom = this.diameterBottom;
  42032. serializationObject.tessellation = this.tessellation;
  42033. return serializationObject;
  42034. };
  42035. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  42036. if (scene.getGeometryByID(parsedCylinder.id)) {
  42037. return null; // null since geometry could be something else than a cylinder...
  42038. }
  42039. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42040. if (BABYLON.Tags) {
  42041. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42042. }
  42043. scene.pushGeometry(cylinder, true);
  42044. return cylinder;
  42045. };
  42046. return CylinderGeometry;
  42047. }(_PrimitiveGeometry));
  42048. BABYLON.CylinderGeometry = CylinderGeometry;
  42049. /**
  42050. * Creates a new torus geometry
  42051. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42052. */
  42053. var TorusGeometry = /** @class */ (function (_super) {
  42054. __extends(TorusGeometry, _super);
  42055. /**
  42056. * Creates a new torus geometry
  42057. * @param id defines the unique ID of the geometry
  42058. * @param scene defines the hosting scene
  42059. * @param diameter defines the diameter of the torus
  42060. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42061. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42062. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42063. * @param mesh defines the hosting mesh (can be null)
  42064. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42065. */
  42066. function TorusGeometry(id, scene,
  42067. /**
  42068. * Defines the diameter of the torus
  42069. */
  42070. diameter,
  42071. /**
  42072. * Defines the thickness of the torus (ie. internal diameter)
  42073. */
  42074. thickness,
  42075. /**
  42076. * Defines the tesselation factor to apply to the torus
  42077. */
  42078. tessellation, canBeRegenerated, mesh,
  42079. /**
  42080. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42081. */
  42082. side) {
  42083. if (mesh === void 0) { mesh = null; }
  42084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42086. _this.diameter = diameter;
  42087. _this.thickness = thickness;
  42088. _this.tessellation = tessellation;
  42089. _this.side = side;
  42090. return _this;
  42091. }
  42092. /** @hidden */
  42093. TorusGeometry.prototype._regenerateVertexData = function () {
  42094. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42095. };
  42096. TorusGeometry.prototype.copy = function (id) {
  42097. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42098. };
  42099. TorusGeometry.prototype.serialize = function () {
  42100. var serializationObject = _super.prototype.serialize.call(this);
  42101. serializationObject.diameter = this.diameter;
  42102. serializationObject.thickness = this.thickness;
  42103. serializationObject.tessellation = this.tessellation;
  42104. return serializationObject;
  42105. };
  42106. TorusGeometry.Parse = function (parsedTorus, scene) {
  42107. if (scene.getGeometryByID(parsedTorus.id)) {
  42108. return null; // null since geometry could be something else than a torus...
  42109. }
  42110. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42111. if (BABYLON.Tags) {
  42112. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42113. }
  42114. scene.pushGeometry(torus, true);
  42115. return torus;
  42116. };
  42117. return TorusGeometry;
  42118. }(_PrimitiveGeometry));
  42119. BABYLON.TorusGeometry = TorusGeometry;
  42120. /**
  42121. * Creates a new ground geometry
  42122. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42123. */
  42124. var GroundGeometry = /** @class */ (function (_super) {
  42125. __extends(GroundGeometry, _super);
  42126. /**
  42127. * Creates a new ground geometry
  42128. * @param id defines the unique ID of the geometry
  42129. * @param scene defines the hosting scene
  42130. * @param width defines the width of the ground
  42131. * @param height defines the height of the ground
  42132. * @param subdivisions defines the subdivisions to apply to the ground
  42133. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42134. * @param mesh defines the hosting mesh (can be null)
  42135. */
  42136. function GroundGeometry(id, scene,
  42137. /**
  42138. * Defines the width of the ground
  42139. */
  42140. width,
  42141. /**
  42142. * Defines the height of the ground
  42143. */
  42144. height,
  42145. /**
  42146. * Defines the subdivisions to apply to the ground
  42147. */
  42148. subdivisions, canBeRegenerated, mesh) {
  42149. if (mesh === void 0) { mesh = null; }
  42150. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42151. _this.width = width;
  42152. _this.height = height;
  42153. _this.subdivisions = subdivisions;
  42154. return _this;
  42155. }
  42156. /** @hidden */
  42157. GroundGeometry.prototype._regenerateVertexData = function () {
  42158. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42159. };
  42160. GroundGeometry.prototype.copy = function (id) {
  42161. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42162. };
  42163. GroundGeometry.prototype.serialize = function () {
  42164. var serializationObject = _super.prototype.serialize.call(this);
  42165. serializationObject.width = this.width;
  42166. serializationObject.height = this.height;
  42167. serializationObject.subdivisions = this.subdivisions;
  42168. return serializationObject;
  42169. };
  42170. GroundGeometry.Parse = function (parsedGround, scene) {
  42171. if (scene.getGeometryByID(parsedGround.id)) {
  42172. return null; // null since geometry could be something else than a ground...
  42173. }
  42174. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42175. if (BABYLON.Tags) {
  42176. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42177. }
  42178. scene.pushGeometry(ground, true);
  42179. return ground;
  42180. };
  42181. return GroundGeometry;
  42182. }(_PrimitiveGeometry));
  42183. BABYLON.GroundGeometry = GroundGeometry;
  42184. /**
  42185. * Creates a tiled ground geometry
  42186. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42187. */
  42188. var TiledGroundGeometry = /** @class */ (function (_super) {
  42189. __extends(TiledGroundGeometry, _super);
  42190. /**
  42191. * Creates a tiled ground geometry
  42192. * @param id defines the unique ID of the geometry
  42193. * @param scene defines the hosting scene
  42194. * @param xmin defines the minimum value on X axis
  42195. * @param zmin defines the minimum value on Z axis
  42196. * @param xmax defines the maximum value on X axis
  42197. * @param zmax defines the maximum value on Z axis
  42198. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42199. * @param precision defines the precision to use when computing the tiles
  42200. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42201. * @param mesh defines the hosting mesh (can be null)
  42202. */
  42203. function TiledGroundGeometry(id, scene,
  42204. /**
  42205. * Defines the minimum value on X axis
  42206. */
  42207. xmin,
  42208. /**
  42209. * Defines the minimum value on Z axis
  42210. */
  42211. zmin,
  42212. /**
  42213. * Defines the maximum value on X axis
  42214. */
  42215. xmax,
  42216. /**
  42217. * Defines the maximum value on Z axis
  42218. */
  42219. zmax,
  42220. /**
  42221. * Defines the subdivisions to apply to the ground
  42222. */
  42223. subdivisions,
  42224. /**
  42225. * Defines the precision to use when computing the tiles
  42226. */
  42227. precision, canBeRegenerated, mesh) {
  42228. if (mesh === void 0) { mesh = null; }
  42229. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42230. _this.xmin = xmin;
  42231. _this.zmin = zmin;
  42232. _this.xmax = xmax;
  42233. _this.zmax = zmax;
  42234. _this.subdivisions = subdivisions;
  42235. _this.precision = precision;
  42236. return _this;
  42237. }
  42238. /** @hidden */
  42239. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42240. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42241. };
  42242. TiledGroundGeometry.prototype.copy = function (id) {
  42243. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42244. };
  42245. return TiledGroundGeometry;
  42246. }(_PrimitiveGeometry));
  42247. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42248. /**
  42249. * Creates a plane geometry
  42250. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42251. */
  42252. var PlaneGeometry = /** @class */ (function (_super) {
  42253. __extends(PlaneGeometry, _super);
  42254. /**
  42255. * Creates a plane geometry
  42256. * @param id defines the unique ID of the geometry
  42257. * @param scene defines the hosting scene
  42258. * @param size defines the size of the plane (width === height)
  42259. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42260. * @param mesh defines the hosting mesh (can be null)
  42261. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42262. */
  42263. function PlaneGeometry(id, scene,
  42264. /**
  42265. * Defines the size of the plane (width === height)
  42266. */
  42267. size, canBeRegenerated, mesh,
  42268. /**
  42269. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42270. */
  42271. side) {
  42272. if (mesh === void 0) { mesh = null; }
  42273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42275. _this.size = size;
  42276. _this.side = side;
  42277. return _this;
  42278. }
  42279. /** @hidden */
  42280. PlaneGeometry.prototype._regenerateVertexData = function () {
  42281. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42282. };
  42283. PlaneGeometry.prototype.copy = function (id) {
  42284. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42285. };
  42286. PlaneGeometry.prototype.serialize = function () {
  42287. var serializationObject = _super.prototype.serialize.call(this);
  42288. serializationObject.size = this.size;
  42289. return serializationObject;
  42290. };
  42291. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42292. if (scene.getGeometryByID(parsedPlane.id)) {
  42293. return null; // null since geometry could be something else than a ground...
  42294. }
  42295. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42296. if (BABYLON.Tags) {
  42297. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42298. }
  42299. scene.pushGeometry(plane, true);
  42300. return plane;
  42301. };
  42302. return PlaneGeometry;
  42303. }(_PrimitiveGeometry));
  42304. BABYLON.PlaneGeometry = PlaneGeometry;
  42305. /**
  42306. * Creates a torus knot geometry
  42307. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42308. */
  42309. var TorusKnotGeometry = /** @class */ (function (_super) {
  42310. __extends(TorusKnotGeometry, _super);
  42311. /**
  42312. * Creates a torus knot geometry
  42313. * @param id defines the unique ID of the geometry
  42314. * @param scene defines the hosting scene
  42315. * @param radius defines the radius of the torus knot
  42316. * @param tube defines the thickness of the torus knot tube
  42317. * @param radialSegments defines the number of radial segments
  42318. * @param tubularSegments defines the number of tubular segments
  42319. * @param p defines the first number of windings
  42320. * @param q defines the second number of windings
  42321. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42322. * @param mesh defines the hosting mesh (can be null)
  42323. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42324. */
  42325. function TorusKnotGeometry(id, scene,
  42326. /**
  42327. * Defines the radius of the torus knot
  42328. */
  42329. radius,
  42330. /**
  42331. * Defines the thickness of the torus knot tube
  42332. */
  42333. tube,
  42334. /**
  42335. * Defines the number of radial segments
  42336. */
  42337. radialSegments,
  42338. /**
  42339. * Defines the number of tubular segments
  42340. */
  42341. tubularSegments,
  42342. /**
  42343. * Defines the first number of windings
  42344. */
  42345. p,
  42346. /**
  42347. * Defines the second number of windings
  42348. */
  42349. q, canBeRegenerated, mesh,
  42350. /**
  42351. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42352. */
  42353. side) {
  42354. if (mesh === void 0) { mesh = null; }
  42355. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42356. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42357. _this.radius = radius;
  42358. _this.tube = tube;
  42359. _this.radialSegments = radialSegments;
  42360. _this.tubularSegments = tubularSegments;
  42361. _this.p = p;
  42362. _this.q = q;
  42363. _this.side = side;
  42364. return _this;
  42365. }
  42366. /** @hidden */
  42367. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42368. 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 });
  42369. };
  42370. TorusKnotGeometry.prototype.copy = function (id) {
  42371. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42372. };
  42373. TorusKnotGeometry.prototype.serialize = function () {
  42374. var serializationObject = _super.prototype.serialize.call(this);
  42375. serializationObject.radius = this.radius;
  42376. serializationObject.tube = this.tube;
  42377. serializationObject.radialSegments = this.radialSegments;
  42378. serializationObject.tubularSegments = this.tubularSegments;
  42379. serializationObject.p = this.p;
  42380. serializationObject.q = this.q;
  42381. return serializationObject;
  42382. };
  42383. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42384. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42385. return null; // null since geometry could be something else than a ground...
  42386. }
  42387. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42388. if (BABYLON.Tags) {
  42389. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42390. }
  42391. scene.pushGeometry(torusKnot, true);
  42392. return torusKnot;
  42393. };
  42394. return TorusKnotGeometry;
  42395. }(_PrimitiveGeometry));
  42396. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42397. //}
  42398. })(BABYLON || (BABYLON = {}));
  42399. //# sourceMappingURL=babylon.geometry.js.map
  42400. var BABYLON;
  42401. (function (BABYLON) {
  42402. /**
  42403. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42404. */
  42405. var PerformanceMonitor = /** @class */ (function () {
  42406. /**
  42407. * constructor
  42408. * @param frameSampleSize The number of samples required to saturate the sliding window
  42409. */
  42410. function PerformanceMonitor(frameSampleSize) {
  42411. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42412. this._enabled = true;
  42413. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42414. }
  42415. /**
  42416. * Samples current frame
  42417. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42418. */
  42419. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42420. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42421. if (!this._enabled) {
  42422. return;
  42423. }
  42424. if (this._lastFrameTimeMs != null) {
  42425. var dt = timeMs - this._lastFrameTimeMs;
  42426. this._rollingFrameTime.add(dt);
  42427. }
  42428. this._lastFrameTimeMs = timeMs;
  42429. };
  42430. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42431. /**
  42432. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42433. */
  42434. get: function () {
  42435. return this._rollingFrameTime.average;
  42436. },
  42437. enumerable: true,
  42438. configurable: true
  42439. });
  42440. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42441. /**
  42442. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42443. */
  42444. get: function () {
  42445. return this._rollingFrameTime.variance;
  42446. },
  42447. enumerable: true,
  42448. configurable: true
  42449. });
  42450. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42451. /**
  42452. * Returns the frame time of the most recent frame
  42453. */
  42454. get: function () {
  42455. return this._rollingFrameTime.history(0);
  42456. },
  42457. enumerable: true,
  42458. configurable: true
  42459. });
  42460. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42461. /**
  42462. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42463. */
  42464. get: function () {
  42465. return 1000.0 / this._rollingFrameTime.average;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42471. /**
  42472. * Returns the average framerate in frames per second using the most recent frame time
  42473. */
  42474. get: function () {
  42475. var history = this._rollingFrameTime.history(0);
  42476. if (history === 0) {
  42477. return 0;
  42478. }
  42479. return 1000.0 / history;
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42485. /**
  42486. * Returns true if enough samples have been taken to completely fill the sliding window
  42487. */
  42488. get: function () {
  42489. return this._rollingFrameTime.isSaturated();
  42490. },
  42491. enumerable: true,
  42492. configurable: true
  42493. });
  42494. /**
  42495. * Enables contributions to the sliding window sample set
  42496. */
  42497. PerformanceMonitor.prototype.enable = function () {
  42498. this._enabled = true;
  42499. };
  42500. /**
  42501. * Disables contributions to the sliding window sample set
  42502. * Samples will not be interpolated over the disabled period
  42503. */
  42504. PerformanceMonitor.prototype.disable = function () {
  42505. this._enabled = false;
  42506. //clear last sample to avoid interpolating over the disabled period when next enabled
  42507. this._lastFrameTimeMs = null;
  42508. };
  42509. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42510. /**
  42511. * Returns true if sampling is enabled
  42512. */
  42513. get: function () {
  42514. return this._enabled;
  42515. },
  42516. enumerable: true,
  42517. configurable: true
  42518. });
  42519. /**
  42520. * Resets performance monitor
  42521. */
  42522. PerformanceMonitor.prototype.reset = function () {
  42523. //clear last sample to avoid interpolating over the disabled period when next enabled
  42524. this._lastFrameTimeMs = null;
  42525. //wipe record
  42526. this._rollingFrameTime.reset();
  42527. };
  42528. return PerformanceMonitor;
  42529. }());
  42530. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42531. /**
  42532. * RollingAverage
  42533. *
  42534. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42535. */
  42536. var RollingAverage = /** @class */ (function () {
  42537. /**
  42538. * constructor
  42539. * @param length The number of samples required to saturate the sliding window
  42540. */
  42541. function RollingAverage(length) {
  42542. this._samples = new Array(length);
  42543. this.reset();
  42544. }
  42545. /**
  42546. * Adds a sample to the sample set
  42547. * @param v The sample value
  42548. */
  42549. RollingAverage.prototype.add = function (v) {
  42550. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42551. var delta;
  42552. //we need to check if we've already wrapped round
  42553. if (this.isSaturated()) {
  42554. //remove bottom of stack from mean
  42555. var bottomValue = this._samples[this._pos];
  42556. delta = bottomValue - this.average;
  42557. this.average -= delta / (this._sampleCount - 1);
  42558. this._m2 -= delta * (bottomValue - this.average);
  42559. }
  42560. else {
  42561. this._sampleCount++;
  42562. }
  42563. //add new value to mean
  42564. delta = v - this.average;
  42565. this.average += delta / (this._sampleCount);
  42566. this._m2 += delta * (v - this.average);
  42567. //set the new variance
  42568. this.variance = this._m2 / (this._sampleCount - 1);
  42569. this._samples[this._pos] = v;
  42570. this._pos++;
  42571. this._pos %= this._samples.length; //positive wrap around
  42572. };
  42573. /**
  42574. * Returns previously added values or null if outside of history or outside the sliding window domain
  42575. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42576. * @return Value previously recorded with add() or null if outside of range
  42577. */
  42578. RollingAverage.prototype.history = function (i) {
  42579. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42580. return 0;
  42581. }
  42582. var i0 = this._wrapPosition(this._pos - 1.0);
  42583. return this._samples[this._wrapPosition(i0 - i)];
  42584. };
  42585. /**
  42586. * Returns true if enough samples have been taken to completely fill the sliding window
  42587. * @return true if sample-set saturated
  42588. */
  42589. RollingAverage.prototype.isSaturated = function () {
  42590. return this._sampleCount >= this._samples.length;
  42591. };
  42592. /**
  42593. * Resets the rolling average (equivalent to 0 samples taken so far)
  42594. */
  42595. RollingAverage.prototype.reset = function () {
  42596. this.average = 0;
  42597. this.variance = 0;
  42598. this._sampleCount = 0;
  42599. this._pos = 0;
  42600. this._m2 = 0;
  42601. };
  42602. /**
  42603. * Wraps a value around the sample range boundaries
  42604. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42605. * @return Wrapped position in sample range
  42606. */
  42607. RollingAverage.prototype._wrapPosition = function (i) {
  42608. var max = this._samples.length;
  42609. return ((i % max) + max) % max;
  42610. };
  42611. return RollingAverage;
  42612. }());
  42613. BABYLON.RollingAverage = RollingAverage;
  42614. })(BABYLON || (BABYLON = {}));
  42615. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42616. var BABYLON;
  42617. (function (BABYLON) {
  42618. /**
  42619. * "Static Class" containing the most commonly used helper while dealing with material for
  42620. * rendering purpose.
  42621. *
  42622. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42623. *
  42624. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42625. */
  42626. var MaterialHelper = /** @class */ (function () {
  42627. function MaterialHelper() {
  42628. }
  42629. /**
  42630. * Bind the current view position to an effect.
  42631. * @param effect The effect to be bound
  42632. * @param scene The scene the eyes position is used from
  42633. */
  42634. MaterialHelper.BindEyePosition = function (effect, scene) {
  42635. if (scene._forcedViewPosition) {
  42636. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42637. return;
  42638. }
  42639. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42640. };
  42641. /**
  42642. * Helps preparing the defines values about the UVs in used in the effect.
  42643. * UVs are shared as much as we can accross channels in the shaders.
  42644. * @param texture The texture we are preparing the UVs for
  42645. * @param defines The defines to update
  42646. * @param key The channel key "diffuse", "specular"... used in the shader
  42647. */
  42648. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42649. defines._needUVs = true;
  42650. defines[key] = true;
  42651. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  42652. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42653. if (texture.coordinatesIndex === 0) {
  42654. defines["MAINUV1"] = true;
  42655. }
  42656. else {
  42657. defines["MAINUV2"] = true;
  42658. }
  42659. }
  42660. else {
  42661. defines[key + "DIRECTUV"] = 0;
  42662. }
  42663. };
  42664. /**
  42665. * Binds a texture matrix value to its corrsponding uniform
  42666. * @param texture The texture to bind the matrix for
  42667. * @param uniformBuffer The uniform buffer receivin the data
  42668. * @param key The channel key "diffuse", "specular"... used in the shader
  42669. */
  42670. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42671. var matrix = texture.getTextureMatrix();
  42672. if (!matrix.isIdentityAs3x2()) {
  42673. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42674. }
  42675. };
  42676. /**
  42677. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42678. * @param mesh defines the current mesh
  42679. * @param scene defines the current scene
  42680. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42681. * @param pointsCloud defines if point cloud rendering has to be turned on
  42682. * @param fogEnabled defines if fog has to be turned on
  42683. * @param alphaTest defines if alpha testing has to be turned on
  42684. * @param defines defines the current list of defines
  42685. */
  42686. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42687. if (defines._areMiscDirty) {
  42688. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42689. defines["POINTSIZE"] = pointsCloud;
  42690. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42691. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42692. defines["ALPHATEST"] = alphaTest;
  42693. }
  42694. };
  42695. /**
  42696. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42697. * @param scene defines the current scene
  42698. * @param engine defines the current engine
  42699. * @param defines specifies the list of active defines
  42700. * @param useInstances defines if instances have to be turned on
  42701. * @param useClipPlane defines if clip plane have to be turned on
  42702. */
  42703. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42704. if (useClipPlane === void 0) { useClipPlane = null; }
  42705. var changed = false;
  42706. var useClipPlane1 = false;
  42707. var useClipPlane2 = false;
  42708. var useClipPlane3 = false;
  42709. var useClipPlane4 = false;
  42710. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42711. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42712. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42713. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42714. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42715. defines["CLIPPLANE"] = useClipPlane1;
  42716. changed = true;
  42717. }
  42718. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42719. defines["CLIPPLANE2"] = useClipPlane2;
  42720. changed = true;
  42721. }
  42722. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42723. defines["CLIPPLANE3"] = useClipPlane3;
  42724. changed = true;
  42725. }
  42726. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42727. defines["CLIPPLANE4"] = useClipPlane4;
  42728. changed = true;
  42729. }
  42730. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42731. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42732. changed = true;
  42733. }
  42734. if (defines["INSTANCES"] !== useInstances) {
  42735. defines["INSTANCES"] = useInstances;
  42736. changed = true;
  42737. }
  42738. if (changed) {
  42739. defines.markAsUnprocessed();
  42740. }
  42741. };
  42742. /**
  42743. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42744. * @param mesh The mesh containing the geometry data we will draw
  42745. * @param defines The defines to update
  42746. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42747. * @param useBones Precise whether bones should be used or not (override mesh info)
  42748. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42749. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42750. * @returns false if defines are considered not dirty and have not been checked
  42751. */
  42752. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42753. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42754. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42755. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42756. return false;
  42757. }
  42758. defines._normals = defines._needNormals;
  42759. defines._uvs = defines._needUVs;
  42760. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42761. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42762. defines["TANGENT"] = true;
  42763. }
  42764. if (defines._needUVs) {
  42765. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42766. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42767. }
  42768. else {
  42769. defines["UV1"] = false;
  42770. defines["UV2"] = false;
  42771. }
  42772. if (useVertexColor) {
  42773. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42774. defines["VERTEXCOLOR"] = hasVertexColors;
  42775. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42776. }
  42777. if (useBones) {
  42778. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42779. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42780. var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  42781. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  42782. defines["BONETEXTURE"] = true;
  42783. }
  42784. else {
  42785. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42786. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  42787. }
  42788. }
  42789. else {
  42790. defines["NUM_BONE_INFLUENCERS"] = 0;
  42791. defines["BonesPerMesh"] = 0;
  42792. }
  42793. }
  42794. if (useMorphTargets) {
  42795. var manager = mesh.morphTargetManager;
  42796. if (manager) {
  42797. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42798. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42799. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42800. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42801. }
  42802. else {
  42803. defines["MORPHTARGETS_TANGENT"] = false;
  42804. defines["MORPHTARGETS_NORMAL"] = false;
  42805. defines["MORPHTARGETS"] = false;
  42806. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42807. }
  42808. }
  42809. return true;
  42810. };
  42811. /**
  42812. * Prepares the defines related to the light information passed in parameter
  42813. * @param scene The scene we are intending to draw
  42814. * @param mesh The mesh the effect is compiling for
  42815. * @param defines The defines to update
  42816. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42817. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42818. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42819. * @returns true if normals will be required for the rest of the effect
  42820. */
  42821. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42822. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42823. if (disableLighting === void 0) { disableLighting = false; }
  42824. if (!defines._areLightsDirty) {
  42825. return defines._needNormals;
  42826. }
  42827. var lightIndex = 0;
  42828. var needNormals = false;
  42829. var needRebuild = false;
  42830. var lightmapMode = false;
  42831. var shadowEnabled = false;
  42832. var specularEnabled = false;
  42833. if (scene.lightsEnabled && !disableLighting) {
  42834. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42835. var light = _a[_i];
  42836. needNormals = true;
  42837. if (defines["LIGHT" + lightIndex] === undefined) {
  42838. needRebuild = true;
  42839. }
  42840. defines["LIGHT" + lightIndex] = true;
  42841. defines["SPOTLIGHT" + lightIndex] = false;
  42842. defines["HEMILIGHT" + lightIndex] = false;
  42843. defines["POINTLIGHT" + lightIndex] = false;
  42844. defines["DIRLIGHT" + lightIndex] = false;
  42845. light.prepareLightSpecificDefines(defines, lightIndex);
  42846. // FallOff.
  42847. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42848. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42849. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42850. switch (light.falloffType) {
  42851. case BABYLON.Light.FALLOFF_GLTF:
  42852. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42853. break;
  42854. case BABYLON.Light.FALLOFF_PHYSICAL:
  42855. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42856. break;
  42857. case BABYLON.Light.FALLOFF_STANDARD:
  42858. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42859. break;
  42860. }
  42861. // Specular
  42862. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42863. specularEnabled = true;
  42864. }
  42865. // Shadows
  42866. defines["SHADOW" + lightIndex] = false;
  42867. defines["SHADOWPCF" + lightIndex] = false;
  42868. defines["SHADOWPCSS" + lightIndex] = false;
  42869. defines["SHADOWPOISSON" + lightIndex] = false;
  42870. defines["SHADOWESM" + lightIndex] = false;
  42871. defines["SHADOWCUBE" + lightIndex] = false;
  42872. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42873. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42874. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42875. var shadowGenerator = light.getShadowGenerator();
  42876. if (shadowGenerator) {
  42877. var shadowMap = shadowGenerator.getShadowMap();
  42878. if (shadowMap) {
  42879. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42880. shadowEnabled = true;
  42881. shadowGenerator.prepareDefines(defines, lightIndex);
  42882. }
  42883. }
  42884. }
  42885. }
  42886. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42887. lightmapMode = true;
  42888. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42889. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42890. }
  42891. else {
  42892. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42893. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42894. }
  42895. lightIndex++;
  42896. if (lightIndex === maxSimultaneousLights) {
  42897. break;
  42898. }
  42899. }
  42900. }
  42901. defines["SPECULARTERM"] = specularEnabled;
  42902. defines["SHADOWS"] = shadowEnabled;
  42903. // Resetting all other lights if any
  42904. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42905. if (defines["LIGHT" + index] !== undefined) {
  42906. defines["LIGHT" + index] = false;
  42907. defines["HEMILIGHT" + lightIndex] = false;
  42908. defines["POINTLIGHT" + lightIndex] = false;
  42909. defines["DIRLIGHT" + lightIndex] = false;
  42910. defines["SPOTLIGHT" + lightIndex] = false;
  42911. defines["SHADOW" + lightIndex] = false;
  42912. }
  42913. }
  42914. var caps = scene.getEngine().getCaps();
  42915. if (defines["SHADOWFLOAT"] === undefined) {
  42916. needRebuild = true;
  42917. }
  42918. defines["SHADOWFLOAT"] = shadowEnabled &&
  42919. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42920. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42921. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42922. if (needRebuild) {
  42923. defines.rebuild();
  42924. }
  42925. return needNormals;
  42926. };
  42927. /**
  42928. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42929. * that won t be acctive due to defines being turned off.
  42930. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42931. * @param samplersList The samplers list
  42932. * @param defines The defines helping in the list generation
  42933. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42934. */
  42935. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42936. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42937. var uniformsList;
  42938. var uniformBuffersList = null;
  42939. if (uniformsListOrOptions.uniformsNames) {
  42940. var options = uniformsListOrOptions;
  42941. uniformsList = options.uniformsNames;
  42942. uniformBuffersList = options.uniformBuffersNames;
  42943. samplersList = options.samplers;
  42944. defines = options.defines;
  42945. maxSimultaneousLights = options.maxSimultaneousLights;
  42946. }
  42947. else {
  42948. uniformsList = uniformsListOrOptions;
  42949. if (!samplersList) {
  42950. samplersList = [];
  42951. }
  42952. }
  42953. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42954. if (!defines["LIGHT" + lightIndex]) {
  42955. break;
  42956. }
  42957. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42958. if (uniformBuffersList) {
  42959. uniformBuffersList.push("Light" + lightIndex);
  42960. }
  42961. samplersList.push("shadowSampler" + lightIndex);
  42962. samplersList.push("depthSampler" + lightIndex);
  42963. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42964. samplersList.push("projectionLightSampler" + lightIndex);
  42965. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42966. }
  42967. }
  42968. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42969. uniformsList.push("morphTargetInfluences");
  42970. }
  42971. };
  42972. /**
  42973. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42974. * @param defines The defines to update while falling back
  42975. * @param fallbacks The authorized effect fallbacks
  42976. * @param maxSimultaneousLights The maximum number of lights allowed
  42977. * @param rank the current rank of the Effect
  42978. * @returns The newly affected rank
  42979. */
  42980. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42981. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42982. if (rank === void 0) { rank = 0; }
  42983. var lightFallbackRank = 0;
  42984. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42985. if (!defines["LIGHT" + lightIndex]) {
  42986. break;
  42987. }
  42988. if (lightIndex > 0) {
  42989. lightFallbackRank = rank + lightIndex;
  42990. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42991. }
  42992. if (!defines["SHADOWS"]) {
  42993. if (defines["SHADOW" + lightIndex]) {
  42994. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42995. }
  42996. if (defines["SHADOWPCF" + lightIndex]) {
  42997. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42998. }
  42999. if (defines["SHADOWPCSS" + lightIndex]) {
  43000. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  43001. }
  43002. if (defines["SHADOWPOISSON" + lightIndex]) {
  43003. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  43004. }
  43005. if (defines["SHADOWESM" + lightIndex]) {
  43006. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43007. }
  43008. }
  43009. }
  43010. return lightFallbackRank++;
  43011. };
  43012. /**
  43013. * Prepares the list of attributes required for morph targets according to the effect defines.
  43014. * @param attribs The current list of supported attribs
  43015. * @param mesh The mesh to prepare the morph targets attributes for
  43016. * @param defines The current Defines of the effect
  43017. */
  43018. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43019. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43020. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43021. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43022. var manager = mesh.morphTargetManager;
  43023. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43024. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43025. for (var index = 0; index < influencers; index++) {
  43026. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43027. if (normal) {
  43028. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43029. }
  43030. if (tangent) {
  43031. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43032. }
  43033. if (attribs.length > maxAttributesCount) {
  43034. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43035. }
  43036. }
  43037. }
  43038. };
  43039. /**
  43040. * Prepares the list of attributes required for bones according to the effect defines.
  43041. * @param attribs The current list of supported attribs
  43042. * @param mesh The mesh to prepare the bones attributes for
  43043. * @param defines The current Defines of the effect
  43044. * @param fallbacks The current efffect fallback strategy
  43045. */
  43046. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43047. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43048. fallbacks.addCPUSkinningFallback(0, mesh);
  43049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43051. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43054. }
  43055. }
  43056. };
  43057. /**
  43058. * Prepares the list of attributes required for instances according to the effect defines.
  43059. * @param attribs The current list of supported attribs
  43060. * @param defines The current Defines of the effect
  43061. */
  43062. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43063. if (defines["INSTANCES"]) {
  43064. attribs.push("world0");
  43065. attribs.push("world1");
  43066. attribs.push("world2");
  43067. attribs.push("world3");
  43068. }
  43069. };
  43070. /**
  43071. * Binds the light shadow information to the effect for the given mesh.
  43072. * @param light The light containing the generator
  43073. * @param scene The scene the lights belongs to
  43074. * @param mesh The mesh we are binding the information to render
  43075. * @param lightIndex The light index in the effect used to render the mesh
  43076. * @param effect The effect we are binding the data to
  43077. */
  43078. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43079. if (light.shadowEnabled && mesh.receiveShadows) {
  43080. var shadowGenerator = light.getShadowGenerator();
  43081. if (shadowGenerator) {
  43082. shadowGenerator.bindShadowLight(lightIndex, effect);
  43083. }
  43084. }
  43085. };
  43086. /**
  43087. * Binds the light information to the effect.
  43088. * @param light The light containing the generator
  43089. * @param effect The effect we are binding the data to
  43090. * @param lightIndex The light index in the effect used to render
  43091. */
  43092. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43093. light.transferToEffect(effect, lightIndex + "");
  43094. };
  43095. /**
  43096. * Binds the lights information from the scene to the effect for the given mesh.
  43097. * @param scene The scene the lights belongs to
  43098. * @param mesh The mesh we are binding the information to render
  43099. * @param effect The effect we are binding the data to
  43100. * @param defines The generated defines for the effect
  43101. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43102. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43103. */
  43104. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43105. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43106. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43107. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43108. for (var i = 0; i < len; i++) {
  43109. var light = mesh._lightSources[i];
  43110. var iAsString = i.toString();
  43111. var scaledIntensity = light.getScaledIntensity();
  43112. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43113. MaterialHelper.BindLightProperties(light, effect, i);
  43114. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43115. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43116. if (defines["SPECULARTERM"]) {
  43117. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43118. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43119. }
  43120. // Shadows
  43121. if (scene.shadowsEnabled) {
  43122. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43123. }
  43124. light._uniformBuffer.update();
  43125. }
  43126. };
  43127. /**
  43128. * Binds the fog information from the scene to the effect for the given mesh.
  43129. * @param scene The scene the lights belongs to
  43130. * @param mesh The mesh we are binding the information to render
  43131. * @param effect The effect we are binding the data to
  43132. * @param linearSpace Defines if the fog effect is applied in linear space
  43133. */
  43134. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43135. if (linearSpace === void 0) { linearSpace = false; }
  43136. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43137. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43138. // Convert fog color to linear space if used in a linear space computed shader.
  43139. if (linearSpace) {
  43140. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43141. effect.setColor3("vFogColor", this._tempFogColor);
  43142. }
  43143. else {
  43144. effect.setColor3("vFogColor", scene.fogColor);
  43145. }
  43146. }
  43147. };
  43148. /**
  43149. * Binds the bones information from the mesh to the effect.
  43150. * @param mesh The mesh we are binding the information to render
  43151. * @param effect The effect we are binding the data to
  43152. */
  43153. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43154. if (!effect || !mesh) {
  43155. return;
  43156. }
  43157. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43158. mesh.computeBonesUsingShaders = false;
  43159. }
  43160. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43161. var skeleton = mesh.skeleton;
  43162. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  43163. var boneTexture = skeleton.getTransformMatrixTexture();
  43164. effect.setTexture("boneSampler", boneTexture);
  43165. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  43166. }
  43167. else {
  43168. var matrices = skeleton.getTransformMatrices(mesh);
  43169. if (matrices) {
  43170. effect.setMatrices("mBones", matrices);
  43171. }
  43172. }
  43173. }
  43174. };
  43175. /**
  43176. * Binds the morph targets information from the mesh to the effect.
  43177. * @param abstractMesh The mesh we are binding the information to render
  43178. * @param effect The effect we are binding the data to
  43179. */
  43180. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43181. var manager = abstractMesh.morphTargetManager;
  43182. if (!abstractMesh || !manager) {
  43183. return;
  43184. }
  43185. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43186. };
  43187. /**
  43188. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43189. * @param defines The generated defines used in the effect
  43190. * @param effect The effect we are binding the data to
  43191. * @param scene The scene we are willing to render with logarithmic scale for
  43192. */
  43193. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43194. if (defines["LOGARITHMICDEPTH"]) {
  43195. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43196. }
  43197. };
  43198. /**
  43199. * Binds the clip plane information from the scene to the effect.
  43200. * @param scene The scene the clip plane information are extracted from
  43201. * @param effect The effect we are binding the data to
  43202. */
  43203. MaterialHelper.BindClipPlane = function (effect, scene) {
  43204. if (scene.clipPlane) {
  43205. var clipPlane = scene.clipPlane;
  43206. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43207. }
  43208. if (scene.clipPlane2) {
  43209. var clipPlane = scene.clipPlane2;
  43210. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43211. }
  43212. if (scene.clipPlane3) {
  43213. var clipPlane = scene.clipPlane3;
  43214. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43215. }
  43216. if (scene.clipPlane4) {
  43217. var clipPlane = scene.clipPlane4;
  43218. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43219. }
  43220. };
  43221. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43222. return MaterialHelper;
  43223. }());
  43224. BABYLON.MaterialHelper = MaterialHelper;
  43225. })(BABYLON || (BABYLON = {}));
  43226. //# sourceMappingURL=babylon.materialHelper.js.map
  43227. var BABYLON;
  43228. (function (BABYLON) {
  43229. /**
  43230. * Base class of materials working in push mode in babylon JS
  43231. * @hidden
  43232. */
  43233. var PushMaterial = /** @class */ (function (_super) {
  43234. __extends(PushMaterial, _super);
  43235. function PushMaterial(name, scene) {
  43236. var _this = _super.call(this, name, scene) || this;
  43237. _this._normalMatrix = new BABYLON.Matrix();
  43238. /**
  43239. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43240. * This means that the material can keep using a previous shader while a new one is being compiled.
  43241. * This is mostly used when shader parallel compilation is supported (true by default)
  43242. */
  43243. _this.allowShaderHotSwapping = true;
  43244. _this._storeEffectOnSubMeshes = true;
  43245. return _this;
  43246. }
  43247. PushMaterial.prototype.getEffect = function () {
  43248. return this._activeEffect;
  43249. };
  43250. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43251. if (!mesh) {
  43252. return false;
  43253. }
  43254. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43255. return true;
  43256. }
  43257. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43258. };
  43259. /**
  43260. * Binds the given world matrix to the active effect
  43261. *
  43262. * @param world the matrix to bind
  43263. */
  43264. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43265. this._activeEffect.setMatrix("world", world);
  43266. };
  43267. /**
  43268. * Binds the given normal matrix to the active effect
  43269. *
  43270. * @param normalMatrix the matrix to bind
  43271. */
  43272. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43273. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43274. };
  43275. PushMaterial.prototype.bind = function (world, mesh) {
  43276. if (!mesh) {
  43277. return;
  43278. }
  43279. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43280. };
  43281. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43282. if (effect === void 0) { effect = null; }
  43283. _super.prototype._afterBind.call(this, mesh);
  43284. this.getScene()._cachedEffect = effect;
  43285. };
  43286. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43287. if (visibility === void 0) { visibility = 1; }
  43288. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43289. };
  43290. return PushMaterial;
  43291. }(BABYLON.Material));
  43292. BABYLON.PushMaterial = PushMaterial;
  43293. })(BABYLON || (BABYLON = {}));
  43294. //# sourceMappingURL=babylon.pushMaterial.js.map
  43295. var BABYLON;
  43296. (function (BABYLON) {
  43297. /** @hidden */
  43298. var StandardMaterialDefines = /** @class */ (function (_super) {
  43299. __extends(StandardMaterialDefines, _super);
  43300. function StandardMaterialDefines() {
  43301. var _this = _super.call(this) || this;
  43302. _this.MAINUV1 = false;
  43303. _this.MAINUV2 = false;
  43304. _this.DIFFUSE = false;
  43305. _this.DIFFUSEDIRECTUV = 0;
  43306. _this.AMBIENT = false;
  43307. _this.AMBIENTDIRECTUV = 0;
  43308. _this.OPACITY = false;
  43309. _this.OPACITYDIRECTUV = 0;
  43310. _this.OPACITYRGB = false;
  43311. _this.REFLECTION = false;
  43312. _this.EMISSIVE = false;
  43313. _this.EMISSIVEDIRECTUV = 0;
  43314. _this.SPECULAR = false;
  43315. _this.SPECULARDIRECTUV = 0;
  43316. _this.BUMP = false;
  43317. _this.BUMPDIRECTUV = 0;
  43318. _this.PARALLAX = false;
  43319. _this.PARALLAXOCCLUSION = false;
  43320. _this.SPECULAROVERALPHA = false;
  43321. _this.CLIPPLANE = false;
  43322. _this.CLIPPLANE2 = false;
  43323. _this.CLIPPLANE3 = false;
  43324. _this.CLIPPLANE4 = false;
  43325. _this.ALPHATEST = false;
  43326. _this.DEPTHPREPASS = false;
  43327. _this.ALPHAFROMDIFFUSE = false;
  43328. _this.POINTSIZE = false;
  43329. _this.FOG = false;
  43330. _this.SPECULARTERM = false;
  43331. _this.DIFFUSEFRESNEL = false;
  43332. _this.OPACITYFRESNEL = false;
  43333. _this.REFLECTIONFRESNEL = false;
  43334. _this.REFRACTIONFRESNEL = false;
  43335. _this.EMISSIVEFRESNEL = false;
  43336. _this.FRESNEL = false;
  43337. _this.NORMAL = false;
  43338. _this.UV1 = false;
  43339. _this.UV2 = false;
  43340. _this.VERTEXCOLOR = false;
  43341. _this.VERTEXALPHA = false;
  43342. _this.NUM_BONE_INFLUENCERS = 0;
  43343. _this.BonesPerMesh = 0;
  43344. _this.BONETEXTURE = false;
  43345. _this.INSTANCES = false;
  43346. _this.GLOSSINESS = false;
  43347. _this.ROUGHNESS = false;
  43348. _this.EMISSIVEASILLUMINATION = false;
  43349. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43350. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43351. _this.LIGHTMAP = false;
  43352. _this.LIGHTMAPDIRECTUV = 0;
  43353. _this.OBJECTSPACE_NORMALMAP = false;
  43354. _this.USELIGHTMAPASSHADOWMAP = false;
  43355. _this.REFLECTIONMAP_3D = false;
  43356. _this.REFLECTIONMAP_SPHERICAL = false;
  43357. _this.REFLECTIONMAP_PLANAR = false;
  43358. _this.REFLECTIONMAP_CUBIC = false;
  43359. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43360. _this.REFLECTIONMAP_PROJECTION = false;
  43361. _this.REFLECTIONMAP_SKYBOX = false;
  43362. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43363. _this.REFLECTIONMAP_EXPLICIT = false;
  43364. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43365. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43366. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43367. _this.INVERTCUBICMAP = false;
  43368. _this.LOGARITHMICDEPTH = false;
  43369. _this.REFRACTION = false;
  43370. _this.REFRACTIONMAP_3D = false;
  43371. _this.REFLECTIONOVERALPHA = false;
  43372. _this.TWOSIDEDLIGHTING = false;
  43373. _this.SHADOWFLOAT = false;
  43374. _this.MORPHTARGETS = false;
  43375. _this.MORPHTARGETS_NORMAL = false;
  43376. _this.MORPHTARGETS_TANGENT = false;
  43377. _this.NUM_MORPH_INFLUENCERS = 0;
  43378. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43379. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43380. _this.IMAGEPROCESSING = false;
  43381. _this.VIGNETTE = false;
  43382. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43383. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43384. _this.TONEMAPPING = false;
  43385. _this.TONEMAPPING_ACES = false;
  43386. _this.CONTRAST = false;
  43387. _this.COLORCURVES = false;
  43388. _this.COLORGRADING = false;
  43389. _this.COLORGRADING3D = false;
  43390. _this.SAMPLER3DGREENDEPTH = false;
  43391. _this.SAMPLER3DBGRMAP = false;
  43392. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43393. /**
  43394. * If the reflection texture on this material is in linear color space
  43395. * @hidden
  43396. */
  43397. _this.IS_REFLECTION_LINEAR = false;
  43398. /**
  43399. * If the refraction texture on this material is in linear color space
  43400. * @hidden
  43401. */
  43402. _this.IS_REFRACTION_LINEAR = false;
  43403. _this.EXPOSURE = false;
  43404. _this.rebuild();
  43405. return _this;
  43406. }
  43407. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43408. var modes = [
  43409. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43410. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43411. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43412. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43413. ];
  43414. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43415. var mode = modes_1[_i];
  43416. this[mode] = (mode === modeToEnable);
  43417. }
  43418. };
  43419. return StandardMaterialDefines;
  43420. }(BABYLON.MaterialDefines));
  43421. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43422. /**
  43423. * This is the default material used in Babylon. It is the best trade off between quality
  43424. * and performances.
  43425. * @see http://doc.babylonjs.com/babylon101/materials
  43426. */
  43427. var StandardMaterial = /** @class */ (function (_super) {
  43428. __extends(StandardMaterial, _super);
  43429. /**
  43430. * Instantiates a new standard material.
  43431. * This is the default material used in Babylon. It is the best trade off between quality
  43432. * and performances.
  43433. * @see http://doc.babylonjs.com/babylon101/materials
  43434. * @param name Define the name of the material in the scene
  43435. * @param scene Define the scene the material belong to
  43436. */
  43437. function StandardMaterial(name, scene) {
  43438. var _this = _super.call(this, name, scene) || this;
  43439. /**
  43440. * The color of the material lit by the environmental background lighting.
  43441. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43442. */
  43443. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43444. /**
  43445. * The basic color of the material as viewed under a light.
  43446. */
  43447. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43448. /**
  43449. * Define how the color and intensity of the highlight given by the light in the material.
  43450. */
  43451. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43452. /**
  43453. * Define the color of the material as if self lit.
  43454. * This will be mixed in the final result even in the absence of light.
  43455. */
  43456. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43457. /**
  43458. * Defines how sharp are the highlights in the material.
  43459. * The bigger the value the sharper giving a more glossy feeling to the result.
  43460. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43461. */
  43462. _this.specularPower = 64;
  43463. _this._useAlphaFromDiffuseTexture = false;
  43464. _this._useEmissiveAsIllumination = false;
  43465. _this._linkEmissiveWithDiffuse = false;
  43466. _this._useSpecularOverAlpha = false;
  43467. _this._useReflectionOverAlpha = false;
  43468. _this._disableLighting = false;
  43469. _this._useObjectSpaceNormalMap = false;
  43470. _this._useParallax = false;
  43471. _this._useParallaxOcclusion = false;
  43472. /**
  43473. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  43474. */
  43475. _this.parallaxScaleBias = 0.05;
  43476. _this._roughness = 0;
  43477. /**
  43478. * In case of refraction, define the value of the indice of refraction.
  43479. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43480. */
  43481. _this.indexOfRefraction = 0.98;
  43482. /**
  43483. * Invert the refraction texture alongside the y axis.
  43484. * It can be usefull with procedural textures or probe for instance.
  43485. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43486. */
  43487. _this.invertRefractionY = true;
  43488. /**
  43489. * Defines the alpha limits in alpha test mode.
  43490. */
  43491. _this.alphaCutOff = 0.4;
  43492. _this._useLightmapAsShadowmap = false;
  43493. _this._useReflectionFresnelFromSpecular = false;
  43494. _this._useGlossinessFromSpecularMapAlpha = false;
  43495. _this._maxSimultaneousLights = 4;
  43496. _this._invertNormalMapX = false;
  43497. _this._invertNormalMapY = false;
  43498. _this._twoSidedLighting = false;
  43499. _this._renderTargets = new BABYLON.SmartArray(16);
  43500. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43501. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43502. // Setup the default processing configuration to the scene.
  43503. _this._attachImageProcessingConfiguration(null);
  43504. _this.getRenderTargetTextures = function () {
  43505. _this._renderTargets.reset();
  43506. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43507. _this._renderTargets.push(_this._reflectionTexture);
  43508. }
  43509. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43510. _this._renderTargets.push(_this._refractionTexture);
  43511. }
  43512. return _this._renderTargets;
  43513. };
  43514. return _this;
  43515. }
  43516. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43517. /**
  43518. * Gets the image processing configuration used either in this material.
  43519. */
  43520. get: function () {
  43521. return this._imageProcessingConfiguration;
  43522. },
  43523. /**
  43524. * Sets the Default image processing configuration used either in the this material.
  43525. *
  43526. * If sets to null, the scene one is in use.
  43527. */
  43528. set: function (value) {
  43529. this._attachImageProcessingConfiguration(value);
  43530. // Ensure the effect will be rebuilt.
  43531. this._markAllSubMeshesAsTexturesDirty();
  43532. },
  43533. enumerable: true,
  43534. configurable: true
  43535. });
  43536. /**
  43537. * Attaches a new image processing configuration to the Standard Material.
  43538. * @param configuration
  43539. */
  43540. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43541. var _this = this;
  43542. if (configuration === this._imageProcessingConfiguration) {
  43543. return;
  43544. }
  43545. // Detaches observer.
  43546. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43547. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43548. }
  43549. // Pick the scene configuration if needed.
  43550. if (!configuration) {
  43551. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43552. }
  43553. else {
  43554. this._imageProcessingConfiguration = configuration;
  43555. }
  43556. // Attaches observer.
  43557. if (this._imageProcessingConfiguration) {
  43558. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43559. _this._markAllSubMeshesAsImageProcessingDirty();
  43560. });
  43561. }
  43562. };
  43563. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43564. /**
  43565. * Gets wether the color curves effect is enabled.
  43566. */
  43567. get: function () {
  43568. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43569. },
  43570. /**
  43571. * Sets wether the color curves effect is enabled.
  43572. */
  43573. set: function (value) {
  43574. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43575. },
  43576. enumerable: true,
  43577. configurable: true
  43578. });
  43579. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43580. /**
  43581. * Gets wether the color grading effect is enabled.
  43582. */
  43583. get: function () {
  43584. return this.imageProcessingConfiguration.colorGradingEnabled;
  43585. },
  43586. /**
  43587. * Gets wether the color grading effect is enabled.
  43588. */
  43589. set: function (value) {
  43590. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43591. },
  43592. enumerable: true,
  43593. configurable: true
  43594. });
  43595. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43596. /**
  43597. * Gets wether tonemapping is enabled or not.
  43598. */
  43599. get: function () {
  43600. return this._imageProcessingConfiguration.toneMappingEnabled;
  43601. },
  43602. /**
  43603. * Sets wether tonemapping is enabled or not
  43604. */
  43605. set: function (value) {
  43606. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43607. },
  43608. enumerable: true,
  43609. configurable: true
  43610. });
  43611. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43612. /**
  43613. * The camera exposure used on this material.
  43614. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43615. * This corresponds to a photographic exposure.
  43616. */
  43617. get: function () {
  43618. return this._imageProcessingConfiguration.exposure;
  43619. },
  43620. /**
  43621. * The camera exposure used on this material.
  43622. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43623. * This corresponds to a photographic exposure.
  43624. */
  43625. set: function (value) {
  43626. this._imageProcessingConfiguration.exposure = value;
  43627. },
  43628. enumerable: true,
  43629. configurable: true
  43630. });
  43631. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43632. /**
  43633. * Gets The camera contrast used on this material.
  43634. */
  43635. get: function () {
  43636. return this._imageProcessingConfiguration.contrast;
  43637. },
  43638. /**
  43639. * Sets The camera contrast used on this material.
  43640. */
  43641. set: function (value) {
  43642. this._imageProcessingConfiguration.contrast = value;
  43643. },
  43644. enumerable: true,
  43645. configurable: true
  43646. });
  43647. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43648. /**
  43649. * Gets the Color Grading 2D Lookup Texture.
  43650. */
  43651. get: function () {
  43652. return this._imageProcessingConfiguration.colorGradingTexture;
  43653. },
  43654. /**
  43655. * Sets the Color Grading 2D Lookup Texture.
  43656. */
  43657. set: function (value) {
  43658. this._imageProcessingConfiguration.colorGradingTexture = value;
  43659. },
  43660. enumerable: true,
  43661. configurable: true
  43662. });
  43663. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43664. /**
  43665. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43666. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43667. * 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;
  43668. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43669. */
  43670. get: function () {
  43671. return this._imageProcessingConfiguration.colorCurves;
  43672. },
  43673. /**
  43674. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43675. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43676. * 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;
  43677. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43678. */
  43679. set: function (value) {
  43680. this._imageProcessingConfiguration.colorCurves = value;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43686. /**
  43687. * Gets a boolean indicating that current material needs to register RTT
  43688. */
  43689. get: function () {
  43690. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43691. return true;
  43692. }
  43693. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43694. return true;
  43695. }
  43696. return false;
  43697. },
  43698. enumerable: true,
  43699. configurable: true
  43700. });
  43701. /**
  43702. * Gets the current class name of the material e.g. "StandardMaterial"
  43703. * Mainly use in serialization.
  43704. * @returns the class name
  43705. */
  43706. StandardMaterial.prototype.getClassName = function () {
  43707. return "StandardMaterial";
  43708. };
  43709. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43710. /**
  43711. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43712. * You can try switching to logarithmic depth.
  43713. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43714. */
  43715. get: function () {
  43716. return this._useLogarithmicDepth;
  43717. },
  43718. set: function (value) {
  43719. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43720. this._markAllSubMeshesAsMiscDirty();
  43721. },
  43722. enumerable: true,
  43723. configurable: true
  43724. });
  43725. /**
  43726. * Specifies if the material will require alpha blending
  43727. * @returns a boolean specifying if alpha blending is needed
  43728. */
  43729. StandardMaterial.prototype.needAlphaBlending = function () {
  43730. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43731. };
  43732. /**
  43733. * Specifies if this material should be rendered in alpha test mode
  43734. * @returns a boolean specifying if an alpha test is needed.
  43735. */
  43736. StandardMaterial.prototype.needAlphaTesting = function () {
  43737. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43738. };
  43739. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43740. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43741. };
  43742. /**
  43743. * Get the texture used for alpha test purpose.
  43744. * @returns the diffuse texture in case of the standard material.
  43745. */
  43746. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43747. return this._diffuseTexture;
  43748. };
  43749. /**
  43750. * Get if the submesh is ready to be used and all its information available.
  43751. * Child classes can use it to update shaders
  43752. * @param mesh defines the mesh to check
  43753. * @param subMesh defines which submesh to check
  43754. * @param useInstances specifies that instances should be used
  43755. * @returns a boolean indicating that the submesh is ready or not
  43756. */
  43757. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43758. if (useInstances === void 0) { useInstances = false; }
  43759. if (subMesh.effect && this.isFrozen) {
  43760. if (this._wasPreviouslyReady) {
  43761. return true;
  43762. }
  43763. }
  43764. if (!subMesh._materialDefines) {
  43765. subMesh._materialDefines = new StandardMaterialDefines();
  43766. }
  43767. var scene = this.getScene();
  43768. var defines = subMesh._materialDefines;
  43769. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43770. if (defines._renderId === scene.getRenderId()) {
  43771. return true;
  43772. }
  43773. }
  43774. var engine = scene.getEngine();
  43775. // Lights
  43776. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43777. // Textures
  43778. if (defines._areTexturesDirty) {
  43779. defines._needUVs = false;
  43780. defines.MAINUV1 = false;
  43781. defines.MAINUV2 = false;
  43782. if (scene.texturesEnabled) {
  43783. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43784. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43785. return false;
  43786. }
  43787. else {
  43788. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43789. }
  43790. }
  43791. else {
  43792. defines.DIFFUSE = false;
  43793. }
  43794. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43795. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43796. return false;
  43797. }
  43798. else {
  43799. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43800. }
  43801. }
  43802. else {
  43803. defines.AMBIENT = false;
  43804. }
  43805. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43806. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43807. return false;
  43808. }
  43809. else {
  43810. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43811. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43812. }
  43813. }
  43814. else {
  43815. defines.OPACITY = false;
  43816. }
  43817. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43818. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43819. return false;
  43820. }
  43821. else {
  43822. defines._needNormals = true;
  43823. defines.REFLECTION = true;
  43824. defines.ROUGHNESS = (this._roughness > 0);
  43825. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43826. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43827. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43828. switch (this._reflectionTexture.coordinatesMode) {
  43829. case BABYLON.Texture.EXPLICIT_MODE:
  43830. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43831. break;
  43832. case BABYLON.Texture.PLANAR_MODE:
  43833. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43834. break;
  43835. case BABYLON.Texture.PROJECTION_MODE:
  43836. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43837. break;
  43838. case BABYLON.Texture.SKYBOX_MODE:
  43839. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43840. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43841. break;
  43842. case BABYLON.Texture.SPHERICAL_MODE:
  43843. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43844. break;
  43845. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43846. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43847. break;
  43848. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43849. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43850. break;
  43851. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43852. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43853. break;
  43854. case BABYLON.Texture.CUBIC_MODE:
  43855. case BABYLON.Texture.INVCUBIC_MODE:
  43856. default:
  43857. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43858. break;
  43859. }
  43860. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43861. }
  43862. }
  43863. else {
  43864. defines.REFLECTION = false;
  43865. }
  43866. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43867. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43868. return false;
  43869. }
  43870. else {
  43871. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43872. }
  43873. }
  43874. else {
  43875. defines.EMISSIVE = false;
  43876. }
  43877. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43878. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43879. return false;
  43880. }
  43881. else {
  43882. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43883. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43884. }
  43885. }
  43886. else {
  43887. defines.LIGHTMAP = false;
  43888. }
  43889. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43890. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43891. return false;
  43892. }
  43893. else {
  43894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43895. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43896. }
  43897. }
  43898. else {
  43899. defines.SPECULAR = false;
  43900. }
  43901. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43902. // Bump texure can not be not blocking.
  43903. if (!this._bumpTexture.isReady()) {
  43904. return false;
  43905. }
  43906. else {
  43907. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43908. defines.PARALLAX = this._useParallax;
  43909. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43910. }
  43911. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43912. }
  43913. else {
  43914. defines.BUMP = false;
  43915. }
  43916. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43917. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43918. return false;
  43919. }
  43920. else {
  43921. defines._needUVs = true;
  43922. defines.REFRACTION = true;
  43923. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43924. }
  43925. }
  43926. else {
  43927. defines.REFRACTION = false;
  43928. }
  43929. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43930. }
  43931. else {
  43932. defines.DIFFUSE = false;
  43933. defines.AMBIENT = false;
  43934. defines.OPACITY = false;
  43935. defines.REFLECTION = false;
  43936. defines.EMISSIVE = false;
  43937. defines.LIGHTMAP = false;
  43938. defines.BUMP = false;
  43939. defines.REFRACTION = false;
  43940. }
  43941. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43942. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43943. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43944. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43945. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43946. }
  43947. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43948. if (!this._imageProcessingConfiguration.isReady()) {
  43949. return false;
  43950. }
  43951. this._imageProcessingConfiguration.prepareDefines(defines);
  43952. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43953. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43954. }
  43955. if (defines._areFresnelDirty) {
  43956. if (StandardMaterial.FresnelEnabled) {
  43957. // Fresnel
  43958. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43959. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43960. this._reflectionFresnelParameters) {
  43961. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43962. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43963. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43964. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43965. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43966. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43967. defines._needNormals = true;
  43968. defines.FRESNEL = true;
  43969. }
  43970. }
  43971. else {
  43972. defines.FRESNEL = false;
  43973. }
  43974. }
  43975. // Misc.
  43976. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43977. // Attribs
  43978. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43979. // Values that need to be evaluated on every frame
  43980. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43981. // Get correct effect
  43982. if (defines.isDirty) {
  43983. defines.markAsProcessed();
  43984. // Fallbacks
  43985. var fallbacks = new BABYLON.EffectFallbacks();
  43986. if (defines.REFLECTION) {
  43987. fallbacks.addFallback(0, "REFLECTION");
  43988. }
  43989. if (defines.SPECULAR) {
  43990. fallbacks.addFallback(0, "SPECULAR");
  43991. }
  43992. if (defines.BUMP) {
  43993. fallbacks.addFallback(0, "BUMP");
  43994. }
  43995. if (defines.PARALLAX) {
  43996. fallbacks.addFallback(1, "PARALLAX");
  43997. }
  43998. if (defines.PARALLAXOCCLUSION) {
  43999. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44000. }
  44001. if (defines.SPECULAROVERALPHA) {
  44002. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44003. }
  44004. if (defines.FOG) {
  44005. fallbacks.addFallback(1, "FOG");
  44006. }
  44007. if (defines.POINTSIZE) {
  44008. fallbacks.addFallback(0, "POINTSIZE");
  44009. }
  44010. if (defines.LOGARITHMICDEPTH) {
  44011. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44012. }
  44013. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44014. if (defines.SPECULARTERM) {
  44015. fallbacks.addFallback(0, "SPECULARTERM");
  44016. }
  44017. if (defines.DIFFUSEFRESNEL) {
  44018. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44019. }
  44020. if (defines.OPACITYFRESNEL) {
  44021. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44022. }
  44023. if (defines.REFLECTIONFRESNEL) {
  44024. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44025. }
  44026. if (defines.EMISSIVEFRESNEL) {
  44027. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44028. }
  44029. if (defines.FRESNEL) {
  44030. fallbacks.addFallback(4, "FRESNEL");
  44031. }
  44032. //Attributes
  44033. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44034. if (defines.NORMAL) {
  44035. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44036. }
  44037. if (defines.UV1) {
  44038. attribs.push(BABYLON.VertexBuffer.UVKind);
  44039. }
  44040. if (defines.UV2) {
  44041. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44042. }
  44043. if (defines.VERTEXCOLOR) {
  44044. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44045. }
  44046. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44047. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44048. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44049. var shaderName = "default";
  44050. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44051. "vFogInfos", "vFogColor", "pointSize",
  44052. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44053. "mBones",
  44054. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44055. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44056. "vReflectionPosition", "vReflectionSize",
  44057. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth"
  44058. ];
  44059. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler",
  44060. "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  44061. "refractionCubeSampler", "refraction2DSampler", "boneSampler"];
  44062. var uniformBuffers = ["Material", "Scene"];
  44063. if (BABYLON.ImageProcessingConfiguration) {
  44064. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44065. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44066. }
  44067. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44068. uniformsNames: uniforms,
  44069. uniformBuffersNames: uniformBuffers,
  44070. samplers: samplers,
  44071. defines: defines,
  44072. maxSimultaneousLights: this._maxSimultaneousLights
  44073. });
  44074. if (this.customShaderNameResolve) {
  44075. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44076. }
  44077. var join = defines.toString();
  44078. var previousEffect = subMesh.effect;
  44079. var effect = scene.getEngine().createEffect(shaderName, {
  44080. attributes: attribs,
  44081. uniformsNames: uniforms,
  44082. uniformBuffersNames: uniformBuffers,
  44083. samplers: samplers,
  44084. defines: join,
  44085. fallbacks: fallbacks,
  44086. onCompiled: this.onCompiled,
  44087. onError: this.onError,
  44088. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44089. }, engine);
  44090. if (effect) {
  44091. // Use previous effect while new one is compiling
  44092. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44093. effect = previousEffect;
  44094. defines.markAsUnprocessed();
  44095. }
  44096. else {
  44097. scene.resetCachedMaterial();
  44098. subMesh.setEffect(effect, defines);
  44099. this.buildUniformLayout();
  44100. }
  44101. }
  44102. }
  44103. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44104. return false;
  44105. }
  44106. defines._renderId = scene.getRenderId();
  44107. this._wasPreviouslyReady = true;
  44108. return true;
  44109. };
  44110. /**
  44111. * Builds the material UBO layouts.
  44112. * Used internally during the effect preparation.
  44113. */
  44114. StandardMaterial.prototype.buildUniformLayout = function () {
  44115. // Order is important !
  44116. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44117. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44118. this._uniformBuffer.addUniform("opacityParts", 4);
  44119. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44120. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44121. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44122. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44123. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44124. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44125. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44126. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44127. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44128. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44129. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44130. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44131. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44132. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44133. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44134. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44135. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44136. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44137. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44138. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44139. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44140. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44141. this._uniformBuffer.addUniform("specularMatrix", 16);
  44142. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44143. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44144. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44145. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44146. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44147. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44148. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44149. this._uniformBuffer.addUniform("pointSize", 1);
  44150. this._uniformBuffer.create();
  44151. };
  44152. /**
  44153. * Unbinds the material from the mesh
  44154. */
  44155. StandardMaterial.prototype.unbind = function () {
  44156. if (this._activeEffect) {
  44157. var needFlag = false;
  44158. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44159. this._activeEffect.setTexture("reflection2DSampler", null);
  44160. needFlag = true;
  44161. }
  44162. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44163. this._activeEffect.setTexture("refraction2DSampler", null);
  44164. needFlag = true;
  44165. }
  44166. if (needFlag) {
  44167. this._markAllSubMeshesAsTexturesDirty();
  44168. }
  44169. }
  44170. _super.prototype.unbind.call(this);
  44171. };
  44172. /**
  44173. * Binds the submesh to this material by preparing the effect and shader to draw
  44174. * @param world defines the world transformation matrix
  44175. * @param mesh defines the mesh containing the submesh
  44176. * @param subMesh defines the submesh to bind the material to
  44177. */
  44178. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44179. var scene = this.getScene();
  44180. var defines = subMesh._materialDefines;
  44181. if (!defines) {
  44182. return;
  44183. }
  44184. var effect = subMesh.effect;
  44185. if (!effect) {
  44186. return;
  44187. }
  44188. this._activeEffect = effect;
  44189. // Matrices
  44190. this.bindOnlyWorldMatrix(world);
  44191. // Normal Matrix
  44192. if (defines.OBJECTSPACE_NORMALMAP) {
  44193. world.toNormalMatrix(this._normalMatrix);
  44194. this.bindOnlyNormalMatrix(this._normalMatrix);
  44195. }
  44196. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44197. // Bones
  44198. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44199. if (mustRebind) {
  44200. this._uniformBuffer.bindToEffect(effect, "Material");
  44201. this.bindViewProjection(effect);
  44202. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44203. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44204. // Fresnel
  44205. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44206. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44207. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44208. }
  44209. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44210. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44211. }
  44212. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44213. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44214. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44215. }
  44216. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44217. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44218. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44219. }
  44220. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44221. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44222. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44223. }
  44224. }
  44225. // Textures
  44226. if (scene.texturesEnabled) {
  44227. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44228. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44229. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44230. if (this._diffuseTexture.hasAlpha) {
  44231. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44232. }
  44233. }
  44234. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44235. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44236. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44237. }
  44238. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44239. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44240. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44241. }
  44242. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44243. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44244. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44245. if (this._reflectionTexture.boundingBoxSize) {
  44246. var cubeTexture = this._reflectionTexture;
  44247. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44248. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44249. }
  44250. }
  44251. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44252. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44253. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44254. }
  44255. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44256. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44257. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44258. }
  44259. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44260. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44261. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44262. }
  44263. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44264. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44265. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44266. if (scene._mirroredCameraPosition) {
  44267. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44268. }
  44269. else {
  44270. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44271. }
  44272. }
  44273. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44274. var depth = 1.0;
  44275. if (!this._refractionTexture.isCube) {
  44276. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44277. if (this._refractionTexture.depth) {
  44278. depth = this._refractionTexture.depth;
  44279. }
  44280. }
  44281. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44282. }
  44283. }
  44284. // Point size
  44285. if (this.pointsCloud) {
  44286. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44287. }
  44288. if (defines.SPECULARTERM) {
  44289. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44290. }
  44291. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44292. // Diffuse
  44293. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44294. }
  44295. // Textures
  44296. if (scene.texturesEnabled) {
  44297. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44298. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44299. }
  44300. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44301. effect.setTexture("ambientSampler", this._ambientTexture);
  44302. }
  44303. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44304. effect.setTexture("opacitySampler", this._opacityTexture);
  44305. }
  44306. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44307. if (this._reflectionTexture.isCube) {
  44308. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44309. }
  44310. else {
  44311. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44312. }
  44313. }
  44314. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44315. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44316. }
  44317. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44318. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44319. }
  44320. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44321. effect.setTexture("specularSampler", this._specularTexture);
  44322. }
  44323. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44324. effect.setTexture("bumpSampler", this._bumpTexture);
  44325. }
  44326. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44327. var depth = 1.0;
  44328. if (this._refractionTexture.isCube) {
  44329. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44330. }
  44331. else {
  44332. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44333. }
  44334. }
  44335. }
  44336. // Clip plane
  44337. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44338. // Colors
  44339. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44340. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44341. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44342. }
  44343. if (mustRebind || !this.isFrozen) {
  44344. // Lights
  44345. if (scene.lightsEnabled && !this._disableLighting) {
  44346. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44347. }
  44348. // View
  44349. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44350. this.bindView(effect);
  44351. }
  44352. // Fog
  44353. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44354. // Morph targets
  44355. if (defines.NUM_MORPH_INFLUENCERS) {
  44356. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44357. }
  44358. // Log. depth
  44359. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44360. // image processing
  44361. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44362. this._imageProcessingConfiguration.bind(this._activeEffect);
  44363. }
  44364. }
  44365. this._uniformBuffer.update();
  44366. this._afterBind(mesh, this._activeEffect);
  44367. };
  44368. /**
  44369. * Get the list of animatables in the material.
  44370. * @returns the list of animatables object used in the material
  44371. */
  44372. StandardMaterial.prototype.getAnimatables = function () {
  44373. var results = [];
  44374. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44375. results.push(this._diffuseTexture);
  44376. }
  44377. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44378. results.push(this._ambientTexture);
  44379. }
  44380. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44381. results.push(this._opacityTexture);
  44382. }
  44383. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44384. results.push(this._reflectionTexture);
  44385. }
  44386. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44387. results.push(this._emissiveTexture);
  44388. }
  44389. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44390. results.push(this._specularTexture);
  44391. }
  44392. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44393. results.push(this._bumpTexture);
  44394. }
  44395. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44396. results.push(this._lightmapTexture);
  44397. }
  44398. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44399. results.push(this._refractionTexture);
  44400. }
  44401. return results;
  44402. };
  44403. /**
  44404. * Gets the active textures from the material
  44405. * @returns an array of textures
  44406. */
  44407. StandardMaterial.prototype.getActiveTextures = function () {
  44408. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44409. if (this._diffuseTexture) {
  44410. activeTextures.push(this._diffuseTexture);
  44411. }
  44412. if (this._ambientTexture) {
  44413. activeTextures.push(this._ambientTexture);
  44414. }
  44415. if (this._opacityTexture) {
  44416. activeTextures.push(this._opacityTexture);
  44417. }
  44418. if (this._reflectionTexture) {
  44419. activeTextures.push(this._reflectionTexture);
  44420. }
  44421. if (this._emissiveTexture) {
  44422. activeTextures.push(this._emissiveTexture);
  44423. }
  44424. if (this._specularTexture) {
  44425. activeTextures.push(this._specularTexture);
  44426. }
  44427. if (this._bumpTexture) {
  44428. activeTextures.push(this._bumpTexture);
  44429. }
  44430. if (this._lightmapTexture) {
  44431. activeTextures.push(this._lightmapTexture);
  44432. }
  44433. if (this._refractionTexture) {
  44434. activeTextures.push(this._refractionTexture);
  44435. }
  44436. return activeTextures;
  44437. };
  44438. /**
  44439. * Specifies if the material uses a texture
  44440. * @param texture defines the texture to check against the material
  44441. * @returns a boolean specifying if the material uses the texture
  44442. */
  44443. StandardMaterial.prototype.hasTexture = function (texture) {
  44444. if (_super.prototype.hasTexture.call(this, texture)) {
  44445. return true;
  44446. }
  44447. if (this._diffuseTexture === texture) {
  44448. return true;
  44449. }
  44450. if (this._ambientTexture === texture) {
  44451. return true;
  44452. }
  44453. if (this._opacityTexture === texture) {
  44454. return true;
  44455. }
  44456. if (this._reflectionTexture === texture) {
  44457. return true;
  44458. }
  44459. if (this._emissiveTexture === texture) {
  44460. return true;
  44461. }
  44462. if (this._specularTexture === texture) {
  44463. return true;
  44464. }
  44465. if (this._bumpTexture === texture) {
  44466. return true;
  44467. }
  44468. if (this._lightmapTexture === texture) {
  44469. return true;
  44470. }
  44471. if (this._refractionTexture === texture) {
  44472. return true;
  44473. }
  44474. return false;
  44475. };
  44476. /**
  44477. * Disposes the material
  44478. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44479. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44480. */
  44481. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44482. if (forceDisposeTextures) {
  44483. if (this._diffuseTexture) {
  44484. this._diffuseTexture.dispose();
  44485. }
  44486. if (this._ambientTexture) {
  44487. this._ambientTexture.dispose();
  44488. }
  44489. if (this._opacityTexture) {
  44490. this._opacityTexture.dispose();
  44491. }
  44492. if (this._reflectionTexture) {
  44493. this._reflectionTexture.dispose();
  44494. }
  44495. if (this._emissiveTexture) {
  44496. this._emissiveTexture.dispose();
  44497. }
  44498. if (this._specularTexture) {
  44499. this._specularTexture.dispose();
  44500. }
  44501. if (this._bumpTexture) {
  44502. this._bumpTexture.dispose();
  44503. }
  44504. if (this._lightmapTexture) {
  44505. this._lightmapTexture.dispose();
  44506. }
  44507. if (this._refractionTexture) {
  44508. this._refractionTexture.dispose();
  44509. }
  44510. }
  44511. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44512. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44513. }
  44514. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44515. };
  44516. /**
  44517. * Makes a duplicate of the material, and gives it a new name
  44518. * @param name defines the new name for the duplicated material
  44519. * @returns the cloned material
  44520. */
  44521. StandardMaterial.prototype.clone = function (name) {
  44522. var _this = this;
  44523. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44524. result.name = name;
  44525. result.id = name;
  44526. return result;
  44527. };
  44528. /**
  44529. * Serializes this material in a JSON representation
  44530. * @returns the serialized material object
  44531. */
  44532. StandardMaterial.prototype.serialize = function () {
  44533. return BABYLON.SerializationHelper.Serialize(this);
  44534. };
  44535. /**
  44536. * Creates a standard material from parsed material data
  44537. * @param source defines the JSON represnetation of the material
  44538. * @param scene defines the hosting scene
  44539. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44540. * @returns a new material
  44541. */
  44542. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44543. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44544. };
  44545. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44546. /**
  44547. * Are diffuse textures enabled in the application.
  44548. */
  44549. get: function () {
  44550. return StandardMaterial._DiffuseTextureEnabled;
  44551. },
  44552. set: function (value) {
  44553. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44554. return;
  44555. }
  44556. StandardMaterial._DiffuseTextureEnabled = value;
  44557. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44558. },
  44559. enumerable: true,
  44560. configurable: true
  44561. });
  44562. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44563. /**
  44564. * Are ambient textures enabled in the application.
  44565. */
  44566. get: function () {
  44567. return StandardMaterial._AmbientTextureEnabled;
  44568. },
  44569. set: function (value) {
  44570. if (StandardMaterial._AmbientTextureEnabled === value) {
  44571. return;
  44572. }
  44573. StandardMaterial._AmbientTextureEnabled = value;
  44574. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44575. },
  44576. enumerable: true,
  44577. configurable: true
  44578. });
  44579. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44580. /**
  44581. * Are opacity textures enabled in the application.
  44582. */
  44583. get: function () {
  44584. return StandardMaterial._OpacityTextureEnabled;
  44585. },
  44586. set: function (value) {
  44587. if (StandardMaterial._OpacityTextureEnabled === value) {
  44588. return;
  44589. }
  44590. StandardMaterial._OpacityTextureEnabled = value;
  44591. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44592. },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44597. /**
  44598. * Are reflection textures enabled in the application.
  44599. */
  44600. get: function () {
  44601. return StandardMaterial._ReflectionTextureEnabled;
  44602. },
  44603. set: function (value) {
  44604. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44605. return;
  44606. }
  44607. StandardMaterial._ReflectionTextureEnabled = value;
  44608. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44609. },
  44610. enumerable: true,
  44611. configurable: true
  44612. });
  44613. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44614. /**
  44615. * Are emissive textures enabled in the application.
  44616. */
  44617. get: function () {
  44618. return StandardMaterial._EmissiveTextureEnabled;
  44619. },
  44620. set: function (value) {
  44621. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44622. return;
  44623. }
  44624. StandardMaterial._EmissiveTextureEnabled = value;
  44625. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44626. },
  44627. enumerable: true,
  44628. configurable: true
  44629. });
  44630. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44631. /**
  44632. * Are specular textures enabled in the application.
  44633. */
  44634. get: function () {
  44635. return StandardMaterial._SpecularTextureEnabled;
  44636. },
  44637. set: function (value) {
  44638. if (StandardMaterial._SpecularTextureEnabled === value) {
  44639. return;
  44640. }
  44641. StandardMaterial._SpecularTextureEnabled = value;
  44642. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44643. },
  44644. enumerable: true,
  44645. configurable: true
  44646. });
  44647. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44648. /**
  44649. * Are bump textures enabled in the application.
  44650. */
  44651. get: function () {
  44652. return StandardMaterial._BumpTextureEnabled;
  44653. },
  44654. set: function (value) {
  44655. if (StandardMaterial._BumpTextureEnabled === value) {
  44656. return;
  44657. }
  44658. StandardMaterial._BumpTextureEnabled = value;
  44659. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44660. },
  44661. enumerable: true,
  44662. configurable: true
  44663. });
  44664. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44665. /**
  44666. * Are lightmap textures enabled in the application.
  44667. */
  44668. get: function () {
  44669. return StandardMaterial._LightmapTextureEnabled;
  44670. },
  44671. set: function (value) {
  44672. if (StandardMaterial._LightmapTextureEnabled === value) {
  44673. return;
  44674. }
  44675. StandardMaterial._LightmapTextureEnabled = value;
  44676. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44682. /**
  44683. * Are refraction textures enabled in the application.
  44684. */
  44685. get: function () {
  44686. return StandardMaterial._RefractionTextureEnabled;
  44687. },
  44688. set: function (value) {
  44689. if (StandardMaterial._RefractionTextureEnabled === value) {
  44690. return;
  44691. }
  44692. StandardMaterial._RefractionTextureEnabled = value;
  44693. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44694. },
  44695. enumerable: true,
  44696. configurable: true
  44697. });
  44698. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44699. /**
  44700. * Are color grading textures enabled in the application.
  44701. */
  44702. get: function () {
  44703. return StandardMaterial._ColorGradingTextureEnabled;
  44704. },
  44705. set: function (value) {
  44706. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44707. return;
  44708. }
  44709. StandardMaterial._ColorGradingTextureEnabled = value;
  44710. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44711. },
  44712. enumerable: true,
  44713. configurable: true
  44714. });
  44715. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44716. /**
  44717. * Are fresnels enabled in the application.
  44718. */
  44719. get: function () {
  44720. return StandardMaterial._FresnelEnabled;
  44721. },
  44722. set: function (value) {
  44723. if (StandardMaterial._FresnelEnabled === value) {
  44724. return;
  44725. }
  44726. StandardMaterial._FresnelEnabled = value;
  44727. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44728. },
  44729. enumerable: true,
  44730. configurable: true
  44731. });
  44732. // Flags used to enable or disable a type of texture for all Standard Materials
  44733. StandardMaterial._DiffuseTextureEnabled = true;
  44734. StandardMaterial._AmbientTextureEnabled = true;
  44735. StandardMaterial._OpacityTextureEnabled = true;
  44736. StandardMaterial._ReflectionTextureEnabled = true;
  44737. StandardMaterial._EmissiveTextureEnabled = true;
  44738. StandardMaterial._SpecularTextureEnabled = true;
  44739. StandardMaterial._BumpTextureEnabled = true;
  44740. StandardMaterial._LightmapTextureEnabled = true;
  44741. StandardMaterial._RefractionTextureEnabled = true;
  44742. StandardMaterial._ColorGradingTextureEnabled = true;
  44743. StandardMaterial._FresnelEnabled = true;
  44744. __decorate([
  44745. BABYLON.serializeAsTexture("diffuseTexture")
  44746. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44747. __decorate([
  44748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44749. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44750. __decorate([
  44751. BABYLON.serializeAsTexture("ambientTexture")
  44752. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44753. __decorate([
  44754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44755. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44756. __decorate([
  44757. BABYLON.serializeAsTexture("opacityTexture")
  44758. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44759. __decorate([
  44760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44761. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44762. __decorate([
  44763. BABYLON.serializeAsTexture("reflectionTexture")
  44764. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44765. __decorate([
  44766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44767. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44768. __decorate([
  44769. BABYLON.serializeAsTexture("emissiveTexture")
  44770. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44771. __decorate([
  44772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44773. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44774. __decorate([
  44775. BABYLON.serializeAsTexture("specularTexture")
  44776. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44777. __decorate([
  44778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44779. ], StandardMaterial.prototype, "specularTexture", void 0);
  44780. __decorate([
  44781. BABYLON.serializeAsTexture("bumpTexture")
  44782. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44783. __decorate([
  44784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44785. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44786. __decorate([
  44787. BABYLON.serializeAsTexture("lightmapTexture")
  44788. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44789. __decorate([
  44790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44791. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44792. __decorate([
  44793. BABYLON.serializeAsTexture("refractionTexture")
  44794. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44795. __decorate([
  44796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44797. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44798. __decorate([
  44799. BABYLON.serializeAsColor3("ambient")
  44800. ], StandardMaterial.prototype, "ambientColor", void 0);
  44801. __decorate([
  44802. BABYLON.serializeAsColor3("diffuse")
  44803. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44804. __decorate([
  44805. BABYLON.serializeAsColor3("specular")
  44806. ], StandardMaterial.prototype, "specularColor", void 0);
  44807. __decorate([
  44808. BABYLON.serializeAsColor3("emissive")
  44809. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44810. __decorate([
  44811. BABYLON.serialize()
  44812. ], StandardMaterial.prototype, "specularPower", void 0);
  44813. __decorate([
  44814. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44815. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44816. __decorate([
  44817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44818. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44819. __decorate([
  44820. BABYLON.serialize("useEmissiveAsIllumination")
  44821. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44822. __decorate([
  44823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44824. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44825. __decorate([
  44826. BABYLON.serialize("linkEmissiveWithDiffuse")
  44827. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44828. __decorate([
  44829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44830. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44831. __decorate([
  44832. BABYLON.serialize("useSpecularOverAlpha")
  44833. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44834. __decorate([
  44835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44836. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44837. __decorate([
  44838. BABYLON.serialize("useReflectionOverAlpha")
  44839. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44840. __decorate([
  44841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44842. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44843. __decorate([
  44844. BABYLON.serialize("disableLighting")
  44845. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44846. __decorate([
  44847. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44848. ], StandardMaterial.prototype, "disableLighting", void 0);
  44849. __decorate([
  44850. BABYLON.serialize("useObjectSpaceNormalMap")
  44851. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44852. __decorate([
  44853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44854. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44855. __decorate([
  44856. BABYLON.serialize("useParallax")
  44857. ], StandardMaterial.prototype, "_useParallax", void 0);
  44858. __decorate([
  44859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44860. ], StandardMaterial.prototype, "useParallax", void 0);
  44861. __decorate([
  44862. BABYLON.serialize("useParallaxOcclusion")
  44863. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44864. __decorate([
  44865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44866. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44867. __decorate([
  44868. BABYLON.serialize()
  44869. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44870. __decorate([
  44871. BABYLON.serialize("roughness")
  44872. ], StandardMaterial.prototype, "_roughness", void 0);
  44873. __decorate([
  44874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44875. ], StandardMaterial.prototype, "roughness", void 0);
  44876. __decorate([
  44877. BABYLON.serialize()
  44878. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44879. __decorate([
  44880. BABYLON.serialize()
  44881. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44882. __decorate([
  44883. BABYLON.serialize()
  44884. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44885. __decorate([
  44886. BABYLON.serialize("useLightmapAsShadowmap")
  44887. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44888. __decorate([
  44889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44890. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44891. __decorate([
  44892. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44893. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44894. __decorate([
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44896. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44897. __decorate([
  44898. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44899. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44900. __decorate([
  44901. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44902. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44903. __decorate([
  44904. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44905. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44906. __decorate([
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44908. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44909. __decorate([
  44910. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44911. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44912. __decorate([
  44913. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44914. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44915. __decorate([
  44916. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44917. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44918. __decorate([
  44919. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44920. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44921. __decorate([
  44922. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44923. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44924. __decorate([
  44925. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44926. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44927. __decorate([
  44928. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44929. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44930. __decorate([
  44931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44932. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44933. __decorate([
  44934. BABYLON.serialize("maxSimultaneousLights")
  44935. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44936. __decorate([
  44937. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44938. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44939. __decorate([
  44940. BABYLON.serialize("invertNormalMapX")
  44941. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44942. __decorate([
  44943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44944. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44945. __decorate([
  44946. BABYLON.serialize("invertNormalMapY")
  44947. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44948. __decorate([
  44949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44950. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44951. __decorate([
  44952. BABYLON.serialize("twoSidedLighting")
  44953. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44954. __decorate([
  44955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44956. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44957. __decorate([
  44958. BABYLON.serialize()
  44959. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44960. return StandardMaterial;
  44961. }(BABYLON.PushMaterial));
  44962. BABYLON.StandardMaterial = StandardMaterial;
  44963. })(BABYLON || (BABYLON = {}));
  44964. //# sourceMappingURL=babylon.standardMaterial.js.map
  44965. var BABYLON;
  44966. (function (BABYLON) {
  44967. /**
  44968. * Class representing spherical polynomial coefficients to the 3rd degree
  44969. */
  44970. var SphericalPolynomial = /** @class */ (function () {
  44971. function SphericalPolynomial() {
  44972. /**
  44973. * The x coefficients of the spherical polynomial
  44974. */
  44975. this.x = BABYLON.Vector3.Zero();
  44976. /**
  44977. * The y coefficients of the spherical polynomial
  44978. */
  44979. this.y = BABYLON.Vector3.Zero();
  44980. /**
  44981. * The z coefficients of the spherical polynomial
  44982. */
  44983. this.z = BABYLON.Vector3.Zero();
  44984. /**
  44985. * The xx coefficients of the spherical polynomial
  44986. */
  44987. this.xx = BABYLON.Vector3.Zero();
  44988. /**
  44989. * The yy coefficients of the spherical polynomial
  44990. */
  44991. this.yy = BABYLON.Vector3.Zero();
  44992. /**
  44993. * The zz coefficients of the spherical polynomial
  44994. */
  44995. this.zz = BABYLON.Vector3.Zero();
  44996. /**
  44997. * The xy coefficients of the spherical polynomial
  44998. */
  44999. this.xy = BABYLON.Vector3.Zero();
  45000. /**
  45001. * The yz coefficients of the spherical polynomial
  45002. */
  45003. this.yz = BABYLON.Vector3.Zero();
  45004. /**
  45005. * The zx coefficients of the spherical polynomial
  45006. */
  45007. this.zx = BABYLON.Vector3.Zero();
  45008. }
  45009. /**
  45010. * Adds an ambient color to the spherical polynomial
  45011. * @param color the color to add
  45012. */
  45013. SphericalPolynomial.prototype.addAmbient = function (color) {
  45014. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45015. this.xx = this.xx.add(colorVector);
  45016. this.yy = this.yy.add(colorVector);
  45017. this.zz = this.zz.add(colorVector);
  45018. };
  45019. /**
  45020. * Scales the spherical polynomial by the given amount
  45021. * @param scale the amount to scale
  45022. */
  45023. SphericalPolynomial.prototype.scale = function (scale) {
  45024. this.x = this.x.scale(scale);
  45025. this.y = this.y.scale(scale);
  45026. this.z = this.z.scale(scale);
  45027. this.xx = this.xx.scale(scale);
  45028. this.yy = this.yy.scale(scale);
  45029. this.zz = this.zz.scale(scale);
  45030. this.yz = this.yz.scale(scale);
  45031. this.zx = this.zx.scale(scale);
  45032. this.xy = this.xy.scale(scale);
  45033. };
  45034. /**
  45035. * Gets the spherical polynomial from harmonics
  45036. * @param harmonics the spherical harmonics
  45037. * @returns the spherical polynomial
  45038. */
  45039. SphericalPolynomial.FromHarmonics = function (harmonics) {
  45040. var result = new SphericalPolynomial();
  45041. result.x = harmonics.l11.scale(1.02333);
  45042. result.y = harmonics.l1_1.scale(1.02333);
  45043. result.z = harmonics.l10.scale(1.02333);
  45044. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  45045. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  45046. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  45047. result.yz = harmonics.l2_1.scale(0.858086);
  45048. result.zx = harmonics.l21.scale(0.858086);
  45049. result.xy = harmonics.l2_2.scale(0.858086);
  45050. result.scale(1.0 / Math.PI);
  45051. return result;
  45052. };
  45053. /**
  45054. * Constructs a spherical polynomial from an array.
  45055. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45056. * @returns the spherical polynomial
  45057. */
  45058. SphericalPolynomial.FromArray = function (data) {
  45059. var sp = new SphericalPolynomial();
  45060. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45061. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45062. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45063. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45064. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45065. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45066. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45067. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45068. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45069. return sp;
  45070. };
  45071. return SphericalPolynomial;
  45072. }());
  45073. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45074. /**
  45075. * Class representing spherical harmonics coefficients to the 3rd degree
  45076. */
  45077. var SphericalHarmonics = /** @class */ (function () {
  45078. function SphericalHarmonics() {
  45079. /**
  45080. * The l0,0 coefficients of the spherical harmonics
  45081. */
  45082. this.l00 = BABYLON.Vector3.Zero();
  45083. /**
  45084. * The l1,-1 coefficients of the spherical harmonics
  45085. */
  45086. this.l1_1 = BABYLON.Vector3.Zero();
  45087. /**
  45088. * The l1,0 coefficients of the spherical harmonics
  45089. */
  45090. this.l10 = BABYLON.Vector3.Zero();
  45091. /**
  45092. * The l1,1 coefficients of the spherical harmonics
  45093. */
  45094. this.l11 = BABYLON.Vector3.Zero();
  45095. /**
  45096. * The l2,-2 coefficients of the spherical harmonics
  45097. */
  45098. this.l2_2 = BABYLON.Vector3.Zero();
  45099. /**
  45100. * The l2,-1 coefficients of the spherical harmonics
  45101. */
  45102. this.l2_1 = BABYLON.Vector3.Zero();
  45103. /**
  45104. * The l2,0 coefficients of the spherical harmonics
  45105. */
  45106. this.l20 = BABYLON.Vector3.Zero();
  45107. /**
  45108. * The l2,1 coefficients of the spherical harmonics
  45109. */
  45110. this.l21 = BABYLON.Vector3.Zero();
  45111. /**
  45112. * The l2,2 coefficients of the spherical harmonics
  45113. */
  45114. this.lL22 = BABYLON.Vector3.Zero();
  45115. }
  45116. /**
  45117. * Adds a light to the spherical harmonics
  45118. * @param direction the direction of the light
  45119. * @param color the color of the light
  45120. * @param deltaSolidAngle the delta solid angle of the light
  45121. */
  45122. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45123. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45124. var c = colorVector.scale(deltaSolidAngle);
  45125. this.l00 = this.l00.add(c.scale(0.282095));
  45126. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45127. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45128. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45129. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45130. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45131. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45132. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45133. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45134. };
  45135. /**
  45136. * Scales the spherical harmonics by the given amount
  45137. * @param scale the amount to scale
  45138. */
  45139. SphericalHarmonics.prototype.scale = function (scale) {
  45140. this.l00 = this.l00.scale(scale);
  45141. this.l1_1 = this.l1_1.scale(scale);
  45142. this.l10 = this.l10.scale(scale);
  45143. this.l11 = this.l11.scale(scale);
  45144. this.l2_2 = this.l2_2.scale(scale);
  45145. this.l2_1 = this.l2_1.scale(scale);
  45146. this.l20 = this.l20.scale(scale);
  45147. this.l21 = this.l21.scale(scale);
  45148. this.lL22 = this.lL22.scale(scale);
  45149. };
  45150. /**
  45151. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45152. *
  45153. * ```
  45154. * E_lm = A_l * L_lm
  45155. * ```
  45156. *
  45157. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45158. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45159. * the scaling factors are given in equation 9.
  45160. */
  45161. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45162. // Constant (Band 0)
  45163. this.l00 = this.l00.scale(3.141593);
  45164. // Linear (Band 1)
  45165. this.l1_1 = this.l1_1.scale(2.094395);
  45166. this.l10 = this.l10.scale(2.094395);
  45167. this.l11 = this.l11.scale(2.094395);
  45168. // Quadratic (Band 2)
  45169. this.l2_2 = this.l2_2.scale(0.785398);
  45170. this.l2_1 = this.l2_1.scale(0.785398);
  45171. this.l20 = this.l20.scale(0.785398);
  45172. this.l21 = this.l21.scale(0.785398);
  45173. this.lL22 = this.lL22.scale(0.785398);
  45174. };
  45175. /**
  45176. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45177. *
  45178. * ```
  45179. * L = (1/pi) * E * rho
  45180. * ```
  45181. *
  45182. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45183. */
  45184. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45185. this.scale(1.0 / Math.PI);
  45186. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45187. // (The pixel shader must apply albedo after texture fetches, etc).
  45188. };
  45189. /**
  45190. * Gets the spherical harmonics from polynomial
  45191. * @param polynomial the spherical polynomial
  45192. * @returns the spherical harmonics
  45193. */
  45194. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45195. var result = new SphericalHarmonics();
  45196. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45197. result.l1_1 = polynomial.y.scale(0.977204);
  45198. result.l10 = polynomial.z.scale(0.977204);
  45199. result.l11 = polynomial.x.scale(0.977204);
  45200. result.l2_2 = polynomial.xy.scale(1.16538);
  45201. result.l2_1 = polynomial.yz.scale(1.16538);
  45202. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45203. result.l21 = polynomial.zx.scale(1.16538);
  45204. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45205. result.scale(Math.PI);
  45206. return result;
  45207. };
  45208. /**
  45209. * Constructs a spherical harmonics from an array.
  45210. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45211. * @returns the spherical harmonics
  45212. */
  45213. SphericalHarmonics.FromArray = function (data) {
  45214. var sh = new SphericalHarmonics();
  45215. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45216. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45217. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45218. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45219. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45220. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45221. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45222. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45223. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45224. return sh;
  45225. };
  45226. return SphericalHarmonics;
  45227. }());
  45228. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45229. })(BABYLON || (BABYLON = {}));
  45230. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  45231. var BABYLON;
  45232. (function (BABYLON) {
  45233. var FileFaceOrientation = /** @class */ (function () {
  45234. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45235. this.name = name;
  45236. this.worldAxisForNormal = worldAxisForNormal;
  45237. this.worldAxisForFileX = worldAxisForFileX;
  45238. this.worldAxisForFileY = worldAxisForFileY;
  45239. }
  45240. return FileFaceOrientation;
  45241. }());
  45242. /**
  45243. * Helper class dealing with the extraction of spherical polynomial dataArray
  45244. * from a cube map.
  45245. */
  45246. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45247. function CubeMapToSphericalPolynomialTools() {
  45248. }
  45249. /**
  45250. * Converts a texture to the according Spherical Polynomial data.
  45251. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45252. *
  45253. * @param texture The texture to extract the information from.
  45254. * @return The Spherical Polynomial data.
  45255. */
  45256. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45257. if (!texture.isCube) {
  45258. // Only supports cube Textures currently.
  45259. return null;
  45260. }
  45261. var size = texture.getSize().width;
  45262. var right = texture.readPixels(0);
  45263. var left = texture.readPixels(1);
  45264. var up;
  45265. var down;
  45266. if (texture.isRenderTarget) {
  45267. up = texture.readPixels(3);
  45268. down = texture.readPixels(2);
  45269. }
  45270. else {
  45271. up = texture.readPixels(2);
  45272. down = texture.readPixels(3);
  45273. }
  45274. var front = texture.readPixels(4);
  45275. var back = texture.readPixels(5);
  45276. var gammaSpace = texture.gammaSpace;
  45277. // Always read as RGBA.
  45278. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45279. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45280. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45281. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45282. }
  45283. var cubeInfo = {
  45284. size: size,
  45285. right: right,
  45286. left: left,
  45287. up: up,
  45288. down: down,
  45289. front: front,
  45290. back: back,
  45291. format: format,
  45292. type: type,
  45293. gammaSpace: gammaSpace,
  45294. };
  45295. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45296. };
  45297. /**
  45298. * Converts a cubemap to the according Spherical Polynomial data.
  45299. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45300. *
  45301. * @param cubeInfo The Cube map to extract the information from.
  45302. * @return The Spherical Polynomial data.
  45303. */
  45304. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45305. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45306. var totalSolidAngle = 0.0;
  45307. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45308. var du = 2.0 / cubeInfo.size;
  45309. var dv = du;
  45310. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45311. var minUV = du * 0.5 - 1.0;
  45312. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45313. var fileFace = this.FileFaces[faceIndex];
  45314. var dataArray = cubeInfo[fileFace.name];
  45315. var v = minUV;
  45316. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45317. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45318. // Because SP is still linear, so summation is fine in that basis.
  45319. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45320. for (var y = 0; y < cubeInfo.size; y++) {
  45321. var u = minUV;
  45322. for (var x = 0; x < cubeInfo.size; x++) {
  45323. // World direction (not normalised)
  45324. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45325. worldDirection.normalize();
  45326. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45327. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45328. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45329. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45330. // Handle Integer types.
  45331. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45332. r /= 255;
  45333. g /= 255;
  45334. b /= 255;
  45335. }
  45336. // Handle Gamma space textures.
  45337. if (cubeInfo.gammaSpace) {
  45338. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45339. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45340. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45341. }
  45342. var color = new BABYLON.Color3(r, g, b);
  45343. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45344. totalSolidAngle += deltaSolidAngle;
  45345. u += du;
  45346. }
  45347. v += dv;
  45348. }
  45349. }
  45350. // Solid angle for entire sphere is 4*pi
  45351. var sphereSolidAngle = 4.0 * Math.PI;
  45352. // Adjust the solid angle to allow for how many faces we processed.
  45353. var facesProcessed = 6.0;
  45354. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45355. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45356. // This is needed because the numerical integration over the cube uses a
  45357. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45358. // and also to compensate for accumulative error due to float precision in the summation.
  45359. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45360. sphericalHarmonics.scale(correctionFactor);
  45361. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45362. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45363. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45364. };
  45365. CubeMapToSphericalPolynomialTools.FileFaces = [
  45366. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45367. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45368. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45369. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45370. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45371. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45372. ];
  45373. return CubeMapToSphericalPolynomialTools;
  45374. }());
  45375. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45376. })(BABYLON || (BABYLON = {}));
  45377. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45378. var BABYLON;
  45379. (function (BABYLON) {
  45380. /**
  45381. * Manages the defines for the PBR Material.
  45382. * @hiddenChildren
  45383. */
  45384. var PBRMaterialDefines = /** @class */ (function (_super) {
  45385. __extends(PBRMaterialDefines, _super);
  45386. /**
  45387. * Initializes the PBR Material defines.
  45388. */
  45389. function PBRMaterialDefines() {
  45390. var _this = _super.call(this) || this;
  45391. _this.PBR = true;
  45392. _this.MAINUV1 = false;
  45393. _this.MAINUV2 = false;
  45394. _this.UV1 = false;
  45395. _this.UV2 = false;
  45396. _this.ALBEDO = false;
  45397. _this.ALBEDODIRECTUV = 0;
  45398. _this.VERTEXCOLOR = false;
  45399. _this.AMBIENT = false;
  45400. _this.AMBIENTDIRECTUV = 0;
  45401. _this.AMBIENTINGRAYSCALE = false;
  45402. _this.OPACITY = false;
  45403. _this.VERTEXALPHA = false;
  45404. _this.OPACITYDIRECTUV = 0;
  45405. _this.OPACITYRGB = false;
  45406. _this.ALPHATEST = false;
  45407. _this.DEPTHPREPASS = false;
  45408. _this.ALPHABLEND = false;
  45409. _this.ALPHAFROMALBEDO = false;
  45410. _this.ALPHATESTVALUE = "0.5";
  45411. _this.SPECULAROVERALPHA = false;
  45412. _this.RADIANCEOVERALPHA = false;
  45413. _this.ALPHAFRESNEL = false;
  45414. _this.LINEARALPHAFRESNEL = false;
  45415. _this.PREMULTIPLYALPHA = false;
  45416. _this.EMISSIVE = false;
  45417. _this.EMISSIVEDIRECTUV = 0;
  45418. _this.REFLECTIVITY = false;
  45419. _this.REFLECTIVITYDIRECTUV = 0;
  45420. _this.SPECULARTERM = false;
  45421. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45422. _this.MICROSURFACEAUTOMATIC = false;
  45423. _this.LODBASEDMICROSFURACE = false;
  45424. _this.MICROSURFACEMAP = false;
  45425. _this.MICROSURFACEMAPDIRECTUV = 0;
  45426. _this.METALLICWORKFLOW = false;
  45427. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45428. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45429. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45430. _this.AOSTOREINMETALMAPRED = false;
  45431. _this.ENVIRONMENTBRDF = false;
  45432. _this.NORMAL = false;
  45433. _this.TANGENT = false;
  45434. _this.BUMP = false;
  45435. _this.BUMPDIRECTUV = 0;
  45436. _this.OBJECTSPACE_NORMALMAP = false;
  45437. _this.PARALLAX = false;
  45438. _this.PARALLAXOCCLUSION = false;
  45439. _this.NORMALXYSCALE = true;
  45440. _this.LIGHTMAP = false;
  45441. _this.LIGHTMAPDIRECTUV = 0;
  45442. _this.USELIGHTMAPASSHADOWMAP = false;
  45443. _this.GAMMALIGHTMAP = false;
  45444. _this.REFLECTION = false;
  45445. _this.REFLECTIONMAP_3D = false;
  45446. _this.REFLECTIONMAP_SPHERICAL = false;
  45447. _this.REFLECTIONMAP_PLANAR = false;
  45448. _this.REFLECTIONMAP_CUBIC = false;
  45449. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45450. _this.REFLECTIONMAP_PROJECTION = false;
  45451. _this.REFLECTIONMAP_SKYBOX = false;
  45452. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45453. _this.REFLECTIONMAP_EXPLICIT = false;
  45454. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45455. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45456. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45457. _this.INVERTCUBICMAP = false;
  45458. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45459. _this.USESPHERICALINVERTEX = false;
  45460. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45461. _this.LODINREFLECTIONALPHA = false;
  45462. _this.GAMMAREFLECTION = false;
  45463. _this.RGBDREFLECTION = false;
  45464. _this.RADIANCEOCCLUSION = false;
  45465. _this.HORIZONOCCLUSION = false;
  45466. _this.REFRACTION = false;
  45467. _this.REFRACTIONMAP_3D = false;
  45468. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45469. _this.LODINREFRACTIONALPHA = false;
  45470. _this.GAMMAREFRACTION = false;
  45471. _this.RGBDREFRACTION = false;
  45472. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45473. _this.INSTANCES = false;
  45474. _this.NUM_BONE_INFLUENCERS = 0;
  45475. _this.BonesPerMesh = 0;
  45476. _this.BONETEXTURE = false;
  45477. _this.NONUNIFORMSCALING = false;
  45478. _this.MORPHTARGETS = false;
  45479. _this.MORPHTARGETS_NORMAL = false;
  45480. _this.MORPHTARGETS_TANGENT = false;
  45481. _this.NUM_MORPH_INFLUENCERS = 0;
  45482. _this.IMAGEPROCESSING = false;
  45483. _this.VIGNETTE = false;
  45484. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45485. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45486. _this.TONEMAPPING = false;
  45487. _this.TONEMAPPING_ACES = false;
  45488. _this.CONTRAST = false;
  45489. _this.COLORCURVES = false;
  45490. _this.COLORGRADING = false;
  45491. _this.COLORGRADING3D = false;
  45492. _this.SAMPLER3DGREENDEPTH = false;
  45493. _this.SAMPLER3DBGRMAP = false;
  45494. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45495. _this.EXPOSURE = false;
  45496. _this.USEPHYSICALLIGHTFALLOFF = false;
  45497. _this.USEGLTFLIGHTFALLOFF = false;
  45498. _this.TWOSIDEDLIGHTING = false;
  45499. _this.SHADOWFLOAT = false;
  45500. _this.CLIPPLANE = false;
  45501. _this.CLIPPLANE2 = false;
  45502. _this.CLIPPLANE3 = false;
  45503. _this.CLIPPLANE4 = false;
  45504. _this.POINTSIZE = false;
  45505. _this.FOG = false;
  45506. _this.LOGARITHMICDEPTH = false;
  45507. _this.FORCENORMALFORWARD = false;
  45508. _this.SPECULARAA = false;
  45509. _this.UNLIT = false;
  45510. _this.rebuild();
  45511. return _this;
  45512. }
  45513. /**
  45514. * Resets the PBR Material defines.
  45515. */
  45516. PBRMaterialDefines.prototype.reset = function () {
  45517. _super.prototype.reset.call(this);
  45518. this.ALPHATESTVALUE = "0.5";
  45519. this.PBR = true;
  45520. };
  45521. return PBRMaterialDefines;
  45522. }(BABYLON.MaterialDefines));
  45523. /**
  45524. * The Physically based material base class of BJS.
  45525. *
  45526. * This offers the main features of a standard PBR material.
  45527. * For more information, please refer to the documentation :
  45528. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45529. */
  45530. var PBRBaseMaterial = /** @class */ (function (_super) {
  45531. __extends(PBRBaseMaterial, _super);
  45532. /**
  45533. * Instantiates a new PBRMaterial instance.
  45534. *
  45535. * @param name The material name
  45536. * @param scene The scene the material will be use in.
  45537. */
  45538. function PBRBaseMaterial(name, scene) {
  45539. var _this = _super.call(this, name, scene) || this;
  45540. /**
  45541. * Intensity of the direct lights e.g. the four lights available in your scene.
  45542. * This impacts both the direct diffuse and specular highlights.
  45543. */
  45544. _this._directIntensity = 1.0;
  45545. /**
  45546. * Intensity of the emissive part of the material.
  45547. * This helps controlling the emissive effect without modifying the emissive color.
  45548. */
  45549. _this._emissiveIntensity = 1.0;
  45550. /**
  45551. * Intensity of the environment e.g. how much the environment will light the object
  45552. * either through harmonics for rough material or through the refelction for shiny ones.
  45553. */
  45554. _this._environmentIntensity = 1.0;
  45555. /**
  45556. * This is a special control allowing the reduction of the specular highlights coming from the
  45557. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45558. */
  45559. _this._specularIntensity = 1.0;
  45560. /**
  45561. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45562. */
  45563. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45564. /**
  45565. * Debug Control allowing disabling the bump map on this material.
  45566. */
  45567. _this._disableBumpMap = false;
  45568. /**
  45569. * AKA Occlusion Texture Intensity in other nomenclature.
  45570. */
  45571. _this._ambientTextureStrength = 1.0;
  45572. /**
  45573. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45574. * 1 means it completely occludes it
  45575. * 0 mean it has no impact
  45576. */
  45577. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45578. /**
  45579. * The color of a material in ambient lighting.
  45580. */
  45581. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45582. /**
  45583. * AKA Diffuse Color in other nomenclature.
  45584. */
  45585. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45586. /**
  45587. * AKA Specular Color in other nomenclature.
  45588. */
  45589. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45590. /**
  45591. * The color applied when light is reflected from a material.
  45592. */
  45593. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45594. /**
  45595. * The color applied when light is emitted from a material.
  45596. */
  45597. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45598. /**
  45599. * AKA Glossiness in other nomenclature.
  45600. */
  45601. _this._microSurface = 0.9;
  45602. /**
  45603. * source material index of refraction (IOR)' / 'destination material IOR.
  45604. */
  45605. _this._indexOfRefraction = 0.66;
  45606. /**
  45607. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45608. */
  45609. _this._invertRefractionY = false;
  45610. /**
  45611. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45612. * Materials half opaque for instance using refraction could benefit from this control.
  45613. */
  45614. _this._linkRefractionWithTransparency = false;
  45615. /**
  45616. * Specifies that the material will use the light map as a show map.
  45617. */
  45618. _this._useLightmapAsShadowmap = false;
  45619. /**
  45620. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45621. * makes the reflect vector face the model (under horizon).
  45622. */
  45623. _this._useHorizonOcclusion = true;
  45624. /**
  45625. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45626. * too much the area relying on ambient texture to define their ambient occlusion.
  45627. */
  45628. _this._useRadianceOcclusion = true;
  45629. /**
  45630. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45631. */
  45632. _this._useAlphaFromAlbedoTexture = false;
  45633. /**
  45634. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45635. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45636. */
  45637. _this._useSpecularOverAlpha = true;
  45638. /**
  45639. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45640. */
  45641. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45642. /**
  45643. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45644. */
  45645. _this._useRoughnessFromMetallicTextureAlpha = true;
  45646. /**
  45647. * Specifies if the metallic texture contains the roughness information in its green channel.
  45648. */
  45649. _this._useRoughnessFromMetallicTextureGreen = false;
  45650. /**
  45651. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45652. */
  45653. _this._useMetallnessFromMetallicTextureBlue = false;
  45654. /**
  45655. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45656. */
  45657. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45658. /**
  45659. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45660. */
  45661. _this._useAmbientInGrayScale = false;
  45662. /**
  45663. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45664. * The material will try to infer what glossiness each pixel should be.
  45665. */
  45666. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45667. /**
  45668. * Defines the falloff type used in this material.
  45669. * It by default is Physical.
  45670. */
  45671. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45672. /**
  45673. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45674. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45675. */
  45676. _this._useRadianceOverAlpha = true;
  45677. /**
  45678. * Allows using an object space normal map (instead of tangent space).
  45679. */
  45680. _this._useObjectSpaceNormalMap = false;
  45681. /**
  45682. * Allows using the bump map in parallax mode.
  45683. */
  45684. _this._useParallax = false;
  45685. /**
  45686. * Allows using the bump map in parallax occlusion mode.
  45687. */
  45688. _this._useParallaxOcclusion = false;
  45689. /**
  45690. * Controls the scale bias of the parallax mode.
  45691. */
  45692. _this._parallaxScaleBias = 0.05;
  45693. /**
  45694. * If sets to true, disables all the lights affecting the material.
  45695. */
  45696. _this._disableLighting = false;
  45697. /**
  45698. * Number of Simultaneous lights allowed on the material.
  45699. */
  45700. _this._maxSimultaneousLights = 4;
  45701. /**
  45702. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45703. */
  45704. _this._invertNormalMapX = false;
  45705. /**
  45706. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45707. */
  45708. _this._invertNormalMapY = false;
  45709. /**
  45710. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45711. */
  45712. _this._twoSidedLighting = false;
  45713. /**
  45714. * Defines the alpha limits in alpha test mode.
  45715. */
  45716. _this._alphaCutOff = 0.4;
  45717. /**
  45718. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45719. */
  45720. _this._forceAlphaTest = false;
  45721. /**
  45722. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45723. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45724. */
  45725. _this._useAlphaFresnel = false;
  45726. /**
  45727. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45728. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45729. */
  45730. _this._useLinearAlphaFresnel = false;
  45731. /**
  45732. * The transparency mode of the material.
  45733. */
  45734. _this._transparencyMode = null;
  45735. /**
  45736. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45737. * from cos thetav and roughness:
  45738. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45739. */
  45740. _this._environmentBRDFTexture = null;
  45741. /**
  45742. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45743. */
  45744. _this._forceIrradianceInFragment = false;
  45745. /**
  45746. * Force normal to face away from face.
  45747. */
  45748. _this._forceNormalForward = false;
  45749. /**
  45750. * Enables specular anti aliasing in the PBR shader.
  45751. * It will both interacts on the Geometry for analytical and IBL lighting.
  45752. * It also prefilter the roughness map based on the bump values.
  45753. */
  45754. _this._enableSpecularAntiAliasing = false;
  45755. /**
  45756. * Stores the available render targets.
  45757. */
  45758. _this._renderTargets = new BABYLON.SmartArray(16);
  45759. /**
  45760. * Sets the global ambient color for the material used in lighting calculations.
  45761. */
  45762. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45763. /**
  45764. * If set to true, no lighting calculations will be applied.
  45765. */
  45766. _this._unlit = false;
  45767. // Setup the default processing configuration to the scene.
  45768. _this._attachImageProcessingConfiguration(null);
  45769. _this.getRenderTargetTextures = function () {
  45770. _this._renderTargets.reset();
  45771. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45772. _this._renderTargets.push(_this._reflectionTexture);
  45773. }
  45774. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45775. _this._renderTargets.push(_this._refractionTexture);
  45776. }
  45777. return _this._renderTargets;
  45778. };
  45779. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45780. return _this;
  45781. }
  45782. /**
  45783. * Attaches a new image processing configuration to the PBR Material.
  45784. * @param configuration
  45785. */
  45786. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45787. var _this = this;
  45788. if (configuration === this._imageProcessingConfiguration) {
  45789. return;
  45790. }
  45791. // Detaches observer.
  45792. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45793. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45794. }
  45795. // Pick the scene configuration if needed.
  45796. if (!configuration) {
  45797. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45798. }
  45799. else {
  45800. this._imageProcessingConfiguration = configuration;
  45801. }
  45802. // Attaches observer.
  45803. if (this._imageProcessingConfiguration) {
  45804. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45805. _this._markAllSubMeshesAsImageProcessingDirty();
  45806. });
  45807. }
  45808. };
  45809. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45810. /**
  45811. * Gets a boolean indicating that current material needs to register RTT
  45812. */
  45813. get: function () {
  45814. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45815. return true;
  45816. }
  45817. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45818. return true;
  45819. }
  45820. return false;
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. /**
  45826. * Gets the name of the material class.
  45827. */
  45828. PBRBaseMaterial.prototype.getClassName = function () {
  45829. return "PBRBaseMaterial";
  45830. };
  45831. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45832. /**
  45833. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45834. */
  45835. get: function () {
  45836. return this._useLogarithmicDepth;
  45837. },
  45838. /**
  45839. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45840. */
  45841. set: function (value) {
  45842. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45848. /**
  45849. * Gets the current transparency mode.
  45850. */
  45851. get: function () {
  45852. return this._transparencyMode;
  45853. },
  45854. /**
  45855. * Sets the transparency mode of the material.
  45856. *
  45857. * | Value | Type | Description |
  45858. * | ----- | ----------------------------------- | ----------- |
  45859. * | 0 | OPAQUE | |
  45860. * | 1 | ALPHATEST | |
  45861. * | 2 | ALPHABLEND | |
  45862. * | 3 | ALPHATESTANDBLEND | |
  45863. *
  45864. */
  45865. set: function (value) {
  45866. if (this._transparencyMode === value) {
  45867. return;
  45868. }
  45869. this._transparencyMode = value;
  45870. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45871. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45872. },
  45873. enumerable: true,
  45874. configurable: true
  45875. });
  45876. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45877. /**
  45878. * Returns true if alpha blending should be disabled.
  45879. */
  45880. get: function () {
  45881. return (this._linkRefractionWithTransparency ||
  45882. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45883. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45884. },
  45885. enumerable: true,
  45886. configurable: true
  45887. });
  45888. /**
  45889. * Specifies whether or not this material should be rendered in alpha blend mode.
  45890. */
  45891. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45892. if (this._disableAlphaBlending) {
  45893. return false;
  45894. }
  45895. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45896. };
  45897. /**
  45898. * Specifies if the mesh will require alpha blending.
  45899. * @param mesh - BJS mesh.
  45900. */
  45901. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45902. if (this._disableAlphaBlending) {
  45903. return false;
  45904. }
  45905. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45906. };
  45907. /**
  45908. * Specifies whether or not this material should be rendered in alpha test mode.
  45909. */
  45910. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45911. if (this._forceAlphaTest) {
  45912. return true;
  45913. }
  45914. if (this._linkRefractionWithTransparency) {
  45915. return false;
  45916. }
  45917. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45918. };
  45919. /**
  45920. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45921. */
  45922. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45923. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45924. };
  45925. /**
  45926. * Gets the texture used for the alpha test.
  45927. */
  45928. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45929. return this._albedoTexture;
  45930. };
  45931. /**
  45932. * Specifies that the submesh is ready to be used.
  45933. * @param mesh - BJS mesh.
  45934. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45935. * @param useInstances - Specifies that instances should be used.
  45936. * @returns - boolean indicating that the submesh is ready or not.
  45937. */
  45938. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45939. if (subMesh.effect && this.isFrozen) {
  45940. if (this._wasPreviouslyReady) {
  45941. return true;
  45942. }
  45943. }
  45944. if (!subMesh._materialDefines) {
  45945. subMesh._materialDefines = new PBRMaterialDefines();
  45946. }
  45947. var defines = subMesh._materialDefines;
  45948. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45949. if (defines._renderId === this.getScene().getRenderId()) {
  45950. return true;
  45951. }
  45952. }
  45953. var scene = this.getScene();
  45954. var engine = scene.getEngine();
  45955. if (defines._areTexturesDirty) {
  45956. if (scene.texturesEnabled) {
  45957. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45958. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45959. return false;
  45960. }
  45961. }
  45962. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45963. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45964. return false;
  45965. }
  45966. }
  45967. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45968. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45969. return false;
  45970. }
  45971. }
  45972. var reflectionTexture = this._getReflectionTexture();
  45973. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45974. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45975. return false;
  45976. }
  45977. }
  45978. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45979. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45980. return false;
  45981. }
  45982. }
  45983. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45984. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45985. return false;
  45986. }
  45987. }
  45988. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45989. if (this._metallicTexture) {
  45990. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45991. return false;
  45992. }
  45993. }
  45994. else if (this._reflectivityTexture) {
  45995. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45996. return false;
  45997. }
  45998. }
  45999. if (this._microSurfaceTexture) {
  46000. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  46001. return false;
  46002. }
  46003. }
  46004. }
  46005. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46006. // Bump texture cannot be not blocking.
  46007. if (!this._bumpTexture.isReady()) {
  46008. return false;
  46009. }
  46010. }
  46011. var refractionTexture = this._getRefractionTexture();
  46012. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46013. if (!refractionTexture.isReadyOrNotBlocking()) {
  46014. return false;
  46015. }
  46016. }
  46017. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46018. // This is blocking.
  46019. if (!this._environmentBRDFTexture.isReady()) {
  46020. return false;
  46021. }
  46022. }
  46023. }
  46024. }
  46025. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46026. if (!this._imageProcessingConfiguration.isReady()) {
  46027. return false;
  46028. }
  46029. }
  46030. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46031. mesh.createNormals(true);
  46032. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  46033. }
  46034. var previousEffect = subMesh.effect;
  46035. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  46036. if (effect) {
  46037. // Use previous effect while new one is compiling
  46038. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  46039. effect = previousEffect;
  46040. defines.markAsUnprocessed();
  46041. }
  46042. else {
  46043. scene.resetCachedMaterial();
  46044. subMesh.setEffect(effect, defines);
  46045. this.buildUniformLayout();
  46046. }
  46047. }
  46048. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46049. return false;
  46050. }
  46051. defines._renderId = scene.getRenderId();
  46052. this._wasPreviouslyReady = true;
  46053. return true;
  46054. };
  46055. /**
  46056. * Specifies if the material uses metallic roughness workflow.
  46057. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46058. */
  46059. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46060. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46061. return true;
  46062. }
  46063. return false;
  46064. };
  46065. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46066. if (onCompiled === void 0) { onCompiled = null; }
  46067. if (onError === void 0) { onError = null; }
  46068. if (useInstances === void 0) { useInstances = null; }
  46069. if (useClipPlane === void 0) { useClipPlane = null; }
  46070. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46071. if (!defines.isDirty) {
  46072. return null;
  46073. }
  46074. defines.markAsProcessed();
  46075. var scene = this.getScene();
  46076. var engine = scene.getEngine();
  46077. // Fallbacks
  46078. var fallbacks = new BABYLON.EffectFallbacks();
  46079. var fallbackRank = 0;
  46080. if (defines.USESPHERICALINVERTEX) {
  46081. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46082. }
  46083. if (defines.FOG) {
  46084. fallbacks.addFallback(fallbackRank, "FOG");
  46085. }
  46086. if (defines.SPECULARAA) {
  46087. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46088. }
  46089. if (defines.POINTSIZE) {
  46090. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46091. }
  46092. if (defines.LOGARITHMICDEPTH) {
  46093. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46094. }
  46095. if (defines.PARALLAX) {
  46096. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46097. }
  46098. if (defines.PARALLAXOCCLUSION) {
  46099. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46100. }
  46101. if (defines.ENVIRONMENTBRDF) {
  46102. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46103. }
  46104. if (defines.TANGENT) {
  46105. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46106. }
  46107. if (defines.BUMP) {
  46108. fallbacks.addFallback(fallbackRank++, "BUMP");
  46109. }
  46110. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46111. if (defines.SPECULARTERM) {
  46112. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46113. }
  46114. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46115. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46116. }
  46117. if (defines.LIGHTMAP) {
  46118. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46119. }
  46120. if (defines.NORMAL) {
  46121. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46122. }
  46123. if (defines.AMBIENT) {
  46124. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46125. }
  46126. if (defines.EMISSIVE) {
  46127. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46128. }
  46129. if (defines.VERTEXCOLOR) {
  46130. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46131. }
  46132. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46133. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46134. }
  46135. if (defines.MORPHTARGETS) {
  46136. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46137. }
  46138. //Attributes
  46139. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46140. if (defines.NORMAL) {
  46141. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46142. }
  46143. if (defines.TANGENT) {
  46144. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46145. }
  46146. if (defines.UV1) {
  46147. attribs.push(BABYLON.VertexBuffer.UVKind);
  46148. }
  46149. if (defines.UV2) {
  46150. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46151. }
  46152. if (defines.VERTEXCOLOR) {
  46153. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46154. }
  46155. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46156. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46157. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46158. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46159. "vFogInfos", "vFogColor", "pointSize",
  46160. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46161. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46162. "mBones",
  46163. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46164. "vLightingIntensity",
  46165. "logarithmicDepthConstant",
  46166. "vSphericalX", "vSphericalY", "vSphericalZ",
  46167. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46168. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46169. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46170. "vTangentSpaceParams", "boneTextureWidth"
  46171. ];
  46172. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46173. "bumpSampler", "lightmapSampler", "opacitySampler",
  46174. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46175. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46176. "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"];
  46177. var uniformBuffers = ["Material", "Scene"];
  46178. if (BABYLON.ImageProcessingConfiguration) {
  46179. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46180. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46181. }
  46182. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46183. uniformsNames: uniforms,
  46184. uniformBuffersNames: uniformBuffers,
  46185. samplers: samplers,
  46186. defines: defines,
  46187. maxSimultaneousLights: this._maxSimultaneousLights
  46188. });
  46189. var join = defines.toString();
  46190. return engine.createEffect("pbr", {
  46191. attributes: attribs,
  46192. uniformsNames: uniforms,
  46193. uniformBuffersNames: uniformBuffers,
  46194. samplers: samplers,
  46195. defines: join,
  46196. fallbacks: fallbacks,
  46197. onCompiled: onCompiled,
  46198. onError: onError,
  46199. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46200. }, engine);
  46201. };
  46202. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46203. if (useInstances === void 0) { useInstances = null; }
  46204. if (useClipPlane === void 0) { useClipPlane = null; }
  46205. var scene = this.getScene();
  46206. var engine = scene.getEngine();
  46207. // Lights
  46208. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46209. defines._needNormals = true;
  46210. // Textures
  46211. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46212. if (defines._areTexturesDirty) {
  46213. defines._needUVs = false;
  46214. if (scene.texturesEnabled) {
  46215. if (scene.getEngine().getCaps().textureLOD) {
  46216. defines.LODBASEDMICROSFURACE = true;
  46217. }
  46218. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46220. }
  46221. else {
  46222. defines.ALBEDO = false;
  46223. }
  46224. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46226. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46227. }
  46228. else {
  46229. defines.AMBIENT = false;
  46230. }
  46231. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46233. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46234. }
  46235. else {
  46236. defines.OPACITY = false;
  46237. }
  46238. var reflectionTexture = this._getReflectionTexture();
  46239. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46240. defines.REFLECTION = true;
  46241. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46242. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46243. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46244. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46245. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46246. defines.INVERTCUBICMAP = true;
  46247. }
  46248. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46249. switch (reflectionTexture.coordinatesMode) {
  46250. case BABYLON.Texture.EXPLICIT_MODE:
  46251. defines.REFLECTIONMAP_EXPLICIT = true;
  46252. break;
  46253. case BABYLON.Texture.PLANAR_MODE:
  46254. defines.REFLECTIONMAP_PLANAR = true;
  46255. break;
  46256. case BABYLON.Texture.PROJECTION_MODE:
  46257. defines.REFLECTIONMAP_PROJECTION = true;
  46258. break;
  46259. case BABYLON.Texture.SKYBOX_MODE:
  46260. defines.REFLECTIONMAP_SKYBOX = true;
  46261. break;
  46262. case BABYLON.Texture.SPHERICAL_MODE:
  46263. defines.REFLECTIONMAP_SPHERICAL = true;
  46264. break;
  46265. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46266. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46267. break;
  46268. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46269. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46270. break;
  46271. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46272. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46273. break;
  46274. case BABYLON.Texture.CUBIC_MODE:
  46275. case BABYLON.Texture.INVCUBIC_MODE:
  46276. default:
  46277. defines.REFLECTIONMAP_CUBIC = true;
  46278. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46279. break;
  46280. }
  46281. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46282. if (reflectionTexture.sphericalPolynomial) {
  46283. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46284. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46285. defines.USESPHERICALINVERTEX = false;
  46286. }
  46287. else {
  46288. defines.USESPHERICALINVERTEX = true;
  46289. }
  46290. }
  46291. }
  46292. else {
  46293. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46294. }
  46295. }
  46296. else {
  46297. defines.REFLECTION = false;
  46298. defines.REFLECTIONMAP_3D = false;
  46299. defines.REFLECTIONMAP_SPHERICAL = false;
  46300. defines.REFLECTIONMAP_PLANAR = false;
  46301. defines.REFLECTIONMAP_CUBIC = false;
  46302. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46303. defines.REFLECTIONMAP_PROJECTION = false;
  46304. defines.REFLECTIONMAP_SKYBOX = false;
  46305. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46306. defines.REFLECTIONMAP_EXPLICIT = false;
  46307. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46308. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46309. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46310. defines.INVERTCUBICMAP = false;
  46311. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46312. defines.USESPHERICALINVERTEX = false;
  46313. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46314. defines.LODINREFLECTIONALPHA = false;
  46315. defines.GAMMAREFLECTION = false;
  46316. defines.RGBDREFLECTION = false;
  46317. }
  46318. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46319. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46320. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46321. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46322. }
  46323. else {
  46324. defines.LIGHTMAP = false;
  46325. }
  46326. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46327. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46328. }
  46329. else {
  46330. defines.EMISSIVE = false;
  46331. }
  46332. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46333. if (this._metallicTexture) {
  46334. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46335. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46336. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46337. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46338. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46339. }
  46340. else if (this._reflectivityTexture) {
  46341. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46342. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46343. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46344. }
  46345. else {
  46346. defines.REFLECTIVITY = false;
  46347. }
  46348. if (this._microSurfaceTexture) {
  46349. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46350. }
  46351. else {
  46352. defines.MICROSURFACEMAP = false;
  46353. }
  46354. }
  46355. else {
  46356. defines.REFLECTIVITY = false;
  46357. defines.MICROSURFACEMAP = false;
  46358. }
  46359. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46361. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46362. defines.PARALLAX = true;
  46363. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46364. }
  46365. else {
  46366. defines.PARALLAX = false;
  46367. }
  46368. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46369. }
  46370. else {
  46371. defines.BUMP = false;
  46372. }
  46373. var refractionTexture = this._getRefractionTexture();
  46374. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46375. defines.REFRACTION = true;
  46376. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46377. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46378. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46379. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46380. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46381. if (this._linkRefractionWithTransparency) {
  46382. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46383. }
  46384. }
  46385. else {
  46386. defines.REFRACTION = false;
  46387. }
  46388. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46389. defines.ENVIRONMENTBRDF = true;
  46390. }
  46391. else {
  46392. defines.ENVIRONMENTBRDF = false;
  46393. }
  46394. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46395. defines.ALPHAFROMALBEDO = true;
  46396. }
  46397. else {
  46398. defines.ALPHAFROMALBEDO = false;
  46399. }
  46400. }
  46401. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46402. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46403. defines.USEPHYSICALLIGHTFALLOFF = false;
  46404. defines.USEGLTFLIGHTFALLOFF = false;
  46405. }
  46406. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46407. defines.USEPHYSICALLIGHTFALLOFF = false;
  46408. defines.USEGLTFLIGHTFALLOFF = true;
  46409. }
  46410. else {
  46411. defines.USEPHYSICALLIGHTFALLOFF = true;
  46412. defines.USEGLTFLIGHTFALLOFF = false;
  46413. }
  46414. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46415. if (!this.backFaceCulling && this._twoSidedLighting) {
  46416. defines.TWOSIDEDLIGHTING = true;
  46417. }
  46418. else {
  46419. defines.TWOSIDEDLIGHTING = false;
  46420. }
  46421. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46422. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46423. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46424. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46425. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46426. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46427. }
  46428. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46429. this._imageProcessingConfiguration.prepareDefines(defines);
  46430. }
  46431. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46432. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46433. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46434. // Misc.
  46435. if (defines._areMiscDirty) {
  46436. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46437. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46438. }
  46439. // Values that need to be evaluated on every frame
  46440. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46441. // Attribs
  46442. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46443. };
  46444. /**
  46445. * Force shader compilation
  46446. */
  46447. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46448. var _this = this;
  46449. var localOptions = __assign({ clipPlane: false }, options);
  46450. var defines = new PBRMaterialDefines();
  46451. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46452. if (effect.isReady()) {
  46453. if (onCompiled) {
  46454. onCompiled(this);
  46455. }
  46456. }
  46457. else {
  46458. effect.onCompileObservable.add(function () {
  46459. if (onCompiled) {
  46460. onCompiled(_this);
  46461. }
  46462. });
  46463. }
  46464. };
  46465. /**
  46466. * Initializes the uniform buffer layout for the shader.
  46467. */
  46468. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46469. // Order is important !
  46470. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46471. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46472. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46473. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46474. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46475. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46476. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46477. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46478. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46479. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46480. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46481. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46482. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46483. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46484. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46485. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46486. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46487. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46488. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46489. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46490. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46491. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46492. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46493. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46494. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46495. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46496. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46497. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46498. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46499. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46500. this._uniformBuffer.addUniform("pointSize", 1);
  46501. this._uniformBuffer.create();
  46502. };
  46503. /**
  46504. * Unbinds the textures.
  46505. */
  46506. PBRBaseMaterial.prototype.unbind = function () {
  46507. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46508. this._uniformBuffer.setTexture("reflectionSampler", null);
  46509. }
  46510. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46511. this._uniformBuffer.setTexture("refractionSampler", null);
  46512. }
  46513. _super.prototype.unbind.call(this);
  46514. };
  46515. /**
  46516. * Binds the submesh data.
  46517. * @param world - The world matrix.
  46518. * @param mesh - The BJS mesh.
  46519. * @param subMesh - A submesh of the BJS mesh.
  46520. */
  46521. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46522. var scene = this.getScene();
  46523. var defines = subMesh._materialDefines;
  46524. if (!defines) {
  46525. return;
  46526. }
  46527. var effect = subMesh.effect;
  46528. if (!effect) {
  46529. return;
  46530. }
  46531. this._activeEffect = effect;
  46532. // Matrices
  46533. this.bindOnlyWorldMatrix(world);
  46534. // Normal Matrix
  46535. if (defines.OBJECTSPACE_NORMALMAP) {
  46536. world.toNormalMatrix(this._normalMatrix);
  46537. this.bindOnlyNormalMatrix(this._normalMatrix);
  46538. }
  46539. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46540. // Bones
  46541. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46542. var reflectionTexture = null;
  46543. if (mustRebind) {
  46544. this._uniformBuffer.bindToEffect(effect, "Material");
  46545. this.bindViewProjection(effect);
  46546. reflectionTexture = this._getReflectionTexture();
  46547. var refractionTexture = this._getRefractionTexture();
  46548. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46549. // Texture uniforms
  46550. if (scene.texturesEnabled) {
  46551. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46552. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46553. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46554. }
  46555. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46556. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46557. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46558. }
  46559. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46560. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46561. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46562. }
  46563. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46564. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46565. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46566. if (reflectionTexture.boundingBoxSize) {
  46567. var cubeTexture = reflectionTexture;
  46568. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46569. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46570. }
  46571. var polynomials = reflectionTexture.sphericalPolynomial;
  46572. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46573. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46574. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46575. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46576. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46577. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46578. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46579. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46580. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46581. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46582. }
  46583. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46584. }
  46585. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46586. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46587. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46588. }
  46589. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46590. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46591. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46592. }
  46593. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46594. if (this._metallicTexture) {
  46595. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46596. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46597. }
  46598. else if (this._reflectivityTexture) {
  46599. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46600. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46601. }
  46602. if (this._microSurfaceTexture) {
  46603. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46604. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46605. }
  46606. }
  46607. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46608. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46609. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46610. if (scene._mirroredCameraPosition) {
  46611. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46612. }
  46613. else {
  46614. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46615. }
  46616. }
  46617. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46618. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46619. var depth = 1.0;
  46620. if (!refractionTexture.isCube) {
  46621. if (refractionTexture.depth) {
  46622. depth = refractionTexture.depth;
  46623. }
  46624. }
  46625. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46626. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46627. }
  46628. }
  46629. // Point size
  46630. if (this.pointsCloud) {
  46631. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46632. }
  46633. // Colors
  46634. if (defines.METALLICWORKFLOW) {
  46635. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46636. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46637. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46638. }
  46639. else {
  46640. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46641. }
  46642. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46643. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46644. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46645. // Misc
  46646. this._lightingInfos.x = this._directIntensity;
  46647. this._lightingInfos.y = this._emissiveIntensity;
  46648. this._lightingInfos.z = this._environmentIntensity;
  46649. this._lightingInfos.w = this._specularIntensity;
  46650. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46651. }
  46652. // Textures
  46653. if (scene.texturesEnabled) {
  46654. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46655. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46656. }
  46657. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46658. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46659. }
  46660. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46661. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46662. }
  46663. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46664. if (defines.LODBASEDMICROSFURACE) {
  46665. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46666. }
  46667. else {
  46668. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46669. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46670. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46671. }
  46672. }
  46673. if (defines.ENVIRONMENTBRDF) {
  46674. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46675. }
  46676. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46677. if (defines.LODBASEDMICROSFURACE) {
  46678. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46679. }
  46680. else {
  46681. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46682. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46683. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46684. }
  46685. }
  46686. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46687. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46688. }
  46689. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46690. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46691. }
  46692. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46693. if (this._metallicTexture) {
  46694. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46695. }
  46696. else if (this._reflectivityTexture) {
  46697. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46698. }
  46699. if (this._microSurfaceTexture) {
  46700. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46701. }
  46702. }
  46703. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46704. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46705. }
  46706. }
  46707. // Clip plane
  46708. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46709. // Colors
  46710. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46711. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46712. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46713. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46714. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46715. }
  46716. if (mustRebind || !this.isFrozen) {
  46717. // Lights
  46718. if (scene.lightsEnabled && !this._disableLighting) {
  46719. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46720. }
  46721. // View
  46722. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46723. this.bindView(effect);
  46724. }
  46725. // Fog
  46726. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46727. // Morph targets
  46728. if (defines.NUM_MORPH_INFLUENCERS) {
  46729. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46730. }
  46731. // image processing
  46732. this._imageProcessingConfiguration.bind(this._activeEffect);
  46733. // Log. depth
  46734. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46735. }
  46736. this._uniformBuffer.update();
  46737. this._afterBind(mesh, this._activeEffect);
  46738. };
  46739. /**
  46740. * Returns the animatable textures.
  46741. * @returns - Array of animatable textures.
  46742. */
  46743. PBRBaseMaterial.prototype.getAnimatables = function () {
  46744. var results = [];
  46745. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46746. results.push(this._albedoTexture);
  46747. }
  46748. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46749. results.push(this._ambientTexture);
  46750. }
  46751. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46752. results.push(this._opacityTexture);
  46753. }
  46754. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46755. results.push(this._reflectionTexture);
  46756. }
  46757. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46758. results.push(this._emissiveTexture);
  46759. }
  46760. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46761. results.push(this._metallicTexture);
  46762. }
  46763. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46764. results.push(this._reflectivityTexture);
  46765. }
  46766. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46767. results.push(this._bumpTexture);
  46768. }
  46769. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46770. results.push(this._lightmapTexture);
  46771. }
  46772. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46773. results.push(this._refractionTexture);
  46774. }
  46775. return results;
  46776. };
  46777. /**
  46778. * Returns the texture used for reflections.
  46779. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46780. */
  46781. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46782. if (this._reflectionTexture) {
  46783. return this._reflectionTexture;
  46784. }
  46785. return this.getScene().environmentTexture;
  46786. };
  46787. /**
  46788. * Returns the texture used for refraction or null if none is used.
  46789. * @returns - Refection texture if present. If no refraction texture and refraction
  46790. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46791. */
  46792. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46793. if (this._refractionTexture) {
  46794. return this._refractionTexture;
  46795. }
  46796. if (this._linkRefractionWithTransparency) {
  46797. return this.getScene().environmentTexture;
  46798. }
  46799. return null;
  46800. };
  46801. /**
  46802. * Disposes the resources of the material.
  46803. * @param forceDisposeEffect - Forces the disposal of effects.
  46804. * @param forceDisposeTextures - Forces the disposal of all textures.
  46805. */
  46806. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46807. if (forceDisposeTextures) {
  46808. if (this._albedoTexture) {
  46809. this._albedoTexture.dispose();
  46810. }
  46811. if (this._ambientTexture) {
  46812. this._ambientTexture.dispose();
  46813. }
  46814. if (this._opacityTexture) {
  46815. this._opacityTexture.dispose();
  46816. }
  46817. if (this._reflectionTexture) {
  46818. this._reflectionTexture.dispose();
  46819. }
  46820. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46821. this._environmentBRDFTexture.dispose();
  46822. }
  46823. if (this._emissiveTexture) {
  46824. this._emissiveTexture.dispose();
  46825. }
  46826. if (this._metallicTexture) {
  46827. this._metallicTexture.dispose();
  46828. }
  46829. if (this._reflectivityTexture) {
  46830. this._reflectivityTexture.dispose();
  46831. }
  46832. if (this._bumpTexture) {
  46833. this._bumpTexture.dispose();
  46834. }
  46835. if (this._lightmapTexture) {
  46836. this._lightmapTexture.dispose();
  46837. }
  46838. if (this._refractionTexture) {
  46839. this._refractionTexture.dispose();
  46840. }
  46841. }
  46842. this._renderTargets.dispose();
  46843. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46844. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46845. }
  46846. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46847. };
  46848. /**
  46849. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46850. */
  46851. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46852. /**
  46853. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46854. * to enhance interoperability with other engines.
  46855. */
  46856. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46857. /**
  46858. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46859. * to enhance interoperability with other materials.
  46860. */
  46861. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46862. /**
  46863. * Stores the reflectivity values based on metallic roughness workflow.
  46864. */
  46865. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46866. __decorate([
  46867. BABYLON.serializeAsImageProcessingConfiguration()
  46868. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46869. __decorate([
  46870. BABYLON.serialize()
  46871. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46872. __decorate([
  46873. BABYLON.serialize()
  46874. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46875. return PBRBaseMaterial;
  46876. }(BABYLON.PushMaterial));
  46877. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46878. })(BABYLON || (BABYLON = {}));
  46879. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. /**
  46883. * The Physically based simple base material of BJS.
  46884. *
  46885. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46886. * It is used as the base class for both the specGloss and metalRough conventions.
  46887. */
  46888. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46889. __extends(PBRBaseSimpleMaterial, _super);
  46890. /**
  46891. * Instantiates a new PBRMaterial instance.
  46892. *
  46893. * @param name The material name
  46894. * @param scene The scene the material will be use in.
  46895. */
  46896. function PBRBaseSimpleMaterial(name, scene) {
  46897. var _this = _super.call(this, name, scene) || this;
  46898. /**
  46899. * Number of Simultaneous lights allowed on the material.
  46900. */
  46901. _this.maxSimultaneousLights = 4;
  46902. /**
  46903. * If sets to true, disables all the lights affecting the material.
  46904. */
  46905. _this.disableLighting = false;
  46906. /**
  46907. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46908. */
  46909. _this.invertNormalMapX = false;
  46910. /**
  46911. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46912. */
  46913. _this.invertNormalMapY = false;
  46914. /**
  46915. * Emissivie color used to self-illuminate the model.
  46916. */
  46917. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46918. /**
  46919. * Occlusion Channel Strenght.
  46920. */
  46921. _this.occlusionStrength = 1.0;
  46922. /**
  46923. * If true, the light map contains occlusion information instead of lighting info.
  46924. */
  46925. _this.useLightmapAsShadowmap = false;
  46926. _this._useAlphaFromAlbedoTexture = true;
  46927. _this._useAmbientInGrayScale = true;
  46928. return _this;
  46929. }
  46930. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46931. /**
  46932. * Gets the current double sided mode.
  46933. */
  46934. get: function () {
  46935. return this._twoSidedLighting;
  46936. },
  46937. /**
  46938. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46939. */
  46940. set: function (value) {
  46941. if (this._twoSidedLighting === value) {
  46942. return;
  46943. }
  46944. this._twoSidedLighting = value;
  46945. this.backFaceCulling = !value;
  46946. this._markAllSubMeshesAsTexturesDirty();
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. /**
  46952. * Return the active textures of the material.
  46953. */
  46954. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46955. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46956. if (this.environmentTexture) {
  46957. activeTextures.push(this.environmentTexture);
  46958. }
  46959. if (this.normalTexture) {
  46960. activeTextures.push(this.normalTexture);
  46961. }
  46962. if (this.emissiveTexture) {
  46963. activeTextures.push(this.emissiveTexture);
  46964. }
  46965. if (this.occlusionTexture) {
  46966. activeTextures.push(this.occlusionTexture);
  46967. }
  46968. if (this.lightmapTexture) {
  46969. activeTextures.push(this.lightmapTexture);
  46970. }
  46971. return activeTextures;
  46972. };
  46973. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46974. if (_super.prototype.hasTexture.call(this, texture)) {
  46975. return true;
  46976. }
  46977. if (this.lightmapTexture === texture) {
  46978. return true;
  46979. }
  46980. return false;
  46981. };
  46982. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46983. return "PBRBaseSimpleMaterial";
  46984. };
  46985. __decorate([
  46986. BABYLON.serialize(),
  46987. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46988. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46989. __decorate([
  46990. BABYLON.serialize(),
  46991. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46992. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46993. __decorate([
  46994. BABYLON.serializeAsTexture(),
  46995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46996. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46997. __decorate([
  46998. BABYLON.serialize(),
  46999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47000. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  47001. __decorate([
  47002. BABYLON.serialize(),
  47003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47004. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  47005. __decorate([
  47006. BABYLON.serializeAsTexture(),
  47007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  47008. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  47009. __decorate([
  47010. BABYLON.serializeAsColor3("emissive"),
  47011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47012. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  47013. __decorate([
  47014. BABYLON.serializeAsTexture(),
  47015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47016. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  47017. __decorate([
  47018. BABYLON.serialize(),
  47019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  47020. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  47021. __decorate([
  47022. BABYLON.serializeAsTexture(),
  47023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  47024. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  47025. __decorate([
  47026. BABYLON.serialize(),
  47027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  47028. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  47029. __decorate([
  47030. BABYLON.serialize()
  47031. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  47032. __decorate([
  47033. BABYLON.serializeAsTexture(),
  47034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47035. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  47036. __decorate([
  47037. BABYLON.serialize(),
  47038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47039. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47040. return PBRBaseSimpleMaterial;
  47041. }(BABYLON.PBRBaseMaterial));
  47042. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  47043. })(BABYLON || (BABYLON = {}));
  47044. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  47045. var BABYLON;
  47046. (function (BABYLON) {
  47047. /**
  47048. * The Physically based material of BJS.
  47049. *
  47050. * This offers the main features of a standard PBR material.
  47051. * For more information, please refer to the documentation :
  47052. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47053. */
  47054. var PBRMaterial = /** @class */ (function (_super) {
  47055. __extends(PBRMaterial, _super);
  47056. /**
  47057. * Instantiates a new PBRMaterial instance.
  47058. *
  47059. * @param name The material name
  47060. * @param scene The scene the material will be use in.
  47061. */
  47062. function PBRMaterial(name, scene) {
  47063. var _this = _super.call(this, name, scene) || this;
  47064. /**
  47065. * Intensity of the direct lights e.g. the four lights available in your scene.
  47066. * This impacts both the direct diffuse and specular highlights.
  47067. */
  47068. _this.directIntensity = 1.0;
  47069. /**
  47070. * Intensity of the emissive part of the material.
  47071. * This helps controlling the emissive effect without modifying the emissive color.
  47072. */
  47073. _this.emissiveIntensity = 1.0;
  47074. /**
  47075. * Intensity of the environment e.g. how much the environment will light the object
  47076. * either through harmonics for rough material or through the refelction for shiny ones.
  47077. */
  47078. _this.environmentIntensity = 1.0;
  47079. /**
  47080. * This is a special control allowing the reduction of the specular highlights coming from the
  47081. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47082. */
  47083. _this.specularIntensity = 1.0;
  47084. /**
  47085. * Debug Control allowing disabling the bump map on this material.
  47086. */
  47087. _this.disableBumpMap = false;
  47088. /**
  47089. * AKA Occlusion Texture Intensity in other nomenclature.
  47090. */
  47091. _this.ambientTextureStrength = 1.0;
  47092. /**
  47093. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47094. * 1 means it completely occludes it
  47095. * 0 mean it has no impact
  47096. */
  47097. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47098. /**
  47099. * The color of a material in ambient lighting.
  47100. */
  47101. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47102. /**
  47103. * AKA Diffuse Color in other nomenclature.
  47104. */
  47105. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47106. /**
  47107. * AKA Specular Color in other nomenclature.
  47108. */
  47109. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47110. /**
  47111. * The color reflected from the material.
  47112. */
  47113. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47114. /**
  47115. * The color emitted from the material.
  47116. */
  47117. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47118. /**
  47119. * AKA Glossiness in other nomenclature.
  47120. */
  47121. _this.microSurface = 1.0;
  47122. /**
  47123. * source material index of refraction (IOR)' / 'destination material IOR.
  47124. */
  47125. _this.indexOfRefraction = 0.66;
  47126. /**
  47127. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  47128. */
  47129. _this.invertRefractionY = false;
  47130. /**
  47131. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47132. * Materials half opaque for instance using refraction could benefit from this control.
  47133. */
  47134. _this.linkRefractionWithTransparency = false;
  47135. /**
  47136. * If true, the light map contains occlusion information instead of lighting info.
  47137. */
  47138. _this.useLightmapAsShadowmap = false;
  47139. /**
  47140. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47141. */
  47142. _this.useAlphaFromAlbedoTexture = false;
  47143. /**
  47144. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47145. */
  47146. _this.forceAlphaTest = false;
  47147. /**
  47148. * Defines the alpha limits in alpha test mode.
  47149. */
  47150. _this.alphaCutOff = 0.4;
  47151. /**
  47152. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47153. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47154. */
  47155. _this.useSpecularOverAlpha = true;
  47156. /**
  47157. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47158. */
  47159. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47160. /**
  47161. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47162. */
  47163. _this.useRoughnessFromMetallicTextureAlpha = true;
  47164. /**
  47165. * Specifies if the metallic texture contains the roughness information in its green channel.
  47166. */
  47167. _this.useRoughnessFromMetallicTextureGreen = false;
  47168. /**
  47169. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47170. */
  47171. _this.useMetallnessFromMetallicTextureBlue = false;
  47172. /**
  47173. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47174. */
  47175. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47176. /**
  47177. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47178. */
  47179. _this.useAmbientInGrayScale = false;
  47180. /**
  47181. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47182. * The material will try to infer what glossiness each pixel should be.
  47183. */
  47184. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47185. /**
  47186. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47187. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47188. */
  47189. _this.useRadianceOverAlpha = true;
  47190. /**
  47191. * Allows using an object space normal map (instead of tangent space).
  47192. */
  47193. _this.useObjectSpaceNormalMap = false;
  47194. /**
  47195. * Allows using the bump map in parallax mode.
  47196. */
  47197. _this.useParallax = false;
  47198. /**
  47199. * Allows using the bump map in parallax occlusion mode.
  47200. */
  47201. _this.useParallaxOcclusion = false;
  47202. /**
  47203. * Controls the scale bias of the parallax mode.
  47204. */
  47205. _this.parallaxScaleBias = 0.05;
  47206. /**
  47207. * If sets to true, disables all the lights affecting the material.
  47208. */
  47209. _this.disableLighting = false;
  47210. /**
  47211. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47212. */
  47213. _this.forceIrradianceInFragment = false;
  47214. /**
  47215. * Number of Simultaneous lights allowed on the material.
  47216. */
  47217. _this.maxSimultaneousLights = 4;
  47218. /**
  47219. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47220. */
  47221. _this.invertNormalMapX = false;
  47222. /**
  47223. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47224. */
  47225. _this.invertNormalMapY = false;
  47226. /**
  47227. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47228. */
  47229. _this.twoSidedLighting = false;
  47230. /**
  47231. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47232. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47233. */
  47234. _this.useAlphaFresnel = false;
  47235. /**
  47236. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47237. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47238. */
  47239. _this.useLinearAlphaFresnel = false;
  47240. /**
  47241. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47242. * And/Or occlude the blended part.
  47243. */
  47244. _this.environmentBRDFTexture = null;
  47245. /**
  47246. * Force normal to face away from face.
  47247. */
  47248. _this.forceNormalForward = false;
  47249. /**
  47250. * Enables specular anti aliasing in the PBR shader.
  47251. * It will both interacts on the Geometry for analytical and IBL lighting.
  47252. * It also prefilter the roughness map based on the bump values.
  47253. */
  47254. _this.enableSpecularAntiAliasing = false;
  47255. /**
  47256. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47257. * makes the reflect vector face the model (under horizon).
  47258. */
  47259. _this.useHorizonOcclusion = true;
  47260. /**
  47261. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47262. * too much the area relying on ambient texture to define their ambient occlusion.
  47263. */
  47264. _this.useRadianceOcclusion = true;
  47265. /**
  47266. * If set to true, no lighting calculations will be applied.
  47267. */
  47268. _this.unlit = false;
  47269. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47270. return _this;
  47271. }
  47272. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47273. /**
  47274. * BJS is using an harcoded light falloff based on a manually sets up range.
  47275. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47276. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47277. */
  47278. get: function () {
  47279. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47280. },
  47281. /**
  47282. * BJS is using an harcoded light falloff based on a manually sets up range.
  47283. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47284. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47285. */
  47286. set: function (value) {
  47287. if (value !== this.usePhysicalLightFalloff) {
  47288. // Ensure the effect will be rebuilt.
  47289. this._markAllSubMeshesAsTexturesDirty();
  47290. if (value) {
  47291. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47292. }
  47293. else {
  47294. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47295. }
  47296. }
  47297. },
  47298. enumerable: true,
  47299. configurable: true
  47300. });
  47301. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47302. /**
  47303. * In order to support the falloff compatibility with gltf, a special mode has been added
  47304. * to reproduce the gltf light falloff.
  47305. */
  47306. get: function () {
  47307. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47308. },
  47309. /**
  47310. * In order to support the falloff compatibility with gltf, a special mode has been added
  47311. * to reproduce the gltf light falloff.
  47312. */
  47313. set: function (value) {
  47314. if (value !== this.useGLTFLightFalloff) {
  47315. // Ensure the effect will be rebuilt.
  47316. this._markAllSubMeshesAsTexturesDirty();
  47317. if (value) {
  47318. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47319. }
  47320. else {
  47321. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47322. }
  47323. }
  47324. },
  47325. enumerable: true,
  47326. configurable: true
  47327. });
  47328. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47329. /**
  47330. * Gets the image processing configuration used either in this material.
  47331. */
  47332. get: function () {
  47333. return this._imageProcessingConfiguration;
  47334. },
  47335. /**
  47336. * Sets the Default image processing configuration used either in the this material.
  47337. *
  47338. * If sets to null, the scene one is in use.
  47339. */
  47340. set: function (value) {
  47341. this._attachImageProcessingConfiguration(value);
  47342. // Ensure the effect will be rebuilt.
  47343. this._markAllSubMeshesAsTexturesDirty();
  47344. },
  47345. enumerable: true,
  47346. configurable: true
  47347. });
  47348. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47349. /**
  47350. * Gets wether the color curves effect is enabled.
  47351. */
  47352. get: function () {
  47353. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47354. },
  47355. /**
  47356. * Sets wether the color curves effect is enabled.
  47357. */
  47358. set: function (value) {
  47359. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47360. },
  47361. enumerable: true,
  47362. configurable: true
  47363. });
  47364. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47365. /**
  47366. * Gets wether the color grading effect is enabled.
  47367. */
  47368. get: function () {
  47369. return this.imageProcessingConfiguration.colorGradingEnabled;
  47370. },
  47371. /**
  47372. * Gets wether the color grading effect is enabled.
  47373. */
  47374. set: function (value) {
  47375. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47376. },
  47377. enumerable: true,
  47378. configurable: true
  47379. });
  47380. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47381. /**
  47382. * Gets wether tonemapping is enabled or not.
  47383. */
  47384. get: function () {
  47385. return this._imageProcessingConfiguration.toneMappingEnabled;
  47386. },
  47387. /**
  47388. * Sets wether tonemapping is enabled or not
  47389. */
  47390. set: function (value) {
  47391. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47392. },
  47393. enumerable: true,
  47394. configurable: true
  47395. });
  47396. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47397. /**
  47398. * The camera exposure used on this material.
  47399. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47400. * This corresponds to a photographic exposure.
  47401. */
  47402. get: function () {
  47403. return this._imageProcessingConfiguration.exposure;
  47404. },
  47405. /**
  47406. * The camera exposure used on this material.
  47407. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47408. * This corresponds to a photographic exposure.
  47409. */
  47410. set: function (value) {
  47411. this._imageProcessingConfiguration.exposure = value;
  47412. },
  47413. enumerable: true,
  47414. configurable: true
  47415. });
  47416. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47417. /**
  47418. * Gets The camera contrast used on this material.
  47419. */
  47420. get: function () {
  47421. return this._imageProcessingConfiguration.contrast;
  47422. },
  47423. /**
  47424. * Sets The camera contrast used on this material.
  47425. */
  47426. set: function (value) {
  47427. this._imageProcessingConfiguration.contrast = value;
  47428. },
  47429. enumerable: true,
  47430. configurable: true
  47431. });
  47432. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47433. /**
  47434. * Gets the Color Grading 2D Lookup Texture.
  47435. */
  47436. get: function () {
  47437. return this._imageProcessingConfiguration.colorGradingTexture;
  47438. },
  47439. /**
  47440. * Sets the Color Grading 2D Lookup Texture.
  47441. */
  47442. set: function (value) {
  47443. this._imageProcessingConfiguration.colorGradingTexture = value;
  47444. },
  47445. enumerable: true,
  47446. configurable: true
  47447. });
  47448. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47449. /**
  47450. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47451. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47452. * 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;
  47453. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47454. */
  47455. get: function () {
  47456. return this._imageProcessingConfiguration.colorCurves;
  47457. },
  47458. /**
  47459. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47460. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47461. * 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;
  47462. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47463. */
  47464. set: function (value) {
  47465. this._imageProcessingConfiguration.colorCurves = value;
  47466. },
  47467. enumerable: true,
  47468. configurable: true
  47469. });
  47470. /**
  47471. * Returns the name of this material class.
  47472. */
  47473. PBRMaterial.prototype.getClassName = function () {
  47474. return "PBRMaterial";
  47475. };
  47476. /**
  47477. * Returns an array of the actively used textures.
  47478. * @returns - Array of BaseTextures
  47479. */
  47480. PBRMaterial.prototype.getActiveTextures = function () {
  47481. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47482. if (this._albedoTexture) {
  47483. activeTextures.push(this._albedoTexture);
  47484. }
  47485. if (this._ambientTexture) {
  47486. activeTextures.push(this._ambientTexture);
  47487. }
  47488. if (this._opacityTexture) {
  47489. activeTextures.push(this._opacityTexture);
  47490. }
  47491. if (this._reflectionTexture) {
  47492. activeTextures.push(this._reflectionTexture);
  47493. }
  47494. if (this._emissiveTexture) {
  47495. activeTextures.push(this._emissiveTexture);
  47496. }
  47497. if (this._reflectivityTexture) {
  47498. activeTextures.push(this._reflectivityTexture);
  47499. }
  47500. if (this._metallicTexture) {
  47501. activeTextures.push(this._metallicTexture);
  47502. }
  47503. if (this._microSurfaceTexture) {
  47504. activeTextures.push(this._microSurfaceTexture);
  47505. }
  47506. if (this._bumpTexture) {
  47507. activeTextures.push(this._bumpTexture);
  47508. }
  47509. if (this._lightmapTexture) {
  47510. activeTextures.push(this._lightmapTexture);
  47511. }
  47512. if (this._refractionTexture) {
  47513. activeTextures.push(this._refractionTexture);
  47514. }
  47515. return activeTextures;
  47516. };
  47517. /**
  47518. * Checks to see if a texture is used in the material.
  47519. * @param texture - Base texture to use.
  47520. * @returns - Boolean specifying if a texture is used in the material.
  47521. */
  47522. PBRMaterial.prototype.hasTexture = function (texture) {
  47523. if (_super.prototype.hasTexture.call(this, texture)) {
  47524. return true;
  47525. }
  47526. if (this._albedoTexture === texture) {
  47527. return true;
  47528. }
  47529. if (this._ambientTexture === texture) {
  47530. return true;
  47531. }
  47532. if (this._opacityTexture === texture) {
  47533. return true;
  47534. }
  47535. if (this._reflectionTexture === texture) {
  47536. return true;
  47537. }
  47538. if (this._reflectivityTexture === texture) {
  47539. return true;
  47540. }
  47541. if (this._metallicTexture === texture) {
  47542. return true;
  47543. }
  47544. if (this._microSurfaceTexture === texture) {
  47545. return true;
  47546. }
  47547. if (this._bumpTexture === texture) {
  47548. return true;
  47549. }
  47550. if (this._lightmapTexture === texture) {
  47551. return true;
  47552. }
  47553. if (this._refractionTexture === texture) {
  47554. return true;
  47555. }
  47556. return false;
  47557. };
  47558. /**
  47559. * Makes a duplicate of the current material.
  47560. * @param name - name to use for the new material.
  47561. */
  47562. PBRMaterial.prototype.clone = function (name) {
  47563. var _this = this;
  47564. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47565. clone.id = name;
  47566. clone.name = name;
  47567. return clone;
  47568. };
  47569. /**
  47570. * Serializes this PBR Material.
  47571. * @returns - An object with the serialized material.
  47572. */
  47573. PBRMaterial.prototype.serialize = function () {
  47574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47575. serializationObject.customType = "BABYLON.PBRMaterial";
  47576. return serializationObject;
  47577. };
  47578. // Statics
  47579. /**
  47580. * Parses a PBR Material from a serialized object.
  47581. * @param source - Serialized object.
  47582. * @param scene - BJS scene instance.
  47583. * @param rootUrl - url for the scene object
  47584. * @returns - PBRMaterial
  47585. */
  47586. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47587. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47588. };
  47589. /**
  47590. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47591. */
  47592. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47593. /**
  47594. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47595. */
  47596. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47597. /**
  47598. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47599. */
  47600. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47601. /**
  47602. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47603. * They are also discarded below the alpha cutoff threshold to improve performances.
  47604. */
  47605. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47606. /**
  47607. * Defines the default value of how much AO map is occluding the analytical lights
  47608. * (point spot...).
  47609. */
  47610. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47611. __decorate([
  47612. BABYLON.serialize(),
  47613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47614. ], PBRMaterial.prototype, "directIntensity", void 0);
  47615. __decorate([
  47616. BABYLON.serialize(),
  47617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47618. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47619. __decorate([
  47620. BABYLON.serialize(),
  47621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47622. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47623. __decorate([
  47624. BABYLON.serialize(),
  47625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47626. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47627. __decorate([
  47628. BABYLON.serialize(),
  47629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47630. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47631. __decorate([
  47632. BABYLON.serializeAsTexture(),
  47633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47634. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47635. __decorate([
  47636. BABYLON.serializeAsTexture(),
  47637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47638. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47639. __decorate([
  47640. BABYLON.serialize(),
  47641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47642. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47643. __decorate([
  47644. BABYLON.serialize(),
  47645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47646. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47647. __decorate([
  47648. BABYLON.serializeAsTexture(),
  47649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47650. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47651. __decorate([
  47652. BABYLON.serializeAsTexture(),
  47653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47654. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47655. __decorate([
  47656. BABYLON.serializeAsTexture(),
  47657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47658. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47659. __decorate([
  47660. BABYLON.serializeAsTexture(),
  47661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47662. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47663. __decorate([
  47664. BABYLON.serializeAsTexture(),
  47665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47666. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47667. __decorate([
  47668. BABYLON.serialize(),
  47669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47670. ], PBRMaterial.prototype, "metallic", void 0);
  47671. __decorate([
  47672. BABYLON.serialize(),
  47673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47674. ], PBRMaterial.prototype, "roughness", void 0);
  47675. __decorate([
  47676. BABYLON.serializeAsTexture(),
  47677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47678. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47679. __decorate([
  47680. BABYLON.serializeAsTexture(),
  47681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47682. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47683. __decorate([
  47684. BABYLON.serializeAsTexture(),
  47685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47686. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47687. __decorate([
  47688. BABYLON.serializeAsTexture(),
  47689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47690. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47691. __decorate([
  47692. BABYLON.serializeAsColor3("ambient"),
  47693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47694. ], PBRMaterial.prototype, "ambientColor", void 0);
  47695. __decorate([
  47696. BABYLON.serializeAsColor3("albedo"),
  47697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47698. ], PBRMaterial.prototype, "albedoColor", void 0);
  47699. __decorate([
  47700. BABYLON.serializeAsColor3("reflectivity"),
  47701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47702. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47703. __decorate([
  47704. BABYLON.serializeAsColor3("reflection"),
  47705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47706. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47707. __decorate([
  47708. BABYLON.serializeAsColor3("emissive"),
  47709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47710. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47711. __decorate([
  47712. BABYLON.serialize(),
  47713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47714. ], PBRMaterial.prototype, "microSurface", void 0);
  47715. __decorate([
  47716. BABYLON.serialize(),
  47717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47718. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47719. __decorate([
  47720. BABYLON.serialize(),
  47721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47722. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47723. __decorate([
  47724. BABYLON.serialize(),
  47725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47726. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47727. __decorate([
  47728. BABYLON.serialize(),
  47729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47730. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47731. __decorate([
  47732. BABYLON.serialize(),
  47733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47734. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47735. __decorate([
  47736. BABYLON.serialize(),
  47737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47738. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47739. __decorate([
  47740. BABYLON.serialize(),
  47741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47742. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47743. __decorate([
  47744. BABYLON.serialize(),
  47745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47746. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47747. __decorate([
  47748. BABYLON.serialize(),
  47749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47750. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47751. __decorate([
  47752. BABYLON.serialize(),
  47753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47754. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47755. __decorate([
  47756. BABYLON.serialize(),
  47757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47758. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47759. __decorate([
  47760. BABYLON.serialize(),
  47761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47762. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47763. __decorate([
  47764. BABYLON.serialize(),
  47765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47766. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47767. __decorate([
  47768. BABYLON.serialize(),
  47769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47770. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47771. __decorate([
  47772. BABYLON.serialize(),
  47773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47774. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47775. __decorate([
  47776. BABYLON.serialize()
  47777. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47778. __decorate([
  47779. BABYLON.serialize()
  47780. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47781. __decorate([
  47782. BABYLON.serialize(),
  47783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47784. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47785. __decorate([
  47786. BABYLON.serialize(),
  47787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47788. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47789. __decorate([
  47790. BABYLON.serialize(),
  47791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47792. ], PBRMaterial.prototype, "useParallax", void 0);
  47793. __decorate([
  47794. BABYLON.serialize(),
  47795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47796. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47797. __decorate([
  47798. BABYLON.serialize(),
  47799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47800. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47801. __decorate([
  47802. BABYLON.serialize(),
  47803. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47804. ], PBRMaterial.prototype, "disableLighting", void 0);
  47805. __decorate([
  47806. BABYLON.serialize(),
  47807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47808. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47809. __decorate([
  47810. BABYLON.serialize(),
  47811. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47812. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47813. __decorate([
  47814. BABYLON.serialize(),
  47815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47816. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47817. __decorate([
  47818. BABYLON.serialize(),
  47819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47820. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47821. __decorate([
  47822. BABYLON.serialize(),
  47823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47824. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47825. __decorate([
  47826. BABYLON.serialize(),
  47827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47828. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47829. __decorate([
  47830. BABYLON.serialize(),
  47831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47832. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47833. __decorate([
  47834. BABYLON.serializeAsTexture(),
  47835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47836. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47837. __decorate([
  47838. BABYLON.serialize(),
  47839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47840. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47841. __decorate([
  47842. BABYLON.serialize(),
  47843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47844. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47845. __decorate([
  47846. BABYLON.serialize(),
  47847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47848. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47849. __decorate([
  47850. BABYLON.serialize(),
  47851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47852. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47853. __decorate([
  47854. BABYLON.serialize(),
  47855. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47856. ], PBRMaterial.prototype, "unlit", void 0);
  47857. return PBRMaterial;
  47858. }(BABYLON.PBRBaseMaterial));
  47859. BABYLON.PBRMaterial = PBRMaterial;
  47860. })(BABYLON || (BABYLON = {}));
  47861. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47862. var BABYLON;
  47863. (function (BABYLON) {
  47864. /**
  47865. * The PBR material of BJS following the metal roughness convention.
  47866. *
  47867. * This fits to the PBR convention in the GLTF definition:
  47868. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47869. */
  47870. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47871. __extends(PBRMetallicRoughnessMaterial, _super);
  47872. /**
  47873. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47874. *
  47875. * @param name The material name
  47876. * @param scene The scene the material will be use in.
  47877. */
  47878. function PBRMetallicRoughnessMaterial(name, scene) {
  47879. var _this = _super.call(this, name, scene) || this;
  47880. _this._useRoughnessFromMetallicTextureAlpha = false;
  47881. _this._useRoughnessFromMetallicTextureGreen = true;
  47882. _this._useMetallnessFromMetallicTextureBlue = true;
  47883. _this.metallic = 1.0;
  47884. _this.roughness = 1.0;
  47885. return _this;
  47886. }
  47887. /**
  47888. * Return the currrent class name of the material.
  47889. */
  47890. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47891. return "PBRMetallicRoughnessMaterial";
  47892. };
  47893. /**
  47894. * Return the active textures of the material.
  47895. */
  47896. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47897. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47898. if (this.baseTexture) {
  47899. activeTextures.push(this.baseTexture);
  47900. }
  47901. if (this.metallicRoughnessTexture) {
  47902. activeTextures.push(this.metallicRoughnessTexture);
  47903. }
  47904. return activeTextures;
  47905. };
  47906. /**
  47907. * Checks to see if a texture is used in the material.
  47908. * @param texture - Base texture to use.
  47909. * @returns - Boolean specifying if a texture is used in the material.
  47910. */
  47911. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47912. if (_super.prototype.hasTexture.call(this, texture)) {
  47913. return true;
  47914. }
  47915. if (this.baseTexture === texture) {
  47916. return true;
  47917. }
  47918. if (this.metallicRoughnessTexture === texture) {
  47919. return true;
  47920. }
  47921. return false;
  47922. };
  47923. /**
  47924. * Makes a duplicate of the current material.
  47925. * @param name - name to use for the new material.
  47926. */
  47927. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47928. var _this = this;
  47929. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47930. clone.id = name;
  47931. clone.name = name;
  47932. return clone;
  47933. };
  47934. /**
  47935. * Serialize the material to a parsable JSON object.
  47936. */
  47937. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47939. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47940. return serializationObject;
  47941. };
  47942. /**
  47943. * Parses a JSON object correponding to the serialize function.
  47944. */
  47945. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47946. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47947. };
  47948. __decorate([
  47949. BABYLON.serializeAsColor3(),
  47950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47951. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47952. __decorate([
  47953. BABYLON.serializeAsTexture(),
  47954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47955. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47956. __decorate([
  47957. BABYLON.serialize(),
  47958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47959. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47960. __decorate([
  47961. BABYLON.serialize(),
  47962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47963. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47964. __decorate([
  47965. BABYLON.serializeAsTexture(),
  47966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47967. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47968. return PBRMetallicRoughnessMaterial;
  47969. }(BABYLON.PBRBaseSimpleMaterial));
  47970. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47971. })(BABYLON || (BABYLON = {}));
  47972. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47973. var BABYLON;
  47974. (function (BABYLON) {
  47975. /**
  47976. * The PBR material of BJS following the specular glossiness convention.
  47977. *
  47978. * This fits to the PBR convention in the GLTF definition:
  47979. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47980. */
  47981. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47982. __extends(PBRSpecularGlossinessMaterial, _super);
  47983. /**
  47984. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47985. *
  47986. * @param name The material name
  47987. * @param scene The scene the material will be use in.
  47988. */
  47989. function PBRSpecularGlossinessMaterial(name, scene) {
  47990. var _this = _super.call(this, name, scene) || this;
  47991. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47992. return _this;
  47993. }
  47994. /**
  47995. * Return the currrent class name of the material.
  47996. */
  47997. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47998. return "PBRSpecularGlossinessMaterial";
  47999. };
  48000. /**
  48001. * Return the active textures of the material.
  48002. */
  48003. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  48004. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48005. if (this.diffuseTexture) {
  48006. activeTextures.push(this.diffuseTexture);
  48007. }
  48008. if (this.specularGlossinessTexture) {
  48009. activeTextures.push(this.specularGlossinessTexture);
  48010. }
  48011. return activeTextures;
  48012. };
  48013. /**
  48014. * Checks to see if a texture is used in the material.
  48015. * @param texture - Base texture to use.
  48016. * @returns - Boolean specifying if a texture is used in the material.
  48017. */
  48018. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  48019. if (_super.prototype.hasTexture.call(this, texture)) {
  48020. return true;
  48021. }
  48022. if (this.diffuseTexture === texture) {
  48023. return true;
  48024. }
  48025. if (this.specularGlossinessTexture === texture) {
  48026. return true;
  48027. }
  48028. return false;
  48029. };
  48030. /**
  48031. * Makes a duplicate of the current material.
  48032. * @param name - name to use for the new material.
  48033. */
  48034. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  48035. var _this = this;
  48036. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  48037. clone.id = name;
  48038. clone.name = name;
  48039. return clone;
  48040. };
  48041. /**
  48042. * Serialize the material to a parsable JSON object.
  48043. */
  48044. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  48045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48046. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  48047. return serializationObject;
  48048. };
  48049. /**
  48050. * Parses a JSON object correponding to the serialize function.
  48051. */
  48052. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48053. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48054. };
  48055. __decorate([
  48056. BABYLON.serializeAsColor3("diffuse"),
  48057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48058. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48059. __decorate([
  48060. BABYLON.serializeAsTexture(),
  48061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48062. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48063. __decorate([
  48064. BABYLON.serializeAsColor3("specular"),
  48065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48066. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48067. __decorate([
  48068. BABYLON.serialize(),
  48069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48070. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48071. __decorate([
  48072. BABYLON.serializeAsTexture(),
  48073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48074. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48075. return PBRSpecularGlossinessMaterial;
  48076. }(BABYLON.PBRBaseSimpleMaterial));
  48077. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48078. })(BABYLON || (BABYLON = {}));
  48079. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  48080. var BABYLON;
  48081. (function (BABYLON) {
  48082. /**
  48083. * @ignore
  48084. * This is a list of all the different input types that are available in the application.
  48085. * Fo instance: ArcRotateCameraGamepadInput...
  48086. */
  48087. BABYLON.CameraInputTypes = {};
  48088. /**
  48089. * This represents the input manager used within a camera.
  48090. * It helps dealing with all the different kind of input attached to a camera.
  48091. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48092. */
  48093. var CameraInputsManager = /** @class */ (function () {
  48094. /**
  48095. * Instantiate a new Camera Input Manager.
  48096. * @param camera Defines the camera the input manager blongs to
  48097. */
  48098. function CameraInputsManager(camera) {
  48099. this.attached = {};
  48100. this.camera = camera;
  48101. this.checkInputs = function () { };
  48102. }
  48103. /**
  48104. * Add an input method to a camera
  48105. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48106. * @param input camera input method
  48107. */
  48108. CameraInputsManager.prototype.add = function (input) {
  48109. var type = input.getSimpleName();
  48110. if (this.attached[type]) {
  48111. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48112. return;
  48113. }
  48114. this.attached[type] = input;
  48115. input.camera = this.camera;
  48116. //for checkInputs, we are dynamically creating a function
  48117. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48118. if (input.checkInputs) {
  48119. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48120. }
  48121. if (this.attachedElement) {
  48122. input.attachControl(this.attachedElement);
  48123. }
  48124. };
  48125. /**
  48126. * Remove a specific input method from a camera
  48127. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48128. * @param inputToRemove camera input method
  48129. */
  48130. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48131. for (var cam in this.attached) {
  48132. var input = this.attached[cam];
  48133. if (input === inputToRemove) {
  48134. input.detachControl(this.attachedElement);
  48135. input.camera = null;
  48136. delete this.attached[cam];
  48137. this.rebuildInputCheck();
  48138. }
  48139. }
  48140. };
  48141. /**
  48142. * Remove a specific input type from a camera
  48143. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48144. * @param inputType the type of the input to remove
  48145. */
  48146. CameraInputsManager.prototype.removeByType = function (inputType) {
  48147. for (var cam in this.attached) {
  48148. var input = this.attached[cam];
  48149. if (input.getClassName() === inputType) {
  48150. input.detachControl(this.attachedElement);
  48151. input.camera = null;
  48152. delete this.attached[cam];
  48153. this.rebuildInputCheck();
  48154. }
  48155. }
  48156. };
  48157. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48158. var current = this.checkInputs;
  48159. return function () {
  48160. current();
  48161. fn();
  48162. };
  48163. };
  48164. /**
  48165. * Attach the input controls to the currently attached dom element to listen the events from.
  48166. * @param input Defines the input to attach
  48167. */
  48168. CameraInputsManager.prototype.attachInput = function (input) {
  48169. if (this.attachedElement) {
  48170. input.attachControl(this.attachedElement, this.noPreventDefault);
  48171. }
  48172. };
  48173. /**
  48174. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48175. * @param element Defines the dom element to collect the events from
  48176. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48177. */
  48178. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48179. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48180. if (this.attachedElement) {
  48181. return;
  48182. }
  48183. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48184. this.attachedElement = element;
  48185. this.noPreventDefault = noPreventDefault;
  48186. for (var cam in this.attached) {
  48187. this.attached[cam].attachControl(element, noPreventDefault);
  48188. }
  48189. };
  48190. /**
  48191. * Detach the current manager inputs controls from a specific dom element.
  48192. * @param element Defines the dom element to collect the events from
  48193. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48194. */
  48195. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48196. if (disconnect === void 0) { disconnect = false; }
  48197. if (this.attachedElement !== element) {
  48198. return;
  48199. }
  48200. for (var cam in this.attached) {
  48201. this.attached[cam].detachControl(element);
  48202. if (disconnect) {
  48203. this.attached[cam].camera = null;
  48204. }
  48205. }
  48206. this.attachedElement = null;
  48207. };
  48208. /**
  48209. * Rebuild the dynamic inputCheck function from the current list of
  48210. * defined inputs in the manager.
  48211. */
  48212. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48213. this.checkInputs = function () { };
  48214. for (var cam in this.attached) {
  48215. var input = this.attached[cam];
  48216. if (input.checkInputs) {
  48217. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48218. }
  48219. }
  48220. };
  48221. /**
  48222. * Remove all attached input methods from a camera
  48223. */
  48224. CameraInputsManager.prototype.clear = function () {
  48225. if (this.attachedElement) {
  48226. this.detachElement(this.attachedElement, true);
  48227. }
  48228. this.attached = {};
  48229. this.attachedElement = null;
  48230. this.checkInputs = function () { };
  48231. };
  48232. /**
  48233. * Serialize the current input manager attached to a camera.
  48234. * This ensures than once parsed,
  48235. * the input associated to the camera will be identical to the current ones
  48236. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48237. */
  48238. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48239. var inputs = {};
  48240. for (var cam in this.attached) {
  48241. var input = this.attached[cam];
  48242. var res = BABYLON.SerializationHelper.Serialize(input);
  48243. inputs[input.getClassName()] = res;
  48244. }
  48245. serializedCamera.inputsmgr = inputs;
  48246. };
  48247. /**
  48248. * Parses an input manager serialized JSON to restore the previous list of inputs
  48249. * and states associated to a camera.
  48250. * @param parsedCamera Defines the JSON to parse
  48251. */
  48252. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48253. var parsedInputs = parsedCamera.inputsmgr;
  48254. if (parsedInputs) {
  48255. this.clear();
  48256. for (var n in parsedInputs) {
  48257. var construct = BABYLON.CameraInputTypes[n];
  48258. if (construct) {
  48259. var parsedinput = parsedInputs[n];
  48260. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48261. this.add(input);
  48262. }
  48263. }
  48264. }
  48265. else {
  48266. //2016-03-08 this part is for managing backward compatibility
  48267. for (var n in this.attached) {
  48268. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48269. if (construct) {
  48270. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48271. this.remove(this.attached[n]);
  48272. this.add(input);
  48273. }
  48274. }
  48275. }
  48276. };
  48277. return CameraInputsManager;
  48278. }());
  48279. BABYLON.CameraInputsManager = CameraInputsManager;
  48280. })(BABYLON || (BABYLON = {}));
  48281. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  48282. var BABYLON;
  48283. (function (BABYLON) {
  48284. /**
  48285. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48286. * This is the base of the follow, arc rotate cameras and Free camera
  48287. * @see http://doc.babylonjs.com/features/cameras
  48288. */
  48289. var TargetCamera = /** @class */ (function (_super) {
  48290. __extends(TargetCamera, _super);
  48291. /**
  48292. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48293. * This is the base of the follow, arc rotate cameras and Free camera
  48294. * @see http://doc.babylonjs.com/features/cameras
  48295. * @param name Defines the name of the camera in the scene
  48296. * @param position Defines the start position of the camera in the scene
  48297. * @param scene Defines the scene the camera belongs to
  48298. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48299. */
  48300. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48301. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48302. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48303. /**
  48304. * Define the current direction the camera is moving to
  48305. */
  48306. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48307. /**
  48308. * Define the current rotation the camera is rotating to
  48309. */
  48310. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48311. /**
  48312. * Define the current rotation of the camera
  48313. */
  48314. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48315. /**
  48316. * Define the current speed of the camera
  48317. */
  48318. _this.speed = 2.0;
  48319. /**
  48320. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48321. * around all axis.
  48322. */
  48323. _this.noRotationConstraint = false;
  48324. /**
  48325. * Define the current target of the camera as an object or a position.
  48326. */
  48327. _this.lockedTarget = null;
  48328. /** @hidden */
  48329. _this._currentTarget = BABYLON.Vector3.Zero();
  48330. /** @hidden */
  48331. _this._viewMatrix = BABYLON.Matrix.Zero();
  48332. /** @hidden */
  48333. _this._camMatrix = BABYLON.Matrix.Zero();
  48334. /** @hidden */
  48335. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48336. /** @hidden */
  48337. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48338. /** @hidden */
  48339. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48340. /** @hidden */
  48341. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48342. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48343. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48344. _this._defaultUp = BABYLON.Vector3.Up();
  48345. _this._cachedRotationZ = 0;
  48346. _this._cachedQuaternionRotationZ = 0;
  48347. return _this;
  48348. }
  48349. /**
  48350. * Gets the position in front of the camera at a given distance.
  48351. * @param distance The distance from the camera we want the position to be
  48352. * @returns the position
  48353. */
  48354. TargetCamera.prototype.getFrontPosition = function (distance) {
  48355. this.getWorldMatrix();
  48356. var direction = this.getTarget().subtract(this.position);
  48357. direction.normalize();
  48358. direction.scaleInPlace(distance);
  48359. return this.globalPosition.add(direction);
  48360. };
  48361. /** @hidden */
  48362. TargetCamera.prototype._getLockedTargetPosition = function () {
  48363. if (!this.lockedTarget) {
  48364. return null;
  48365. }
  48366. if (this.lockedTarget.absolutePosition) {
  48367. this.lockedTarget.computeWorldMatrix();
  48368. }
  48369. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48370. };
  48371. /**
  48372. * Store current camera state of the camera (fov, position, rotation, etc..)
  48373. * @returns the camera
  48374. */
  48375. TargetCamera.prototype.storeState = function () {
  48376. this._storedPosition = this.position.clone();
  48377. this._storedRotation = this.rotation.clone();
  48378. if (this.rotationQuaternion) {
  48379. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48380. }
  48381. return _super.prototype.storeState.call(this);
  48382. };
  48383. /**
  48384. * Restored camera state. You must call storeState() first
  48385. * @returns whether it was successful or not
  48386. * @hidden
  48387. */
  48388. TargetCamera.prototype._restoreStateValues = function () {
  48389. if (!_super.prototype._restoreStateValues.call(this)) {
  48390. return false;
  48391. }
  48392. this.position = this._storedPosition.clone();
  48393. this.rotation = this._storedRotation.clone();
  48394. if (this.rotationQuaternion) {
  48395. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48396. }
  48397. this.cameraDirection.copyFromFloats(0, 0, 0);
  48398. this.cameraRotation.copyFromFloats(0, 0);
  48399. return true;
  48400. };
  48401. /** @hidden */
  48402. TargetCamera.prototype._initCache = function () {
  48403. _super.prototype._initCache.call(this);
  48404. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48405. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48406. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48407. };
  48408. /** @hidden */
  48409. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48410. if (!ignoreParentClass) {
  48411. _super.prototype._updateCache.call(this);
  48412. }
  48413. var lockedTargetPosition = this._getLockedTargetPosition();
  48414. if (!lockedTargetPosition) {
  48415. this._cache.lockedTarget = null;
  48416. }
  48417. else {
  48418. if (!this._cache.lockedTarget) {
  48419. this._cache.lockedTarget = lockedTargetPosition.clone();
  48420. }
  48421. else {
  48422. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48423. }
  48424. }
  48425. this._cache.rotation.copyFrom(this.rotation);
  48426. if (this.rotationQuaternion) {
  48427. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48428. }
  48429. };
  48430. // Synchronized
  48431. /** @hidden */
  48432. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48433. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48434. return false;
  48435. }
  48436. var lockedTargetPosition = this._getLockedTargetPosition();
  48437. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48438. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48439. };
  48440. // Methods
  48441. /** @hidden */
  48442. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48443. var engine = this.getEngine();
  48444. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48445. };
  48446. // Target
  48447. /** @hidden */
  48448. TargetCamera.prototype.setTarget = function (target) {
  48449. this.upVector.normalize();
  48450. if (this.position.z === target.z) {
  48451. this.position.z += BABYLON.Epsilon;
  48452. }
  48453. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48454. this._camMatrix.invert();
  48455. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48456. var vDir = target.subtract(this.position);
  48457. if (vDir.x >= 0.0) {
  48458. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48459. }
  48460. else {
  48461. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48462. }
  48463. this.rotation.z = 0;
  48464. if (isNaN(this.rotation.x)) {
  48465. this.rotation.x = 0;
  48466. }
  48467. if (isNaN(this.rotation.y)) {
  48468. this.rotation.y = 0;
  48469. }
  48470. if (isNaN(this.rotation.z)) {
  48471. this.rotation.z = 0;
  48472. }
  48473. if (this.rotationQuaternion) {
  48474. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48475. }
  48476. };
  48477. /**
  48478. * Return the current target position of the camera. This value is expressed in local space.
  48479. * @returns the target position
  48480. */
  48481. TargetCamera.prototype.getTarget = function () {
  48482. return this._currentTarget;
  48483. };
  48484. /** @hidden */
  48485. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48486. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48487. };
  48488. /** @hidden */
  48489. TargetCamera.prototype._updatePosition = function () {
  48490. if (this.parent) {
  48491. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48492. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48493. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48494. return;
  48495. }
  48496. this.position.addInPlace(this.cameraDirection);
  48497. };
  48498. /** @hidden */
  48499. TargetCamera.prototype._checkInputs = function () {
  48500. var needToMove = this._decideIfNeedsToMove();
  48501. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48502. // Move
  48503. if (needToMove) {
  48504. this._updatePosition();
  48505. }
  48506. // Rotate
  48507. if (needToRotate) {
  48508. this.rotation.x += this.cameraRotation.x;
  48509. this.rotation.y += this.cameraRotation.y;
  48510. //rotate, if quaternion is set and rotation was used
  48511. if (this.rotationQuaternion) {
  48512. var len = this.rotation.lengthSquared();
  48513. if (len) {
  48514. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48515. }
  48516. }
  48517. if (!this.noRotationConstraint) {
  48518. var limit = (Math.PI / 2) * 0.95;
  48519. if (this.rotation.x > limit) {
  48520. this.rotation.x = limit;
  48521. }
  48522. if (this.rotation.x < -limit) {
  48523. this.rotation.x = -limit;
  48524. }
  48525. }
  48526. }
  48527. // Inertia
  48528. if (needToMove) {
  48529. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48530. this.cameraDirection.x = 0;
  48531. }
  48532. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48533. this.cameraDirection.y = 0;
  48534. }
  48535. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48536. this.cameraDirection.z = 0;
  48537. }
  48538. this.cameraDirection.scaleInPlace(this.inertia);
  48539. }
  48540. if (needToRotate) {
  48541. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48542. this.cameraRotation.x = 0;
  48543. }
  48544. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48545. this.cameraRotation.y = 0;
  48546. }
  48547. this.cameraRotation.scaleInPlace(this.inertia);
  48548. }
  48549. _super.prototype._checkInputs.call(this);
  48550. };
  48551. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48552. if (this.rotationQuaternion) {
  48553. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48554. }
  48555. else {
  48556. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48557. }
  48558. };
  48559. /**
  48560. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  48561. * @returns the current camera
  48562. */
  48563. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48564. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48565. return this;
  48566. };
  48567. /** @hidden */
  48568. TargetCamera.prototype._getViewMatrix = function () {
  48569. if (this.lockedTarget) {
  48570. this.setTarget(this._getLockedTargetPosition());
  48571. }
  48572. // Compute
  48573. this._updateCameraRotationMatrix();
  48574. // Apply the changed rotation to the upVector
  48575. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48576. this._rotateUpVectorWithCameraRotationMatrix();
  48577. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48578. }
  48579. else if (this._cachedRotationZ != this.rotation.z) {
  48580. this._rotateUpVectorWithCameraRotationMatrix();
  48581. this._cachedRotationZ = this.rotation.z;
  48582. }
  48583. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48584. // Computing target and final matrix
  48585. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48586. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48587. return this._viewMatrix;
  48588. };
  48589. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48590. if (this.parent) {
  48591. var parentWorldMatrix = this.parent.getWorldMatrix();
  48592. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48593. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48594. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48595. this._markSyncedWithParent();
  48596. }
  48597. else {
  48598. this._globalPosition.copyFrom(position);
  48599. this._globalCurrentTarget.copyFrom(target);
  48600. this._globalCurrentUpVector.copyFrom(up);
  48601. }
  48602. if (this.getScene().useRightHandedSystem) {
  48603. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48604. }
  48605. else {
  48606. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48607. }
  48608. };
  48609. /**
  48610. * @hidden
  48611. */
  48612. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48613. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48614. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48615. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48616. if (!this.rotationQuaternion) {
  48617. this.rotationQuaternion = new BABYLON.Quaternion();
  48618. }
  48619. rigCamera._cameraRigParams = {};
  48620. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48621. }
  48622. return rigCamera;
  48623. }
  48624. return null;
  48625. };
  48626. /**
  48627. * @hidden
  48628. */
  48629. TargetCamera.prototype._updateRigCameras = function () {
  48630. var camLeft = this._rigCameras[0];
  48631. var camRight = this._rigCameras[1];
  48632. switch (this.cameraRigMode) {
  48633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48637. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48638. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48639. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48640. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48641. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48642. camLeft.setTarget(this.getTarget());
  48643. camRight.setTarget(this.getTarget());
  48644. break;
  48645. case BABYLON.Camera.RIG_MODE_VR:
  48646. if (camLeft.rotationQuaternion) {
  48647. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48648. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48649. }
  48650. else {
  48651. camLeft.rotation.copyFrom(this.rotation);
  48652. camRight.rotation.copyFrom(this.rotation);
  48653. }
  48654. camLeft.position.copyFrom(this.position);
  48655. camRight.position.copyFrom(this.position);
  48656. break;
  48657. }
  48658. _super.prototype._updateRigCameras.call(this);
  48659. };
  48660. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48661. if (!this._rigCamTransformMatrix) {
  48662. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48663. }
  48664. var target = this.getTarget();
  48665. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48666. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48667. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48668. };
  48669. /**
  48670. * Gets the current object class name.
  48671. * @return the class name
  48672. */
  48673. TargetCamera.prototype.getClassName = function () {
  48674. return "TargetCamera";
  48675. };
  48676. __decorate([
  48677. BABYLON.serializeAsVector3()
  48678. ], TargetCamera.prototype, "rotation", void 0);
  48679. __decorate([
  48680. BABYLON.serialize()
  48681. ], TargetCamera.prototype, "speed", void 0);
  48682. __decorate([
  48683. BABYLON.serializeAsMeshReference("lockedTargetId")
  48684. ], TargetCamera.prototype, "lockedTarget", void 0);
  48685. return TargetCamera;
  48686. }(BABYLON.Camera));
  48687. BABYLON.TargetCamera = TargetCamera;
  48688. })(BABYLON || (BABYLON = {}));
  48689. //# sourceMappingURL=babylon.targetCamera.js.map
  48690. var BABYLON;
  48691. (function (BABYLON) {
  48692. /**
  48693. * Manage the mouse inputs to control the movement of a free camera.
  48694. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48695. */
  48696. var FreeCameraMouseInput = /** @class */ (function () {
  48697. /**
  48698. * Manage the mouse inputs to control the movement of a free camera.
  48699. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48700. * @param touchEnabled Defines if touch is enabled or not
  48701. */
  48702. function FreeCameraMouseInput(
  48703. /**
  48704. * Define if touch is enabled in the mouse input
  48705. */
  48706. touchEnabled) {
  48707. if (touchEnabled === void 0) { touchEnabled = true; }
  48708. this.touchEnabled = touchEnabled;
  48709. /**
  48710. * Defines the buttons associated with the input to handle camera move.
  48711. */
  48712. this.buttons = [0, 1, 2];
  48713. /**
  48714. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48715. */
  48716. this.angularSensibility = 2000.0;
  48717. this.previousPosition = null;
  48718. }
  48719. /**
  48720. * Attach the input controls to a specific dom element to get the input from.
  48721. * @param element Defines the element the controls should be listened from
  48722. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48723. */
  48724. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48725. var _this = this;
  48726. var engine = this.camera.getEngine();
  48727. if (!this._pointerInput) {
  48728. this._pointerInput = function (p, s) {
  48729. var evt = p.event;
  48730. if (engine.isInVRExclusivePointerMode) {
  48731. return;
  48732. }
  48733. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48734. return;
  48735. }
  48736. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48737. return;
  48738. }
  48739. var srcElement = (evt.srcElement || evt.target);
  48740. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48741. try {
  48742. srcElement.setPointerCapture(evt.pointerId);
  48743. }
  48744. catch (e) {
  48745. //Nothing to do with the error. Execution will continue.
  48746. }
  48747. _this.previousPosition = {
  48748. x: evt.clientX,
  48749. y: evt.clientY
  48750. };
  48751. if (!noPreventDefault) {
  48752. evt.preventDefault();
  48753. element.focus();
  48754. }
  48755. }
  48756. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48757. try {
  48758. srcElement.releasePointerCapture(evt.pointerId);
  48759. }
  48760. catch (e) {
  48761. //Nothing to do with the error.
  48762. }
  48763. _this.previousPosition = null;
  48764. if (!noPreventDefault) {
  48765. evt.preventDefault();
  48766. }
  48767. }
  48768. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48769. if (!_this.previousPosition || engine.isPointerLock) {
  48770. return;
  48771. }
  48772. var offsetX = evt.clientX - _this.previousPosition.x;
  48773. if (_this.camera.getScene().useRightHandedSystem) {
  48774. offsetX *= -1;
  48775. }
  48776. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48777. offsetX *= -1;
  48778. }
  48779. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48780. var offsetY = evt.clientY - _this.previousPosition.y;
  48781. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48782. _this.previousPosition = {
  48783. x: evt.clientX,
  48784. y: evt.clientY
  48785. };
  48786. if (!noPreventDefault) {
  48787. evt.preventDefault();
  48788. }
  48789. }
  48790. };
  48791. }
  48792. this._onMouseMove = function (evt) {
  48793. if (!engine.isPointerLock) {
  48794. return;
  48795. }
  48796. if (engine.isInVRExclusivePointerMode) {
  48797. return;
  48798. }
  48799. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48800. if (_this.camera.getScene().useRightHandedSystem) {
  48801. offsetX *= -1;
  48802. }
  48803. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48804. offsetX *= -1;
  48805. }
  48806. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48807. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48808. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48809. _this.previousPosition = null;
  48810. if (!noPreventDefault) {
  48811. evt.preventDefault();
  48812. }
  48813. };
  48814. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48815. element.addEventListener("mousemove", this._onMouseMove, false);
  48816. };
  48817. /**
  48818. * Detach the current controls from the specified dom element.
  48819. * @param element Defines the element to stop listening the inputs from
  48820. */
  48821. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48822. if (this._observer && element) {
  48823. this.camera.getScene().onPointerObservable.remove(this._observer);
  48824. if (this._onMouseMove) {
  48825. element.removeEventListener("mousemove", this._onMouseMove);
  48826. }
  48827. this._observer = null;
  48828. this._onMouseMove = null;
  48829. this.previousPosition = null;
  48830. }
  48831. };
  48832. /**
  48833. * Gets the class name of the current intput.
  48834. * @returns the class name
  48835. */
  48836. FreeCameraMouseInput.prototype.getClassName = function () {
  48837. return "FreeCameraMouseInput";
  48838. };
  48839. /**
  48840. * Get the friendly name associated with the input class.
  48841. * @returns the input friendly name
  48842. */
  48843. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48844. return "mouse";
  48845. };
  48846. __decorate([
  48847. BABYLON.serialize()
  48848. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48849. __decorate([
  48850. BABYLON.serialize()
  48851. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48852. return FreeCameraMouseInput;
  48853. }());
  48854. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48855. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48856. })(BABYLON || (BABYLON = {}));
  48857. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48858. var BABYLON;
  48859. (function (BABYLON) {
  48860. /**
  48861. * Manage the keyboard inputs to control the movement of a free camera.
  48862. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48863. */
  48864. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48865. function FreeCameraKeyboardMoveInput() {
  48866. /**
  48867. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48868. */
  48869. this.keysUp = [38];
  48870. /**
  48871. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48872. */
  48873. this.keysDown = [40];
  48874. /**
  48875. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48876. */
  48877. this.keysLeft = [37];
  48878. /**
  48879. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48880. */
  48881. this.keysRight = [39];
  48882. this._keys = new Array();
  48883. }
  48884. /**
  48885. * Attach the input controls to a specific dom element to get the input from.
  48886. * @param element Defines the element the controls should be listened from
  48887. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48888. */
  48889. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48890. var _this = this;
  48891. if (this._onCanvasBlurObserver) {
  48892. return;
  48893. }
  48894. this._scene = this.camera.getScene();
  48895. this._engine = this._scene.getEngine();
  48896. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48897. _this._keys = [];
  48898. });
  48899. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48900. var evt = info.event;
  48901. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48902. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48903. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48904. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48905. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48906. var index = _this._keys.indexOf(evt.keyCode);
  48907. if (index === -1) {
  48908. _this._keys.push(evt.keyCode);
  48909. }
  48910. if (!noPreventDefault) {
  48911. evt.preventDefault();
  48912. }
  48913. }
  48914. }
  48915. else {
  48916. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48917. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48918. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48919. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48920. var index = _this._keys.indexOf(evt.keyCode);
  48921. if (index >= 0) {
  48922. _this._keys.splice(index, 1);
  48923. }
  48924. if (!noPreventDefault) {
  48925. evt.preventDefault();
  48926. }
  48927. }
  48928. }
  48929. });
  48930. };
  48931. /**
  48932. * Detach the current controls from the specified dom element.
  48933. * @param element Defines the element to stop listening the inputs from
  48934. */
  48935. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48936. if (this._scene) {
  48937. if (this._onKeyboardObserver) {
  48938. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48939. }
  48940. if (this._onCanvasBlurObserver) {
  48941. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48942. }
  48943. this._onKeyboardObserver = null;
  48944. this._onCanvasBlurObserver = null;
  48945. }
  48946. this._keys = [];
  48947. };
  48948. /**
  48949. * Update the current camera state depending on the inputs that have been used this frame.
  48950. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48951. */
  48952. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48953. if (this._onKeyboardObserver) {
  48954. var camera = this.camera;
  48955. // Keyboard
  48956. for (var index = 0; index < this._keys.length; index++) {
  48957. var keyCode = this._keys[index];
  48958. var speed = camera._computeLocalCameraSpeed();
  48959. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48960. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48961. }
  48962. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48963. camera._localDirection.copyFromFloats(0, 0, speed);
  48964. }
  48965. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48966. camera._localDirection.copyFromFloats(speed, 0, 0);
  48967. }
  48968. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48969. camera._localDirection.copyFromFloats(0, 0, -speed);
  48970. }
  48971. if (camera.getScene().useRightHandedSystem) {
  48972. camera._localDirection.z *= -1;
  48973. }
  48974. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48975. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48976. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48977. }
  48978. }
  48979. };
  48980. /**
  48981. * Gets the class name of the current intput.
  48982. * @returns the class name
  48983. */
  48984. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48985. return "FreeCameraKeyboardMoveInput";
  48986. };
  48987. /** @hidden */
  48988. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48989. this._keys = [];
  48990. };
  48991. /**
  48992. * Get the friendly name associated with the input class.
  48993. * @returns the input friendly name
  48994. */
  48995. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48996. return "keyboard";
  48997. };
  48998. __decorate([
  48999. BABYLON.serialize()
  49000. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49001. __decorate([
  49002. BABYLON.serialize()
  49003. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49004. __decorate([
  49005. BABYLON.serialize()
  49006. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49007. __decorate([
  49008. BABYLON.serialize()
  49009. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49010. return FreeCameraKeyboardMoveInput;
  49011. }());
  49012. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  49013. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  49014. })(BABYLON || (BABYLON = {}));
  49015. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  49016. var BABYLON;
  49017. (function (BABYLON) {
  49018. /**
  49019. * Default Inputs manager for the FreeCamera.
  49020. * It groups all the default supported inputs for ease of use.
  49021. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49022. */
  49023. var FreeCameraInputsManager = /** @class */ (function (_super) {
  49024. __extends(FreeCameraInputsManager, _super);
  49025. /**
  49026. * Instantiates a new FreeCameraInputsManager.
  49027. * @param camera Defines the camera the inputs belong to
  49028. */
  49029. function FreeCameraInputsManager(camera) {
  49030. return _super.call(this, camera) || this;
  49031. }
  49032. /**
  49033. * Add keyboard input support to the input manager.
  49034. * @returns the current input manager
  49035. */
  49036. FreeCameraInputsManager.prototype.addKeyboard = function () {
  49037. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  49038. return this;
  49039. };
  49040. /**
  49041. * Add mouse input support to the input manager.
  49042. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  49043. * @returns the current input manager
  49044. */
  49045. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49046. if (touchEnabled === void 0) { touchEnabled = true; }
  49047. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  49048. return this;
  49049. };
  49050. /**
  49051. * Add orientation input support to the input manager.
  49052. * @returns the current input manager
  49053. */
  49054. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49055. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49056. return this;
  49057. };
  49058. /**
  49059. * Add touch input support to the input manager.
  49060. * @returns the current input manager
  49061. */
  49062. FreeCameraInputsManager.prototype.addTouch = function () {
  49063. this.add(new BABYLON.FreeCameraTouchInput());
  49064. return this;
  49065. };
  49066. /**
  49067. * Add virtual joystick input support to the input manager.
  49068. * @returns the current input manager
  49069. */
  49070. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49071. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49072. return this;
  49073. };
  49074. return FreeCameraInputsManager;
  49075. }(BABYLON.CameraInputsManager));
  49076. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49077. })(BABYLON || (BABYLON = {}));
  49078. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  49079. var BABYLON;
  49080. (function (BABYLON) {
  49081. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49082. // Forcing to use the Universal camera
  49083. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49084. });
  49085. /**
  49086. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49087. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49088. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49089. */
  49090. var FreeCamera = /** @class */ (function (_super) {
  49091. __extends(FreeCamera, _super);
  49092. /**
  49093. * Instantiates a Free Camera.
  49094. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49095. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49096. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49097. * @param name Define the name of the camera in the scene
  49098. * @param position Define the start position of the camera in the scene
  49099. * @param scene Define the scene the camera belongs to
  49100. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49101. */
  49102. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49103. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49104. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49105. /**
  49106. * Define the collision ellipsoid of the camera.
  49107. * This is helpful to simulate a camera body like the player body around the camera
  49108. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49109. */
  49110. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49111. /**
  49112. * Define an offset for the position of the ellipsoid around the camera.
  49113. * This can be helpful to determine the center of the body near the gravity center of the body
  49114. * instead of its head.
  49115. */
  49116. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49117. /**
  49118. * Enable or disable collisions of the camera with the rest of the scene objects.
  49119. */
  49120. _this.checkCollisions = false;
  49121. /**
  49122. * Enable or disable gravity on the camera.
  49123. */
  49124. _this.applyGravity = false;
  49125. _this._needMoveForGravity = false;
  49126. _this._oldPosition = BABYLON.Vector3.Zero();
  49127. _this._diffPosition = BABYLON.Vector3.Zero();
  49128. _this._newPosition = BABYLON.Vector3.Zero();
  49129. // Collisions
  49130. _this._collisionMask = -1;
  49131. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49132. if (collidedMesh === void 0) { collidedMesh = null; }
  49133. //TODO move this to the collision coordinator!
  49134. if (_this.getScene().workerCollisions) {
  49135. newPosition.multiplyInPlace(_this._collider._radius);
  49136. }
  49137. var updatePosition = function (newPos) {
  49138. _this._newPosition.copyFrom(newPos);
  49139. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49140. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49141. _this.position.addInPlace(_this._diffPosition);
  49142. if (_this.onCollide && collidedMesh) {
  49143. _this.onCollide(collidedMesh);
  49144. }
  49145. }
  49146. };
  49147. updatePosition(newPosition);
  49148. };
  49149. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49150. _this.inputs.addKeyboard().addMouse();
  49151. return _this;
  49152. }
  49153. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49154. /**
  49155. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49156. * Higher values reduce sensitivity.
  49157. */
  49158. get: function () {
  49159. var mouse = this.inputs.attached["mouse"];
  49160. if (mouse) {
  49161. return mouse.angularSensibility;
  49162. }
  49163. return 0;
  49164. },
  49165. /**
  49166. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49167. * Higher values reduce sensitivity.
  49168. */
  49169. set: function (value) {
  49170. var mouse = this.inputs.attached["mouse"];
  49171. if (mouse) {
  49172. mouse.angularSensibility = value;
  49173. }
  49174. },
  49175. enumerable: true,
  49176. configurable: true
  49177. });
  49178. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49179. /**
  49180. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49181. */
  49182. get: function () {
  49183. var keyboard = this.inputs.attached["keyboard"];
  49184. if (keyboard) {
  49185. return keyboard.keysUp;
  49186. }
  49187. return [];
  49188. },
  49189. set: function (value) {
  49190. var keyboard = this.inputs.attached["keyboard"];
  49191. if (keyboard) {
  49192. keyboard.keysUp = value;
  49193. }
  49194. },
  49195. enumerable: true,
  49196. configurable: true
  49197. });
  49198. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49199. /**
  49200. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49201. */
  49202. get: function () {
  49203. var keyboard = this.inputs.attached["keyboard"];
  49204. if (keyboard) {
  49205. return keyboard.keysDown;
  49206. }
  49207. return [];
  49208. },
  49209. set: function (value) {
  49210. var keyboard = this.inputs.attached["keyboard"];
  49211. if (keyboard) {
  49212. keyboard.keysDown = value;
  49213. }
  49214. },
  49215. enumerable: true,
  49216. configurable: true
  49217. });
  49218. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49219. /**
  49220. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49221. */
  49222. get: function () {
  49223. var keyboard = this.inputs.attached["keyboard"];
  49224. if (keyboard) {
  49225. return keyboard.keysLeft;
  49226. }
  49227. return [];
  49228. },
  49229. set: function (value) {
  49230. var keyboard = this.inputs.attached["keyboard"];
  49231. if (keyboard) {
  49232. keyboard.keysLeft = value;
  49233. }
  49234. },
  49235. enumerable: true,
  49236. configurable: true
  49237. });
  49238. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49239. /**
  49240. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49241. */
  49242. get: function () {
  49243. var keyboard = this.inputs.attached["keyboard"];
  49244. if (keyboard) {
  49245. return keyboard.keysRight;
  49246. }
  49247. return [];
  49248. },
  49249. set: function (value) {
  49250. var keyboard = this.inputs.attached["keyboard"];
  49251. if (keyboard) {
  49252. keyboard.keysRight = value;
  49253. }
  49254. },
  49255. enumerable: true,
  49256. configurable: true
  49257. });
  49258. /**
  49259. * Attached controls to the current camera.
  49260. * @param element Defines the element the controls should be listened from
  49261. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49262. */
  49263. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49264. this.inputs.attachElement(element, noPreventDefault);
  49265. };
  49266. /**
  49267. * Detach the current controls from the camera.
  49268. * The camera will stop reacting to inputs.
  49269. * @param element Defines the element to stop listening the inputs from
  49270. */
  49271. FreeCamera.prototype.detachControl = function (element) {
  49272. this.inputs.detachElement(element);
  49273. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49274. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49275. };
  49276. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  49277. /**
  49278. * Define a collision mask to limit the list of object the camera can collide with
  49279. */
  49280. get: function () {
  49281. return this._collisionMask;
  49282. },
  49283. set: function (mask) {
  49284. this._collisionMask = !isNaN(mask) ? mask : -1;
  49285. },
  49286. enumerable: true,
  49287. configurable: true
  49288. });
  49289. /** @hidden */
  49290. FreeCamera.prototype._collideWithWorld = function (displacement) {
  49291. var globalPosition;
  49292. if (this.parent) {
  49293. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  49294. }
  49295. else {
  49296. globalPosition = this.position;
  49297. }
  49298. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49299. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49300. if (!this._collider) {
  49301. this._collider = new BABYLON.Collider();
  49302. }
  49303. this._collider._radius = this.ellipsoid;
  49304. this._collider.collisionMask = this._collisionMask;
  49305. //no need for clone, as long as gravity is not on.
  49306. var actualDisplacement = displacement;
  49307. //add gravity to the direction to prevent the dual-collision checking
  49308. if (this.applyGravity) {
  49309. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49310. actualDisplacement = displacement.add(this.getScene().gravity);
  49311. }
  49312. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49313. };
  49314. /** @hidden */
  49315. FreeCamera.prototype._checkInputs = function () {
  49316. if (!this._localDirection) {
  49317. this._localDirection = BABYLON.Vector3.Zero();
  49318. this._transformedDirection = BABYLON.Vector3.Zero();
  49319. }
  49320. this.inputs.checkInputs();
  49321. _super.prototype._checkInputs.call(this);
  49322. };
  49323. /** @hidden */
  49324. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49325. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49326. };
  49327. /** @hidden */
  49328. FreeCamera.prototype._updatePosition = function () {
  49329. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49330. this._collideWithWorld(this.cameraDirection);
  49331. }
  49332. else {
  49333. _super.prototype._updatePosition.call(this);
  49334. }
  49335. };
  49336. /**
  49337. * Destroy the camera and release the current resources hold by it.
  49338. */
  49339. FreeCamera.prototype.dispose = function () {
  49340. this.inputs.clear();
  49341. _super.prototype.dispose.call(this);
  49342. };
  49343. /**
  49344. * Gets the current object class name.
  49345. * @return the class name
  49346. */
  49347. FreeCamera.prototype.getClassName = function () {
  49348. return "FreeCamera";
  49349. };
  49350. __decorate([
  49351. BABYLON.serializeAsVector3()
  49352. ], FreeCamera.prototype, "ellipsoid", void 0);
  49353. __decorate([
  49354. BABYLON.serializeAsVector3()
  49355. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49356. __decorate([
  49357. BABYLON.serialize()
  49358. ], FreeCamera.prototype, "checkCollisions", void 0);
  49359. __decorate([
  49360. BABYLON.serialize()
  49361. ], FreeCamera.prototype, "applyGravity", void 0);
  49362. return FreeCamera;
  49363. }(BABYLON.TargetCamera));
  49364. BABYLON.FreeCamera = FreeCamera;
  49365. })(BABYLON || (BABYLON = {}));
  49366. //# sourceMappingURL=babylon.freeCamera.js.map
  49367. var BABYLON;
  49368. (function (BABYLON) {
  49369. /**
  49370. * Listen to mouse events to control the camera.
  49371. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49372. */
  49373. var FlyCameraMouseInput = /** @class */ (function () {
  49374. /**
  49375. * Listen to mouse events to control the camera.
  49376. * @param touchEnabled Define if touch is enabled. (Default is true.)
  49377. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49378. */
  49379. function FlyCameraMouseInput(touchEnabled) {
  49380. if (touchEnabled === void 0) { touchEnabled = true; }
  49381. /**
  49382. * Defines the buttons associated with the input to handle camera rotation.
  49383. */
  49384. this.buttons = [0, 1, 2];
  49385. /**
  49386. * Assign buttons for Yaw control.
  49387. */
  49388. this.buttonsYaw = [-1, 0, 1];
  49389. /**
  49390. * Assign buttons for Pitch control.
  49391. */
  49392. this.buttonsPitch = [-1, 0, 1];
  49393. /**
  49394. * Assign buttons for Roll control.
  49395. */
  49396. this.buttonsRoll = [2];
  49397. /**
  49398. * Detect if any button is being pressed while mouse is moved.
  49399. * -1 = Mouse locked.
  49400. * 0 = Left button.
  49401. * 1 = Middle Button.
  49402. * 2 = Right Button.
  49403. */
  49404. this.activeButton = -1;
  49405. /**
  49406. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  49407. * Higher values reduce its sensitivity.
  49408. */
  49409. this.angularSensibility = 1000.0;
  49410. this.previousPosition = null;
  49411. }
  49412. /**
  49413. * Attach the mouse control to the HTML DOM element.
  49414. * @param element Defines the element that listens to the input events.
  49415. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  49416. */
  49417. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49418. var _this = this;
  49419. this.element = element;
  49420. this.noPreventDefault = noPreventDefault;
  49421. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  49422. _this._pointerInput(p, s);
  49423. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49424. // Correct Roll by rate, if enabled.
  49425. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  49426. if (_this.camera.rollCorrect) {
  49427. _this.camera.restoreRoll(_this.camera.rollCorrect);
  49428. }
  49429. });
  49430. // Helper function to keep 'this'.
  49431. this._mousemoveCallback = function (e) {
  49432. _this._onMouseMove(e);
  49433. };
  49434. element.addEventListener("mousemove", this._mousemoveCallback, false);
  49435. };
  49436. /**
  49437. * Detach the current controls from the specified dom element.
  49438. * @param element Defines the element to stop listening the inputs from
  49439. */
  49440. FlyCameraMouseInput.prototype.detachControl = function (element) {
  49441. if (this._observer && element) {
  49442. this.camera.getScene().onPointerObservable.remove(this._observer);
  49443. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  49444. if (this._mousemoveCallback) {
  49445. element.removeEventListener("mousemove", this._mousemoveCallback);
  49446. }
  49447. this._observer = null;
  49448. this._rollObserver = null;
  49449. this.previousPosition = null;
  49450. this.noPreventDefault = undefined;
  49451. }
  49452. };
  49453. /**
  49454. * Gets the class name of the current input.
  49455. * @returns the class name.
  49456. */
  49457. FlyCameraMouseInput.prototype.getClassName = function () {
  49458. return "FlyCameraMouseInput";
  49459. };
  49460. /**
  49461. * Get the friendly name associated with the input class.
  49462. * @returns the input's friendly name.
  49463. */
  49464. FlyCameraMouseInput.prototype.getSimpleName = function () {
  49465. return "mouse";
  49466. };
  49467. // Track mouse movement, when the pointer is not locked.
  49468. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  49469. var e = p.event;
  49470. var camera = this.camera;
  49471. var engine = camera.getEngine();
  49472. if (engine.isInVRExclusivePointerMode) {
  49473. return;
  49474. }
  49475. if (!this.touchEnabled && e.pointerType === "touch") {
  49476. return;
  49477. }
  49478. // Mouse is moved but an unknown mouse button is pressed.
  49479. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  49480. return;
  49481. }
  49482. var srcElement = (e.srcElement || e.target);
  49483. // Mouse down.
  49484. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49485. try {
  49486. srcElement.setPointerCapture(e.pointerId);
  49487. }
  49488. catch (e) {
  49489. // Nothing to do with the error. Execution continues.
  49490. }
  49491. this.previousPosition = {
  49492. x: e.clientX,
  49493. y: e.clientY
  49494. };
  49495. this.activeButton = e.button;
  49496. if (!this.noPreventDefault) {
  49497. e.preventDefault();
  49498. this.element.focus();
  49499. }
  49500. }
  49501. else
  49502. // Mouse up.
  49503. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49504. try {
  49505. srcElement.releasePointerCapture(e.pointerId);
  49506. }
  49507. catch (e) {
  49508. // Nothing to do with the error. Execution continues.
  49509. }
  49510. this.activeButton = -1;
  49511. this.previousPosition = null;
  49512. if (!this.noPreventDefault) {
  49513. e.preventDefault();
  49514. }
  49515. }
  49516. else
  49517. // Mouse move.
  49518. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49519. if (!this.previousPosition || engine.isPointerLock) {
  49520. return;
  49521. }
  49522. var offsetX = e.clientX - this.previousPosition.x;
  49523. var offsetY = e.clientY - this.previousPosition.y;
  49524. this.rotateCamera(offsetX, offsetY);
  49525. this.previousPosition = {
  49526. x: e.clientX,
  49527. y: e.clientY
  49528. };
  49529. if (!this.noPreventDefault) {
  49530. e.preventDefault();
  49531. }
  49532. }
  49533. };
  49534. // Track mouse movement, when pointer is locked.
  49535. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  49536. var camera = this.camera;
  49537. var engine = camera.getEngine();
  49538. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  49539. return;
  49540. }
  49541. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  49542. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  49543. this.rotateCamera(offsetX, offsetY);
  49544. this.previousPosition = null;
  49545. if (!this.noPreventDefault) {
  49546. e.preventDefault();
  49547. }
  49548. };
  49549. /**
  49550. * Rotate camera by mouse offset.
  49551. */
  49552. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  49553. var _this = this;
  49554. var camera = this.camera;
  49555. var scene = this.camera.getScene();
  49556. if (scene.useRightHandedSystem) {
  49557. offsetX *= -1;
  49558. }
  49559. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  49560. offsetX *= -1;
  49561. }
  49562. var x = offsetX / this.angularSensibility;
  49563. var y = offsetY / this.angularSensibility;
  49564. // Initialize to current rotation.
  49565. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  49566. var rotationChange;
  49567. // Pitch.
  49568. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  49569. // Apply change in Radians to vector Angle.
  49570. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  49571. // Apply Pitch to quaternion.
  49572. currentRotation.multiplyInPlace(rotationChange);
  49573. }
  49574. // Yaw.
  49575. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  49576. // Apply change in Radians to vector Angle.
  49577. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  49578. // Apply Yaw to quaternion.
  49579. currentRotation.multiplyInPlace(rotationChange);
  49580. // Add Roll, if banked turning is enabled, within Roll limit.
  49581. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  49582. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  49583. var bankingDelta = camera.bankedTurnMultiplier * -x;
  49584. // Apply change in Radians to vector Angle.
  49585. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  49586. // Apply Yaw to quaternion.
  49587. currentRotation.multiplyInPlace(rotationChange);
  49588. }
  49589. }
  49590. // Roll.
  49591. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  49592. // Apply change in Radians to vector Angle.
  49593. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  49594. // Track Rolling.
  49595. camera._trackRoll -= x;
  49596. // Apply Pitch to quaternion.
  49597. currentRotation.multiplyInPlace(rotationChange);
  49598. }
  49599. // Apply rotationQuaternion to Euler camera.rotation.
  49600. currentRotation.toEulerAnglesToRef(camera.rotation);
  49601. };
  49602. __decorate([
  49603. BABYLON.serialize()
  49604. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  49605. __decorate([
  49606. BABYLON.serialize()
  49607. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  49608. return FlyCameraMouseInput;
  49609. }());
  49610. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  49611. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  49612. })(BABYLON || (BABYLON = {}));
  49613. //# sourceMappingURL=babylon.flyCameraMouseInput.js.map
  49614. var BABYLON;
  49615. (function (BABYLON) {
  49616. /**
  49617. * Listen to keyboard events to control the camera.
  49618. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49619. */
  49620. var FlyCameraKeyboardInput = /** @class */ (function () {
  49621. function FlyCameraKeyboardInput() {
  49622. /**
  49623. * The list of keyboard keys used to control the forward move of the camera.
  49624. */
  49625. this.keysForward = [87];
  49626. /**
  49627. * The list of keyboard keys used to control the backward move of the camera.
  49628. */
  49629. this.keysBackward = [83];
  49630. /**
  49631. * The list of keyboard keys used to control the forward move of the camera.
  49632. */
  49633. this.keysUp = [69];
  49634. /**
  49635. * The list of keyboard keys used to control the backward move of the camera.
  49636. */
  49637. this.keysDown = [81];
  49638. /**
  49639. * The list of keyboard keys used to control the right strafe move of the camera.
  49640. */
  49641. this.keysRight = [68];
  49642. /**
  49643. * The list of keyboard keys used to control the left strafe move of the camera.
  49644. */
  49645. this.keysLeft = [65];
  49646. this._keys = new Array();
  49647. }
  49648. /**
  49649. * Attach the input controls to a specific dom element to get the input from.
  49650. * @param element Defines the element the controls should be listened from
  49651. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49652. */
  49653. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  49654. var _this = this;
  49655. if (this._onCanvasBlurObserver) {
  49656. return;
  49657. }
  49658. this._scene = this.camera.getScene();
  49659. this._engine = this._scene.getEngine();
  49660. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49661. _this._keys = [];
  49662. });
  49663. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49664. var evt = info.event;
  49665. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49666. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49667. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49668. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49669. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49670. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49671. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49672. var index = _this._keys.indexOf(evt.keyCode);
  49673. if (index === -1) {
  49674. _this._keys.push(evt.keyCode);
  49675. }
  49676. if (!noPreventDefault) {
  49677. evt.preventDefault();
  49678. }
  49679. }
  49680. }
  49681. else {
  49682. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49683. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49684. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49685. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49686. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49687. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49688. var index = _this._keys.indexOf(evt.keyCode);
  49689. if (index >= 0) {
  49690. _this._keys.splice(index, 1);
  49691. }
  49692. if (!noPreventDefault) {
  49693. evt.preventDefault();
  49694. }
  49695. }
  49696. }
  49697. });
  49698. };
  49699. /**
  49700. * Detach the current controls from the specified dom element.
  49701. * @param element Defines the element to stop listening the inputs from
  49702. */
  49703. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  49704. if (this._scene) {
  49705. if (this._onKeyboardObserver) {
  49706. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49707. }
  49708. if (this._onCanvasBlurObserver) {
  49709. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49710. }
  49711. this._onKeyboardObserver = null;
  49712. this._onCanvasBlurObserver = null;
  49713. }
  49714. this._keys = [];
  49715. };
  49716. /**
  49717. * Gets the class name of the current intput.
  49718. * @returns the class name
  49719. */
  49720. FlyCameraKeyboardInput.prototype.getClassName = function () {
  49721. return "FlyCameraKeyboardInput";
  49722. };
  49723. /** @hidden */
  49724. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  49725. this._keys = [];
  49726. };
  49727. /**
  49728. * Get the friendly name associated with the input class.
  49729. * @returns the input friendly name
  49730. */
  49731. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  49732. return "keyboard";
  49733. };
  49734. /**
  49735. * Update the current camera state depending on the inputs that have been used this frame.
  49736. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49737. */
  49738. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  49739. if (this._onKeyboardObserver) {
  49740. var camera = this.camera;
  49741. // Keyboard
  49742. for (var index = 0; index < this._keys.length; index++) {
  49743. var keyCode = this._keys[index];
  49744. var speed = camera._computeLocalCameraSpeed();
  49745. if (this.keysForward.indexOf(keyCode) !== -1) {
  49746. camera._localDirection.copyFromFloats(0, 0, speed);
  49747. }
  49748. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  49749. camera._localDirection.copyFromFloats(0, 0, -speed);
  49750. }
  49751. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49752. camera._localDirection.copyFromFloats(0, speed, 0);
  49753. }
  49754. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49755. camera._localDirection.copyFromFloats(0, -speed, 0);
  49756. }
  49757. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49758. camera._localDirection.copyFromFloats(speed, 0, 0);
  49759. }
  49760. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  49761. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49762. }
  49763. if (camera.getScene().useRightHandedSystem) {
  49764. camera._localDirection.z *= -1;
  49765. }
  49766. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49767. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49768. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49769. }
  49770. }
  49771. };
  49772. __decorate([
  49773. BABYLON.serialize()
  49774. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  49775. __decorate([
  49776. BABYLON.serialize()
  49777. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  49778. __decorate([
  49779. BABYLON.serialize()
  49780. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  49781. __decorate([
  49782. BABYLON.serialize()
  49783. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  49784. __decorate([
  49785. BABYLON.serialize()
  49786. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  49787. __decorate([
  49788. BABYLON.serialize()
  49789. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  49790. return FlyCameraKeyboardInput;
  49791. }());
  49792. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  49793. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  49794. })(BABYLON || (BABYLON = {}));
  49795. //# sourceMappingURL=babylon.flyCameraKeyboardInput.js.map
  49796. var BABYLON;
  49797. (function (BABYLON) {
  49798. /**
  49799. * Default Inputs manager for the FlyCamera.
  49800. * It groups all the default supported inputs for ease of use.
  49801. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49802. */
  49803. var FlyCameraInputsManager = /** @class */ (function (_super) {
  49804. __extends(FlyCameraInputsManager, _super);
  49805. /**
  49806. * Instantiates a new FlyCameraInputsManager.
  49807. * @param camera Defines the camera the inputs belong to.
  49808. */
  49809. function FlyCameraInputsManager(camera) {
  49810. return _super.call(this, camera) || this;
  49811. }
  49812. /**
  49813. * Add keyboard input support to the input manager.
  49814. * @returns the new FlyCameraKeyboardMoveInput().
  49815. */
  49816. FlyCameraInputsManager.prototype.addKeyboard = function () {
  49817. this.add(new BABYLON.FlyCameraKeyboardInput());
  49818. return this;
  49819. };
  49820. /**
  49821. * Add mouse input support to the input manager.
  49822. * @param touchEnabled Enable touch screen support.
  49823. * @returns the new FlyCameraMouseInput().
  49824. */
  49825. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49826. if (touchEnabled === void 0) { touchEnabled = true; }
  49827. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  49828. return this;
  49829. };
  49830. return FlyCameraInputsManager;
  49831. }(BABYLON.CameraInputsManager));
  49832. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  49833. })(BABYLON || (BABYLON = {}));
  49834. //# sourceMappingURL=babylon.flyCameraInputsManager.js.map
  49835. var BABYLON;
  49836. (function (BABYLON) {
  49837. /**
  49838. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49839. * such as in a 3D Space Shooter or a Flight Simulator.
  49840. */
  49841. var FlyCamera = /** @class */ (function (_super) {
  49842. __extends(FlyCamera, _super);
  49843. /**
  49844. * Instantiates a FlyCamera.
  49845. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49846. * such as in a 3D Space Shooter or a Flight Simulator.
  49847. * @param name Define the name of the camera in the scene.
  49848. * @param position Define the starting position of the camera in the scene.
  49849. * @param scene Define the scene the camera belongs to.
  49850. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  49851. */
  49852. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49853. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49854. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49855. /**
  49856. * Define the collision ellipsoid of the camera.
  49857. * This is helpful for simulating a camera body, like a player's body.
  49858. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49859. */
  49860. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  49861. /**
  49862. * Define an offset for the position of the ellipsoid around the camera.
  49863. * This can be helpful if the camera is attached away from the player's body center,
  49864. * such as at its head.
  49865. */
  49866. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49867. /**
  49868. * Enable or disable collisions of the camera with the rest of the scene objects.
  49869. */
  49870. _this.checkCollisions = false;
  49871. /**
  49872. * Enable or disable gravity on the camera.
  49873. */
  49874. _this.applyGravity = false;
  49875. /**
  49876. * Define the current direction the camera is moving to.
  49877. */
  49878. _this.cameraDirection = BABYLON.Vector3.Zero();
  49879. /**
  49880. * Track Roll to maintain the wanted Rolling when looking around.
  49881. */
  49882. _this._trackRoll = 0;
  49883. /**
  49884. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  49885. */
  49886. _this.rollCorrect = 100;
  49887. /**
  49888. * Mimic a banked turn, Rolling the camera when Yawing.
  49889. * It's recommended to use rollCorrect = 10 for faster banking correction.
  49890. */
  49891. _this.bankedTurn = false;
  49892. /**
  49893. * Limit in radians for how much Roll banking will add. (Default: 90°)
  49894. */
  49895. _this.bankedTurnLimit = Math.PI / 2;
  49896. /**
  49897. * Value of 0 disables the banked Roll.
  49898. * Value of 1 is equal to the Yaw angle in radians.
  49899. */
  49900. _this.bankedTurnMultiplier = 1;
  49901. _this._needMoveForGravity = false;
  49902. _this._oldPosition = BABYLON.Vector3.Zero();
  49903. _this._diffPosition = BABYLON.Vector3.Zero();
  49904. _this._newPosition = BABYLON.Vector3.Zero();
  49905. // Collisions.
  49906. _this._collisionMask = -1;
  49907. /** @hidden */
  49908. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49909. if (collidedMesh === void 0) { collidedMesh = null; }
  49910. // TODO Move this to the collision coordinator!
  49911. if (_this.getScene().workerCollisions) {
  49912. newPosition.multiplyInPlace(_this._collider._radius);
  49913. }
  49914. var updatePosition = function (newPos) {
  49915. _this._newPosition.copyFrom(newPos);
  49916. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49917. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49918. _this.position.addInPlace(_this._diffPosition);
  49919. if (_this.onCollide && collidedMesh) {
  49920. _this.onCollide(collidedMesh);
  49921. }
  49922. }
  49923. };
  49924. updatePosition(newPosition);
  49925. };
  49926. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  49927. _this.inputs.addKeyboard().addMouse();
  49928. return _this;
  49929. }
  49930. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  49931. /**
  49932. * Gets the input sensibility for mouse input.
  49933. * Higher values reduce sensitivity.
  49934. */
  49935. get: function () {
  49936. var mouse = this.inputs.attached["mouse"];
  49937. if (mouse) {
  49938. return mouse.angularSensibility;
  49939. }
  49940. return 0;
  49941. },
  49942. /**
  49943. * Sets the input sensibility for a mouse input.
  49944. * Higher values reduce sensitivity.
  49945. */
  49946. set: function (value) {
  49947. var mouse = this.inputs.attached["mouse"];
  49948. if (mouse) {
  49949. mouse.angularSensibility = value;
  49950. }
  49951. },
  49952. enumerable: true,
  49953. configurable: true
  49954. });
  49955. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  49956. /**
  49957. * Get the keys for camera movement forward.
  49958. */
  49959. get: function () {
  49960. var keyboard = this.inputs.attached["keyboard"];
  49961. if (keyboard) {
  49962. return keyboard.keysForward;
  49963. }
  49964. return [];
  49965. },
  49966. /**
  49967. * Set the keys for camera movement forward.
  49968. */
  49969. set: function (value) {
  49970. var keyboard = this.inputs.attached["keyboard"];
  49971. if (keyboard) {
  49972. keyboard.keysForward = value;
  49973. }
  49974. },
  49975. enumerable: true,
  49976. configurable: true
  49977. });
  49978. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  49979. /**
  49980. * Get the keys for camera movement backward.
  49981. */
  49982. get: function () {
  49983. var keyboard = this.inputs.attached["keyboard"];
  49984. if (keyboard) {
  49985. return keyboard.keysBackward;
  49986. }
  49987. return [];
  49988. },
  49989. set: function (value) {
  49990. var keyboard = this.inputs.attached["keyboard"];
  49991. if (keyboard) {
  49992. keyboard.keysBackward = value;
  49993. }
  49994. },
  49995. enumerable: true,
  49996. configurable: true
  49997. });
  49998. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  49999. /**
  50000. * Get the keys for camera movement up.
  50001. */
  50002. get: function () {
  50003. var keyboard = this.inputs.attached["keyboard"];
  50004. if (keyboard) {
  50005. return keyboard.keysUp;
  50006. }
  50007. return [];
  50008. },
  50009. /**
  50010. * Set the keys for camera movement up.
  50011. */
  50012. set: function (value) {
  50013. var keyboard = this.inputs.attached["keyboard"];
  50014. if (keyboard) {
  50015. keyboard.keysUp = value;
  50016. }
  50017. },
  50018. enumerable: true,
  50019. configurable: true
  50020. });
  50021. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  50022. /**
  50023. * Get the keys for camera movement down.
  50024. */
  50025. get: function () {
  50026. var keyboard = this.inputs.attached["keyboard"];
  50027. if (keyboard) {
  50028. return keyboard.keysDown;
  50029. }
  50030. return [];
  50031. },
  50032. /**
  50033. * Set the keys for camera movement down.
  50034. */
  50035. set: function (value) {
  50036. var keyboard = this.inputs.attached["keyboard"];
  50037. if (keyboard) {
  50038. keyboard.keysDown = value;
  50039. }
  50040. },
  50041. enumerable: true,
  50042. configurable: true
  50043. });
  50044. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  50045. /**
  50046. * Get the keys for camera movement left.
  50047. */
  50048. get: function () {
  50049. var keyboard = this.inputs.attached["keyboard"];
  50050. if (keyboard) {
  50051. return keyboard.keysLeft;
  50052. }
  50053. return [];
  50054. },
  50055. /**
  50056. * Set the keys for camera movement left.
  50057. */
  50058. set: function (value) {
  50059. var keyboard = this.inputs.attached["keyboard"];
  50060. if (keyboard) {
  50061. keyboard.keysLeft = value;
  50062. }
  50063. },
  50064. enumerable: true,
  50065. configurable: true
  50066. });
  50067. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50068. /**
  50069. * Set the keys for camera movement right.
  50070. */
  50071. get: function () {
  50072. var keyboard = this.inputs.attached["keyboard"];
  50073. if (keyboard) {
  50074. return keyboard.keysRight;
  50075. }
  50076. return [];
  50077. },
  50078. /**
  50079. * Set the keys for camera movement right.
  50080. */
  50081. set: function (value) {
  50082. var keyboard = this.inputs.attached["keyboard"];
  50083. if (keyboard) {
  50084. keyboard.keysRight = value;
  50085. }
  50086. },
  50087. enumerable: true,
  50088. configurable: true
  50089. });
  50090. /**
  50091. * Attach a control to the HTML DOM element.
  50092. * @param element Defines the element that listens to the input events.
  50093. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50094. */
  50095. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50096. this.inputs.attachElement(element, noPreventDefault);
  50097. };
  50098. /**
  50099. * Detach a control from the HTML DOM element.
  50100. * The camera will stop reacting to that input.
  50101. * @param element Defines the element that listens to the input events.
  50102. */
  50103. FlyCamera.prototype.detachControl = function (element) {
  50104. this.inputs.detachElement(element);
  50105. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50106. };
  50107. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50108. /**
  50109. * Get the mask that the camera ignores in collision events.
  50110. */
  50111. get: function () {
  50112. return this._collisionMask;
  50113. },
  50114. /**
  50115. * Set the mask that the camera ignores in collision events.
  50116. */
  50117. set: function (mask) {
  50118. this._collisionMask = !isNaN(mask) ? mask : -1;
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. /** @hidden */
  50124. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50125. var globalPosition;
  50126. if (this.parent) {
  50127. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50128. }
  50129. else {
  50130. globalPosition = this.position;
  50131. }
  50132. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50133. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50134. if (!this._collider) {
  50135. this._collider = new BABYLON.Collider();
  50136. }
  50137. this._collider._radius = this.ellipsoid;
  50138. this._collider.collisionMask = this._collisionMask;
  50139. // No need for clone, as long as gravity is not on.
  50140. var actualDisplacement = displacement;
  50141. // Add gravity to direction to prevent dual-collision checking.
  50142. if (this.applyGravity) {
  50143. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50144. actualDisplacement = displacement.add(this.getScene().gravity);
  50145. }
  50146. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50147. };
  50148. /** @hidden */
  50149. FlyCamera.prototype._checkInputs = function () {
  50150. if (!this._localDirection) {
  50151. this._localDirection = BABYLON.Vector3.Zero();
  50152. this._transformedDirection = BABYLON.Vector3.Zero();
  50153. }
  50154. this.inputs.checkInputs();
  50155. _super.prototype._checkInputs.call(this);
  50156. };
  50157. /** @hidden */
  50158. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50159. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50160. };
  50161. /** @hidden */
  50162. FlyCamera.prototype._updatePosition = function () {
  50163. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50164. this._collideWithWorld(this.cameraDirection);
  50165. }
  50166. else {
  50167. _super.prototype._updatePosition.call(this);
  50168. }
  50169. };
  50170. /**
  50171. * Restore the Roll to its target value at the rate specified.
  50172. * @param rate - Higher means slower restoring.
  50173. * @hidden
  50174. */
  50175. FlyCamera.prototype.restoreRoll = function (rate) {
  50176. var limit = this._trackRoll; // Target Roll.
  50177. var z = this.rotation.z; // Current Roll.
  50178. var delta = limit - z; // Difference in Roll.
  50179. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50180. // If the difference is noticable, restore the Roll.
  50181. if (Math.abs(delta) >= minRad) {
  50182. // Change Z rotation towards the target Roll.
  50183. this.rotation.z += delta / rate;
  50184. // Match when near enough.
  50185. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50186. this.rotation.z = limit;
  50187. }
  50188. }
  50189. };
  50190. /**
  50191. * Destroy the camera and release the current resources held by it.
  50192. */
  50193. FlyCamera.prototype.dispose = function () {
  50194. this.inputs.clear();
  50195. _super.prototype.dispose.call(this);
  50196. };
  50197. /**
  50198. * Get the current object class name.
  50199. * @returns the class name.
  50200. */
  50201. FlyCamera.prototype.getClassName = function () {
  50202. return "FlyCamera";
  50203. };
  50204. __decorate([
  50205. BABYLON.serializeAsVector3()
  50206. ], FlyCamera.prototype, "ellipsoid", void 0);
  50207. __decorate([
  50208. BABYLON.serializeAsVector3()
  50209. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50210. __decorate([
  50211. BABYLON.serialize()
  50212. ], FlyCamera.prototype, "checkCollisions", void 0);
  50213. __decorate([
  50214. BABYLON.serialize()
  50215. ], FlyCamera.prototype, "applyGravity", void 0);
  50216. return FlyCamera;
  50217. }(BABYLON.TargetCamera));
  50218. BABYLON.FlyCamera = FlyCamera;
  50219. })(BABYLON || (BABYLON = {}));
  50220. //# sourceMappingURL=babylon.flyCamera.js.map
  50221. var BABYLON;
  50222. (function (BABYLON) {
  50223. /**
  50224. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50225. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50226. */
  50227. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50228. function ArcRotateCameraKeyboardMoveInput() {
  50229. /**
  50230. * Defines the list of key codes associated with the up action (increase alpha)
  50231. */
  50232. this.keysUp = [38];
  50233. /**
  50234. * Defines the list of key codes associated with the down action (decrease alpha)
  50235. */
  50236. this.keysDown = [40];
  50237. /**
  50238. * Defines the list of key codes associated with the left action (increase beta)
  50239. */
  50240. this.keysLeft = [37];
  50241. /**
  50242. * Defines the list of key codes associated with the right action (decrease beta)
  50243. */
  50244. this.keysRight = [39];
  50245. /**
  50246. * Defines the list of key codes associated with the reset action.
  50247. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50248. */
  50249. this.keysReset = [220];
  50250. /**
  50251. * Defines the panning sensibility of the inputs.
  50252. * (How fast is the camera paning)
  50253. */
  50254. this.panningSensibility = 50.0;
  50255. /**
  50256. * Defines the zooming sensibility of the inputs.
  50257. * (How fast is the camera zooming)
  50258. */
  50259. this.zoomingSensibility = 25.0;
  50260. /**
  50261. * Defines wether maintaining the alt key down switch the movement mode from
  50262. * orientation to zoom.
  50263. */
  50264. this.useAltToZoom = true;
  50265. /**
  50266. * Rotation speed of the camera
  50267. */
  50268. this.angularSpeed = 0.01;
  50269. this._keys = new Array();
  50270. }
  50271. /**
  50272. * Attach the input controls to a specific dom element to get the input from.
  50273. * @param element Defines the element the controls should be listened from
  50274. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50275. */
  50276. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  50277. var _this = this;
  50278. if (this._onCanvasBlurObserver) {
  50279. return;
  50280. }
  50281. this._scene = this.camera.getScene();
  50282. this._engine = this._scene.getEngine();
  50283. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50284. _this._keys = [];
  50285. });
  50286. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50287. var evt = info.event;
  50288. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50289. _this._ctrlPressed = evt.ctrlKey;
  50290. _this._altPressed = evt.altKey;
  50291. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50292. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50293. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50294. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50295. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50296. var index = _this._keys.indexOf(evt.keyCode);
  50297. if (index === -1) {
  50298. _this._keys.push(evt.keyCode);
  50299. }
  50300. if (evt.preventDefault) {
  50301. if (!noPreventDefault) {
  50302. evt.preventDefault();
  50303. }
  50304. }
  50305. }
  50306. }
  50307. else {
  50308. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50309. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50310. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50311. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50312. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50313. var index = _this._keys.indexOf(evt.keyCode);
  50314. if (index >= 0) {
  50315. _this._keys.splice(index, 1);
  50316. }
  50317. if (evt.preventDefault) {
  50318. if (!noPreventDefault) {
  50319. evt.preventDefault();
  50320. }
  50321. }
  50322. }
  50323. }
  50324. });
  50325. };
  50326. /**
  50327. * Detach the current controls from the specified dom element.
  50328. * @param element Defines the element to stop listening the inputs from
  50329. */
  50330. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  50331. if (this._scene) {
  50332. if (this._onKeyboardObserver) {
  50333. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50334. }
  50335. if (this._onCanvasBlurObserver) {
  50336. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50337. }
  50338. this._onKeyboardObserver = null;
  50339. this._onCanvasBlurObserver = null;
  50340. }
  50341. this._keys = [];
  50342. };
  50343. /**
  50344. * Update the current camera state depending on the inputs that have been used this frame.
  50345. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50346. */
  50347. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  50348. if (this._onKeyboardObserver) {
  50349. var camera = this.camera;
  50350. for (var index = 0; index < this._keys.length; index++) {
  50351. var keyCode = this._keys[index];
  50352. if (this.keysLeft.indexOf(keyCode) !== -1) {
  50353. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50354. camera.inertialPanningX -= 1 / this.panningSensibility;
  50355. }
  50356. else {
  50357. camera.inertialAlphaOffset -= this.angularSpeed;
  50358. }
  50359. }
  50360. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50361. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50362. camera.inertialPanningY += 1 / this.panningSensibility;
  50363. }
  50364. else if (this._altPressed && this.useAltToZoom) {
  50365. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  50366. }
  50367. else {
  50368. camera.inertialBetaOffset -= this.angularSpeed;
  50369. }
  50370. }
  50371. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50372. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50373. camera.inertialPanningX += 1 / this.panningSensibility;
  50374. }
  50375. else {
  50376. camera.inertialAlphaOffset += this.angularSpeed;
  50377. }
  50378. }
  50379. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50380. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50381. camera.inertialPanningY -= 1 / this.panningSensibility;
  50382. }
  50383. else if (this._altPressed && this.useAltToZoom) {
  50384. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  50385. }
  50386. else {
  50387. camera.inertialBetaOffset += this.angularSpeed;
  50388. }
  50389. }
  50390. else if (this.keysReset.indexOf(keyCode) !== -1) {
  50391. if (camera.useInputToRestoreState) {
  50392. camera.restoreState();
  50393. }
  50394. }
  50395. }
  50396. }
  50397. };
  50398. /**
  50399. * Gets the class name of the current intput.
  50400. * @returns the class name
  50401. */
  50402. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  50403. return "ArcRotateCameraKeyboardMoveInput";
  50404. };
  50405. /**
  50406. * Get the friendly name associated with the input class.
  50407. * @returns the input friendly name
  50408. */
  50409. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  50410. return "keyboard";
  50411. };
  50412. __decorate([
  50413. BABYLON.serialize()
  50414. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  50415. __decorate([
  50416. BABYLON.serialize()
  50417. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  50418. __decorate([
  50419. BABYLON.serialize()
  50420. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  50421. __decorate([
  50422. BABYLON.serialize()
  50423. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  50424. __decorate([
  50425. BABYLON.serialize()
  50426. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  50427. __decorate([
  50428. BABYLON.serialize()
  50429. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  50430. __decorate([
  50431. BABYLON.serialize()
  50432. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  50433. __decorate([
  50434. BABYLON.serialize()
  50435. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  50436. __decorate([
  50437. BABYLON.serialize()
  50438. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  50439. return ArcRotateCameraKeyboardMoveInput;
  50440. }());
  50441. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  50442. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  50443. })(BABYLON || (BABYLON = {}));
  50444. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  50445. var BABYLON;
  50446. (function (BABYLON) {
  50447. /**
  50448. * Manage the mouse wheel inputs to control an arc rotate camera.
  50449. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50450. */
  50451. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  50452. function ArcRotateCameraMouseWheelInput() {
  50453. /**
  50454. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50455. */
  50456. this.wheelPrecision = 3.0;
  50457. /**
  50458. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  50459. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  50460. */
  50461. this.wheelDeltaPercentage = 0;
  50462. }
  50463. /**
  50464. * Attach the input controls to a specific dom element to get the input from.
  50465. * @param element Defines the element the controls should be listened from
  50466. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50467. */
  50468. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  50469. var _this = this;
  50470. this._wheel = function (p, s) {
  50471. //sanity check - this should be a PointerWheel event.
  50472. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  50473. return;
  50474. }
  50475. var event = p.event;
  50476. var delta = 0;
  50477. if (event.wheelDelta) {
  50478. if (_this.wheelDeltaPercentage) {
  50479. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  50480. if (event.wheelDelta > 0) {
  50481. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  50482. }
  50483. else {
  50484. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  50485. }
  50486. }
  50487. else {
  50488. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  50489. }
  50490. }
  50491. else {
  50492. var deltaValue = event.deltaY || event.detail;
  50493. delta = -deltaValue / _this.wheelPrecision;
  50494. }
  50495. if (delta) {
  50496. _this.camera.inertialRadiusOffset += delta;
  50497. }
  50498. if (event.preventDefault) {
  50499. if (!noPreventDefault) {
  50500. event.preventDefault();
  50501. }
  50502. }
  50503. };
  50504. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  50505. };
  50506. /**
  50507. * Detach the current controls from the specified dom element.
  50508. * @param element Defines the element to stop listening the inputs from
  50509. */
  50510. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  50511. if (this._observer && element) {
  50512. this.camera.getScene().onPointerObservable.remove(this._observer);
  50513. this._observer = null;
  50514. this._wheel = null;
  50515. }
  50516. };
  50517. /**
  50518. * Gets the class name of the current intput.
  50519. * @returns the class name
  50520. */
  50521. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  50522. return "ArcRotateCameraMouseWheelInput";
  50523. };
  50524. /**
  50525. * Get the friendly name associated with the input class.
  50526. * @returns the input friendly name
  50527. */
  50528. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  50529. return "mousewheel";
  50530. };
  50531. __decorate([
  50532. BABYLON.serialize()
  50533. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  50534. __decorate([
  50535. BABYLON.serialize()
  50536. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  50537. return ArcRotateCameraMouseWheelInput;
  50538. }());
  50539. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  50540. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  50541. })(BABYLON || (BABYLON = {}));
  50542. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  50543. var BABYLON;
  50544. (function (BABYLON) {
  50545. /**
  50546. * Manage the pointers inputs to control an arc rotate camera.
  50547. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50548. */
  50549. var ArcRotateCameraPointersInput = /** @class */ (function () {
  50550. function ArcRotateCameraPointersInput() {
  50551. /**
  50552. * Defines the buttons associated with the input to handle camera move.
  50553. */
  50554. this.buttons = [0, 1, 2];
  50555. /**
  50556. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50557. */
  50558. this.angularSensibilityX = 1000.0;
  50559. /**
  50560. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50561. */
  50562. this.angularSensibilityY = 1000.0;
  50563. /**
  50564. * Defines the pointer pinch precision or how fast is the camera zooming.
  50565. */
  50566. this.pinchPrecision = 12.0;
  50567. /**
  50568. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  50569. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50570. */
  50571. this.pinchDeltaPercentage = 0;
  50572. /**
  50573. * Defines the pointer panning sensibility or how fast is the camera moving.
  50574. */
  50575. this.panningSensibility = 1000.0;
  50576. /**
  50577. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  50578. */
  50579. this.multiTouchPanning = true;
  50580. /**
  50581. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  50582. */
  50583. this.multiTouchPanAndZoom = true;
  50584. /**
  50585. * Revers pinch action direction.
  50586. */
  50587. this.pinchInwards = true;
  50588. this._isPanClick = false;
  50589. }
  50590. /**
  50591. * Attach the input controls to a specific dom element to get the input from.
  50592. * @param element Defines the element the controls should be listened from
  50593. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50594. */
  50595. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  50596. var _this = this;
  50597. var engine = this.camera.getEngine();
  50598. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  50599. var pointA = null;
  50600. var pointB = null;
  50601. var previousPinchSquaredDistance = 0;
  50602. var initialDistance = 0;
  50603. var twoFingerActivityCount = 0;
  50604. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  50605. this._pointerInput = function (p, s) {
  50606. var evt = p.event;
  50607. var isTouch = p.event.pointerType === "touch";
  50608. if (engine.isInVRExclusivePointerMode) {
  50609. return;
  50610. }
  50611. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  50612. return;
  50613. }
  50614. var srcElement = (evt.srcElement || evt.target);
  50615. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  50616. try {
  50617. srcElement.setPointerCapture(evt.pointerId);
  50618. }
  50619. catch (e) {
  50620. //Nothing to do with the error. Execution will continue.
  50621. }
  50622. // Manage panning with pan button click
  50623. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  50624. // manage pointers
  50625. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  50626. if (pointA === null) {
  50627. pointA = cacheSoloPointer;
  50628. }
  50629. else if (pointB === null) {
  50630. pointB = cacheSoloPointer;
  50631. }
  50632. if (!noPreventDefault) {
  50633. evt.preventDefault();
  50634. element.focus();
  50635. }
  50636. }
  50637. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  50638. if (_this.camera.useInputToRestoreState) {
  50639. _this.camera.restoreState();
  50640. }
  50641. }
  50642. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  50643. try {
  50644. srcElement.releasePointerCapture(evt.pointerId);
  50645. }
  50646. catch (e) {
  50647. //Nothing to do with the error.
  50648. }
  50649. cacheSoloPointer = null;
  50650. previousPinchSquaredDistance = 0;
  50651. previousMultiTouchPanPosition.isPaning = false;
  50652. previousMultiTouchPanPosition.isPinching = false;
  50653. twoFingerActivityCount = 0;
  50654. initialDistance = 0;
  50655. if (!isTouch) {
  50656. pointB = null; // Mouse and pen are mono pointer
  50657. }
  50658. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  50659. //but emptying completly pointers collection is required to fix a bug on iPhone :
  50660. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  50661. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  50662. if (engine._badOS) {
  50663. pointA = pointB = null;
  50664. }
  50665. else {
  50666. //only remove the impacted pointer in case of multitouch allowing on most
  50667. //platforms switching from rotate to zoom and pan seamlessly.
  50668. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  50669. pointA = pointB;
  50670. pointB = null;
  50671. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50672. }
  50673. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  50674. pointB = null;
  50675. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50676. }
  50677. else {
  50678. pointA = pointB = null;
  50679. }
  50680. }
  50681. if (!noPreventDefault) {
  50682. evt.preventDefault();
  50683. }
  50684. }
  50685. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50686. if (!noPreventDefault) {
  50687. evt.preventDefault();
  50688. }
  50689. // One button down
  50690. if (pointA && pointB === null && cacheSoloPointer) {
  50691. if (_this.panningSensibility !== 0 &&
  50692. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  50693. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  50694. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  50695. }
  50696. else {
  50697. var offsetX = evt.clientX - cacheSoloPointer.x;
  50698. var offsetY = evt.clientY - cacheSoloPointer.y;
  50699. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50700. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50701. }
  50702. cacheSoloPointer.x = evt.clientX;
  50703. cacheSoloPointer.y = evt.clientY;
  50704. }
  50705. // Two buttons down: pinch/pan
  50706. else if (pointA && pointB) {
  50707. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  50708. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  50709. ed.x = evt.clientX;
  50710. ed.y = evt.clientY;
  50711. var direction = _this.pinchInwards ? 1 : -1;
  50712. var distX = pointA.x - pointB.x;
  50713. var distY = pointA.y - pointB.y;
  50714. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  50715. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  50716. if (previousPinchSquaredDistance === 0) {
  50717. initialDistance = pinchDistance;
  50718. previousPinchSquaredDistance = pinchSquaredDistance;
  50719. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  50720. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  50721. return;
  50722. }
  50723. if (_this.multiTouchPanAndZoom) {
  50724. if (_this.pinchDeltaPercentage) {
  50725. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50726. }
  50727. else {
  50728. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50729. (_this.pinchPrecision *
  50730. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50731. direction);
  50732. }
  50733. if (_this.panningSensibility !== 0) {
  50734. var pointersCenterX = (pointA.x + pointB.x) / 2;
  50735. var pointersCenterY = (pointA.y + pointB.y) / 2;
  50736. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  50737. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  50738. previousMultiTouchPanPosition.x = pointersCenterX;
  50739. previousMultiTouchPanPosition.y = pointersCenterY;
  50740. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  50741. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  50742. }
  50743. }
  50744. else {
  50745. twoFingerActivityCount++;
  50746. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  50747. if (_this.pinchDeltaPercentage) {
  50748. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50749. }
  50750. else {
  50751. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50752. (_this.pinchPrecision *
  50753. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50754. direction);
  50755. }
  50756. previousMultiTouchPanPosition.isPaning = false;
  50757. previousMultiTouchPanPosition.isPinching = true;
  50758. }
  50759. else {
  50760. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  50761. if (!previousMultiTouchPanPosition.isPaning) {
  50762. previousMultiTouchPanPosition.isPaning = true;
  50763. previousMultiTouchPanPosition.isPinching = false;
  50764. previousMultiTouchPanPosition.x = ed.x;
  50765. previousMultiTouchPanPosition.y = ed.y;
  50766. return;
  50767. }
  50768. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  50769. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  50770. }
  50771. }
  50772. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  50773. previousMultiTouchPanPosition.x = ed.x;
  50774. previousMultiTouchPanPosition.y = ed.y;
  50775. }
  50776. }
  50777. previousPinchSquaredDistance = pinchSquaredDistance;
  50778. }
  50779. }
  50780. };
  50781. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  50782. this._onContextMenu = function (evt) {
  50783. evt.preventDefault();
  50784. };
  50785. if (!this.camera._useCtrlForPanning) {
  50786. element.addEventListener("contextmenu", this._onContextMenu, false);
  50787. }
  50788. this._onLostFocus = function () {
  50789. //this._keys = [];
  50790. pointA = pointB = null;
  50791. previousPinchSquaredDistance = 0;
  50792. previousMultiTouchPanPosition.isPaning = false;
  50793. previousMultiTouchPanPosition.isPinching = false;
  50794. twoFingerActivityCount = 0;
  50795. cacheSoloPointer = null;
  50796. initialDistance = 0;
  50797. };
  50798. this._onMouseMove = function (evt) {
  50799. if (!engine.isPointerLock) {
  50800. return;
  50801. }
  50802. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  50803. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  50804. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50805. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50806. if (!noPreventDefault) {
  50807. evt.preventDefault();
  50808. }
  50809. };
  50810. this._onGestureStart = function (e) {
  50811. if (window.MSGesture === undefined) {
  50812. return;
  50813. }
  50814. if (!_this._MSGestureHandler) {
  50815. _this._MSGestureHandler = new MSGesture();
  50816. _this._MSGestureHandler.target = element;
  50817. }
  50818. _this._MSGestureHandler.addPointer(e.pointerId);
  50819. };
  50820. this._onGesture = function (e) {
  50821. _this.camera.radius *= e.scale;
  50822. if (e.preventDefault) {
  50823. if (!noPreventDefault) {
  50824. e.stopPropagation();
  50825. e.preventDefault();
  50826. }
  50827. }
  50828. };
  50829. element.addEventListener("mousemove", this._onMouseMove, false);
  50830. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  50831. element.addEventListener("MSGestureChange", this._onGesture, false);
  50832. BABYLON.Tools.RegisterTopRootEvents([
  50833. { name: "blur", handler: this._onLostFocus }
  50834. ]);
  50835. };
  50836. /**
  50837. * Detach the current controls from the specified dom element.
  50838. * @param element Defines the element to stop listening the inputs from
  50839. */
  50840. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  50841. if (this._onLostFocus) {
  50842. BABYLON.Tools.UnregisterTopRootEvents([
  50843. { name: "blur", handler: this._onLostFocus }
  50844. ]);
  50845. }
  50846. if (element && this._observer) {
  50847. this.camera.getScene().onPointerObservable.remove(this._observer);
  50848. this._observer = null;
  50849. if (this._onContextMenu) {
  50850. element.removeEventListener("contextmenu", this._onContextMenu);
  50851. }
  50852. if (this._onMouseMove) {
  50853. element.removeEventListener("mousemove", this._onMouseMove);
  50854. }
  50855. if (this._onGestureStart) {
  50856. element.removeEventListener("MSPointerDown", this._onGestureStart);
  50857. }
  50858. if (this._onGesture) {
  50859. element.removeEventListener("MSGestureChange", this._onGesture);
  50860. }
  50861. this._isPanClick = false;
  50862. this.pinchInwards = true;
  50863. this._onMouseMove = null;
  50864. this._onGestureStart = null;
  50865. this._onGesture = null;
  50866. this._MSGestureHandler = null;
  50867. this._onLostFocus = null;
  50868. this._onContextMenu = null;
  50869. }
  50870. };
  50871. /**
  50872. * Gets the class name of the current intput.
  50873. * @returns the class name
  50874. */
  50875. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  50876. return "ArcRotateCameraPointersInput";
  50877. };
  50878. /**
  50879. * Get the friendly name associated with the input class.
  50880. * @returns the input friendly name
  50881. */
  50882. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  50883. return "pointers";
  50884. };
  50885. __decorate([
  50886. BABYLON.serialize()
  50887. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  50888. __decorate([
  50889. BABYLON.serialize()
  50890. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  50891. __decorate([
  50892. BABYLON.serialize()
  50893. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  50894. __decorate([
  50895. BABYLON.serialize()
  50896. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  50897. __decorate([
  50898. BABYLON.serialize()
  50899. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  50900. __decorate([
  50901. BABYLON.serialize()
  50902. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  50903. __decorate([
  50904. BABYLON.serialize()
  50905. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  50906. __decorate([
  50907. BABYLON.serialize()
  50908. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  50909. return ArcRotateCameraPointersInput;
  50910. }());
  50911. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  50912. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  50913. })(BABYLON || (BABYLON = {}));
  50914. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  50915. var BABYLON;
  50916. (function (BABYLON) {
  50917. /**
  50918. * Default Inputs manager for the ArcRotateCamera.
  50919. * It groups all the default supported inputs for ease of use.
  50920. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50921. */
  50922. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  50923. __extends(ArcRotateCameraInputsManager, _super);
  50924. /**
  50925. * Instantiates a new ArcRotateCameraInputsManager.
  50926. * @param camera Defines the camera the inputs belong to
  50927. */
  50928. function ArcRotateCameraInputsManager(camera) {
  50929. return _super.call(this, camera) || this;
  50930. }
  50931. /**
  50932. * Add mouse wheel input support to the input manager.
  50933. * @returns the current input manager
  50934. */
  50935. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  50936. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  50937. return this;
  50938. };
  50939. /**
  50940. * Add pointers input support to the input manager.
  50941. * @returns the current input manager
  50942. */
  50943. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  50944. this.add(new BABYLON.ArcRotateCameraPointersInput());
  50945. return this;
  50946. };
  50947. /**
  50948. * Add keyboard input support to the input manager.
  50949. * @returns the current input manager
  50950. */
  50951. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  50952. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  50953. return this;
  50954. };
  50955. /**
  50956. * Add orientation input support to the input manager.
  50957. * @returns the current input manager
  50958. */
  50959. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  50960. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  50961. return this;
  50962. };
  50963. return ArcRotateCameraInputsManager;
  50964. }(BABYLON.CameraInputsManager));
  50965. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  50966. })(BABYLON || (BABYLON = {}));
  50967. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  50968. var BABYLON;
  50969. (function (BABYLON) {
  50970. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  50971. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  50972. });
  50973. /**
  50974. * This represents an orbital type of camera.
  50975. *
  50976. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  50977. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  50978. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  50979. */
  50980. var ArcRotateCamera = /** @class */ (function (_super) {
  50981. __extends(ArcRotateCamera, _super);
  50982. /**
  50983. * Instantiates a new ArcRotateCamera in a given scene
  50984. * @param name Defines the name of the camera
  50985. * @param alpha Defines the camera rotation along the logitudinal axis
  50986. * @param beta Defines the camera rotation along the latitudinal axis
  50987. * @param radius Defines the camera distance from its target
  50988. * @param target Defines the camera target
  50989. * @param scene Defines the scene the camera belongs to
  50990. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  50991. */
  50992. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  50993. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  50994. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  50995. /**
  50996. * Current inertia value on the longitudinal axis.
  50997. * The bigger this number the longer it will take for the camera to stop.
  50998. */
  50999. _this.inertialAlphaOffset = 0;
  51000. /**
  51001. * Current inertia value on the latitudinal axis.
  51002. * The bigger this number the longer it will take for the camera to stop.
  51003. */
  51004. _this.inertialBetaOffset = 0;
  51005. /**
  51006. * Current inertia value on the radius axis.
  51007. * The bigger this number the longer it will take for the camera to stop.
  51008. */
  51009. _this.inertialRadiusOffset = 0;
  51010. /**
  51011. * Minimum allowed angle on the longitudinal axis.
  51012. * This can help limiting how the Camera is able to move in the scene.
  51013. */
  51014. _this.lowerAlphaLimit = null;
  51015. /**
  51016. * Maximum allowed angle on the longitudinal axis.
  51017. * This can help limiting how the Camera is able to move in the scene.
  51018. */
  51019. _this.upperAlphaLimit = null;
  51020. /**
  51021. * Minimum allowed angle on the latitudinal axis.
  51022. * This can help limiting how the Camera is able to move in the scene.
  51023. */
  51024. _this.lowerBetaLimit = 0.01;
  51025. /**
  51026. * Maximum allowed angle on the latitudinal axis.
  51027. * This can help limiting how the Camera is able to move in the scene.
  51028. */
  51029. _this.upperBetaLimit = Math.PI;
  51030. /**
  51031. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  51032. * This can help limiting how the Camera is able to move in the scene.
  51033. */
  51034. _this.lowerRadiusLimit = null;
  51035. /**
  51036. * Maximum allowed distance of the camera to the target (The camera can not get further).
  51037. * This can help limiting how the Camera is able to move in the scene.
  51038. */
  51039. _this.upperRadiusLimit = null;
  51040. /**
  51041. * Defines the current inertia value used during panning of the camera along the X axis.
  51042. */
  51043. _this.inertialPanningX = 0;
  51044. /**
  51045. * Defines the current inertia value used during panning of the camera along the Y axis.
  51046. */
  51047. _this.inertialPanningY = 0;
  51048. /**
  51049. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51050. * Basically if your fingers moves away from more than this distance you will be considered
  51051. * in pinch mode.
  51052. */
  51053. _this.pinchToPanMaxDistance = 20;
  51054. /**
  51055. * Defines the maximum distance the camera can pan.
  51056. * This could help keeping the cammera always in your scene.
  51057. */
  51058. _this.panningDistanceLimit = null;
  51059. /**
  51060. * Defines the target of the camera before paning.
  51061. */
  51062. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51063. /**
  51064. * Defines the value of the inertia used during panning.
  51065. * 0 would mean stop inertia and one would mean no decelleration at all.
  51066. */
  51067. _this.panningInertia = 0.9;
  51068. //-- end properties for backward compatibility for inputs
  51069. /**
  51070. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51071. */
  51072. _this.zoomOnFactor = 1;
  51073. /**
  51074. * Defines a screen offset for the camera position.
  51075. */
  51076. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51077. /**
  51078. * Allows the camera to be completely reversed.
  51079. * If false the camera can not arrive upside down.
  51080. */
  51081. _this.allowUpsideDown = true;
  51082. /**
  51083. * Define if double tap/click is used to restore the previously saved state of the camera.
  51084. */
  51085. _this.useInputToRestoreState = true;
  51086. /** @hidden */
  51087. _this._viewMatrix = new BABYLON.Matrix();
  51088. /**
  51089. * Defines the allowed panning axis.
  51090. */
  51091. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51092. /**
  51093. * Observable triggered when the mesh target has been changed on the camera.
  51094. */
  51095. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51096. /**
  51097. * Defines whether the camera should check collision with the objects oh the scene.
  51098. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51099. */
  51100. _this.checkCollisions = false;
  51101. /**
  51102. * Defines the collision radius of the camera.
  51103. * This simulates a sphere around the camera.
  51104. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51105. */
  51106. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51107. _this._previousPosition = BABYLON.Vector3.Zero();
  51108. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51109. _this._newPosition = BABYLON.Vector3.Zero();
  51110. _this._computationVector = BABYLON.Vector3.Zero();
  51111. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51112. if (collidedMesh === void 0) { collidedMesh = null; }
  51113. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51114. newPosition.multiplyInPlace(_this._collider._radius);
  51115. }
  51116. if (!collidedMesh) {
  51117. _this._previousPosition.copyFrom(_this.position);
  51118. }
  51119. else {
  51120. _this.setPosition(newPosition);
  51121. if (_this.onCollide) {
  51122. _this.onCollide(collidedMesh);
  51123. }
  51124. }
  51125. // Recompute because of constraints
  51126. var cosa = Math.cos(_this.alpha);
  51127. var sina = Math.sin(_this.alpha);
  51128. var cosb = Math.cos(_this.beta);
  51129. var sinb = Math.sin(_this.beta);
  51130. if (sinb === 0) {
  51131. sinb = 0.0001;
  51132. }
  51133. var target = _this._getTargetPosition();
  51134. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51135. target.addToRef(_this._computationVector, _this._newPosition);
  51136. _this.position.copyFrom(_this._newPosition);
  51137. var up = _this.upVector;
  51138. if (_this.allowUpsideDown && _this.beta < 0) {
  51139. up = up.clone();
  51140. up = up.negate();
  51141. }
  51142. _this._computeViewMatrix(_this.position, target, up);
  51143. _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x);
  51144. _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y);
  51145. _this._collisionTriggered = false;
  51146. };
  51147. _this._target = BABYLON.Vector3.Zero();
  51148. if (target) {
  51149. _this.setTarget(target);
  51150. }
  51151. _this.alpha = alpha;
  51152. _this.beta = beta;
  51153. _this.radius = radius;
  51154. _this.getViewMatrix();
  51155. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51156. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51157. return _this;
  51158. }
  51159. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51160. /**
  51161. * Defines the target point of the camera.
  51162. * The camera looks towards it form the radius distance.
  51163. */
  51164. get: function () {
  51165. return this._target;
  51166. },
  51167. set: function (value) {
  51168. this.setTarget(value);
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51174. //-- begin properties for backward compatibility for inputs
  51175. /**
  51176. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51177. */
  51178. get: function () {
  51179. var pointers = this.inputs.attached["pointers"];
  51180. if (pointers) {
  51181. return pointers.angularSensibilityX;
  51182. }
  51183. return 0;
  51184. },
  51185. set: function (value) {
  51186. var pointers = this.inputs.attached["pointers"];
  51187. if (pointers) {
  51188. pointers.angularSensibilityX = value;
  51189. }
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51195. /**
  51196. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51197. */
  51198. get: function () {
  51199. var pointers = this.inputs.attached["pointers"];
  51200. if (pointers) {
  51201. return pointers.angularSensibilityY;
  51202. }
  51203. return 0;
  51204. },
  51205. set: function (value) {
  51206. var pointers = this.inputs.attached["pointers"];
  51207. if (pointers) {
  51208. pointers.angularSensibilityY = value;
  51209. }
  51210. },
  51211. enumerable: true,
  51212. configurable: true
  51213. });
  51214. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51215. /**
  51216. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51217. */
  51218. get: function () {
  51219. var pointers = this.inputs.attached["pointers"];
  51220. if (pointers) {
  51221. return pointers.pinchPrecision;
  51222. }
  51223. return 0;
  51224. },
  51225. set: function (value) {
  51226. var pointers = this.inputs.attached["pointers"];
  51227. if (pointers) {
  51228. pointers.pinchPrecision = value;
  51229. }
  51230. },
  51231. enumerable: true,
  51232. configurable: true
  51233. });
  51234. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51235. /**
  51236. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51237. * It will be used instead of pinchDeltaPrecision if different from 0.
  51238. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51239. */
  51240. get: function () {
  51241. var pointers = this.inputs.attached["pointers"];
  51242. if (pointers) {
  51243. return pointers.pinchDeltaPercentage;
  51244. }
  51245. return 0;
  51246. },
  51247. set: function (value) {
  51248. var pointers = this.inputs.attached["pointers"];
  51249. if (pointers) {
  51250. pointers.pinchDeltaPercentage = value;
  51251. }
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51257. /**
  51258. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51259. */
  51260. get: function () {
  51261. var pointers = this.inputs.attached["pointers"];
  51262. if (pointers) {
  51263. return pointers.panningSensibility;
  51264. }
  51265. return 0;
  51266. },
  51267. set: function (value) {
  51268. var pointers = this.inputs.attached["pointers"];
  51269. if (pointers) {
  51270. pointers.panningSensibility = value;
  51271. }
  51272. },
  51273. enumerable: true,
  51274. configurable: true
  51275. });
  51276. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  51277. /**
  51278. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  51279. */
  51280. get: function () {
  51281. var keyboard = this.inputs.attached["keyboard"];
  51282. if (keyboard) {
  51283. return keyboard.keysUp;
  51284. }
  51285. return [];
  51286. },
  51287. set: function (value) {
  51288. var keyboard = this.inputs.attached["keyboard"];
  51289. if (keyboard) {
  51290. keyboard.keysUp = value;
  51291. }
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  51297. /**
  51298. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  51299. */
  51300. get: function () {
  51301. var keyboard = this.inputs.attached["keyboard"];
  51302. if (keyboard) {
  51303. return keyboard.keysDown;
  51304. }
  51305. return [];
  51306. },
  51307. set: function (value) {
  51308. var keyboard = this.inputs.attached["keyboard"];
  51309. if (keyboard) {
  51310. keyboard.keysDown = value;
  51311. }
  51312. },
  51313. enumerable: true,
  51314. configurable: true
  51315. });
  51316. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  51317. /**
  51318. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  51319. */
  51320. get: function () {
  51321. var keyboard = this.inputs.attached["keyboard"];
  51322. if (keyboard) {
  51323. return keyboard.keysLeft;
  51324. }
  51325. return [];
  51326. },
  51327. set: function (value) {
  51328. var keyboard = this.inputs.attached["keyboard"];
  51329. if (keyboard) {
  51330. keyboard.keysLeft = value;
  51331. }
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  51337. /**
  51338. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  51339. */
  51340. get: function () {
  51341. var keyboard = this.inputs.attached["keyboard"];
  51342. if (keyboard) {
  51343. return keyboard.keysRight;
  51344. }
  51345. return [];
  51346. },
  51347. set: function (value) {
  51348. var keyboard = this.inputs.attached["keyboard"];
  51349. if (keyboard) {
  51350. keyboard.keysRight = value;
  51351. }
  51352. },
  51353. enumerable: true,
  51354. configurable: true
  51355. });
  51356. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  51357. /**
  51358. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51359. */
  51360. get: function () {
  51361. var mousewheel = this.inputs.attached["mousewheel"];
  51362. if (mousewheel) {
  51363. return mousewheel.wheelPrecision;
  51364. }
  51365. return 0;
  51366. },
  51367. set: function (value) {
  51368. var mousewheel = this.inputs.attached["mousewheel"];
  51369. if (mousewheel) {
  51370. mousewheel.wheelPrecision = value;
  51371. }
  51372. },
  51373. enumerable: true,
  51374. configurable: true
  51375. });
  51376. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  51377. /**
  51378. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  51379. * It will be used instead of pinchDeltaPrecision if different from 0.
  51380. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51381. */
  51382. get: function () {
  51383. var mousewheel = this.inputs.attached["mousewheel"];
  51384. if (mousewheel) {
  51385. return mousewheel.wheelDeltaPercentage;
  51386. }
  51387. return 0;
  51388. },
  51389. set: function (value) {
  51390. var mousewheel = this.inputs.attached["mousewheel"];
  51391. if (mousewheel) {
  51392. mousewheel.wheelDeltaPercentage = value;
  51393. }
  51394. },
  51395. enumerable: true,
  51396. configurable: true
  51397. });
  51398. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  51399. /**
  51400. * Gets the bouncing behavior of the camera if it has been enabled.
  51401. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51402. */
  51403. get: function () {
  51404. return this._bouncingBehavior;
  51405. },
  51406. enumerable: true,
  51407. configurable: true
  51408. });
  51409. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  51410. /**
  51411. * Defines if the bouncing behavior of the camera is enabled on the camera.
  51412. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51413. */
  51414. get: function () {
  51415. return this._bouncingBehavior != null;
  51416. },
  51417. set: function (value) {
  51418. if (value === this.useBouncingBehavior) {
  51419. return;
  51420. }
  51421. if (value) {
  51422. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  51423. this.addBehavior(this._bouncingBehavior);
  51424. }
  51425. else if (this._bouncingBehavior) {
  51426. this.removeBehavior(this._bouncingBehavior);
  51427. this._bouncingBehavior = null;
  51428. }
  51429. },
  51430. enumerable: true,
  51431. configurable: true
  51432. });
  51433. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  51434. /**
  51435. * Gets the framing behavior of the camera if it has been enabled.
  51436. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51437. */
  51438. get: function () {
  51439. return this._framingBehavior;
  51440. },
  51441. enumerable: true,
  51442. configurable: true
  51443. });
  51444. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  51445. /**
  51446. * Defines if the framing behavior of the camera is enabled on the camera.
  51447. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51448. */
  51449. get: function () {
  51450. return this._framingBehavior != null;
  51451. },
  51452. set: function (value) {
  51453. if (value === this.useFramingBehavior) {
  51454. return;
  51455. }
  51456. if (value) {
  51457. this._framingBehavior = new BABYLON.FramingBehavior();
  51458. this.addBehavior(this._framingBehavior);
  51459. }
  51460. else if (this._framingBehavior) {
  51461. this.removeBehavior(this._framingBehavior);
  51462. this._framingBehavior = null;
  51463. }
  51464. },
  51465. enumerable: true,
  51466. configurable: true
  51467. });
  51468. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  51469. /**
  51470. * Gets the auto rotation behavior of the camera if it has been enabled.
  51471. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51472. */
  51473. get: function () {
  51474. return this._autoRotationBehavior;
  51475. },
  51476. enumerable: true,
  51477. configurable: true
  51478. });
  51479. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  51480. /**
  51481. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  51482. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51483. */
  51484. get: function () {
  51485. return this._autoRotationBehavior != null;
  51486. },
  51487. set: function (value) {
  51488. if (value === this.useAutoRotationBehavior) {
  51489. return;
  51490. }
  51491. if (value) {
  51492. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  51493. this.addBehavior(this._autoRotationBehavior);
  51494. }
  51495. else if (this._autoRotationBehavior) {
  51496. this.removeBehavior(this._autoRotationBehavior);
  51497. this._autoRotationBehavior = null;
  51498. }
  51499. },
  51500. enumerable: true,
  51501. configurable: true
  51502. });
  51503. // Cache
  51504. /** @hidden */
  51505. ArcRotateCamera.prototype._initCache = function () {
  51506. _super.prototype._initCache.call(this);
  51507. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51508. this._cache.alpha = undefined;
  51509. this._cache.beta = undefined;
  51510. this._cache.radius = undefined;
  51511. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  51512. };
  51513. /** @hidden */
  51514. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  51515. if (!ignoreParentClass) {
  51516. _super.prototype._updateCache.call(this);
  51517. }
  51518. this._cache._target.copyFrom(this._getTargetPosition());
  51519. this._cache.alpha = this.alpha;
  51520. this._cache.beta = this.beta;
  51521. this._cache.radius = this.radius;
  51522. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  51523. };
  51524. ArcRotateCamera.prototype._getTargetPosition = function () {
  51525. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  51526. var pos = this._targetHost.absolutePosition;
  51527. if (this._targetBoundingCenter) {
  51528. pos.addToRef(this._targetBoundingCenter, this._target);
  51529. }
  51530. else {
  51531. this._target.copyFrom(pos);
  51532. }
  51533. }
  51534. var lockedTargetPosition = this._getLockedTargetPosition();
  51535. if (lockedTargetPosition) {
  51536. return lockedTargetPosition;
  51537. }
  51538. return this._target;
  51539. };
  51540. /**
  51541. * Stores the current state of the camera (alpha, beta, radius and target)
  51542. * @returns the camera itself
  51543. */
  51544. ArcRotateCamera.prototype.storeState = function () {
  51545. this._storedAlpha = this.alpha;
  51546. this._storedBeta = this.beta;
  51547. this._storedRadius = this.radius;
  51548. this._storedTarget = this._getTargetPosition().clone();
  51549. return _super.prototype.storeState.call(this);
  51550. };
  51551. /**
  51552. * @hidden
  51553. * Restored camera state. You must call storeState() first
  51554. */
  51555. ArcRotateCamera.prototype._restoreStateValues = function () {
  51556. if (!_super.prototype._restoreStateValues.call(this)) {
  51557. return false;
  51558. }
  51559. this.alpha = this._storedAlpha;
  51560. this.beta = this._storedBeta;
  51561. this.radius = this._storedRadius;
  51562. this.setTarget(this._storedTarget.clone());
  51563. this.inertialAlphaOffset = 0;
  51564. this.inertialBetaOffset = 0;
  51565. this.inertialRadiusOffset = 0;
  51566. this.inertialPanningX = 0;
  51567. this.inertialPanningY = 0;
  51568. return true;
  51569. };
  51570. // Synchronized
  51571. /** @hidden */
  51572. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  51573. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  51574. return false;
  51575. }
  51576. return this._cache._target.equals(this._getTargetPosition())
  51577. && this._cache.alpha === this.alpha
  51578. && this._cache.beta === this.beta
  51579. && this._cache.radius === this.radius
  51580. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  51581. };
  51582. /**
  51583. * Attached controls to the current camera.
  51584. * @param element Defines the element the controls should be listened from
  51585. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51586. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  51587. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  51588. */
  51589. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  51590. var _this = this;
  51591. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  51592. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  51593. this._useCtrlForPanning = useCtrlForPanning;
  51594. this._panningMouseButton = panningMouseButton;
  51595. this.inputs.attachElement(element, noPreventDefault);
  51596. this._reset = function () {
  51597. _this.inertialAlphaOffset = 0;
  51598. _this.inertialBetaOffset = 0;
  51599. _this.inertialRadiusOffset = 0;
  51600. _this.inertialPanningX = 0;
  51601. _this.inertialPanningY = 0;
  51602. };
  51603. };
  51604. /**
  51605. * Detach the current controls from the camera.
  51606. * The camera will stop reacting to inputs.
  51607. * @param element Defines the element to stop listening the inputs from
  51608. */
  51609. ArcRotateCamera.prototype.detachControl = function (element) {
  51610. this.inputs.detachElement(element);
  51611. if (this._reset) {
  51612. this._reset();
  51613. }
  51614. };
  51615. /** @hidden */
  51616. ArcRotateCamera.prototype._checkInputs = function () {
  51617. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  51618. if (this._collisionTriggered) {
  51619. return;
  51620. }
  51621. this.inputs.checkInputs();
  51622. // Inertia
  51623. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  51624. var inertialAlphaOffset = this.inertialAlphaOffset;
  51625. if (this.beta <= 0) {
  51626. inertialAlphaOffset *= -1;
  51627. }
  51628. if (this.getScene().useRightHandedSystem) {
  51629. inertialAlphaOffset *= -1;
  51630. }
  51631. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  51632. inertialAlphaOffset *= -1;
  51633. }
  51634. this.alpha += inertialAlphaOffset;
  51635. this.beta += this.inertialBetaOffset;
  51636. this.radius -= this.inertialRadiusOffset;
  51637. this.inertialAlphaOffset *= this.inertia;
  51638. this.inertialBetaOffset *= this.inertia;
  51639. this.inertialRadiusOffset *= this.inertia;
  51640. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  51641. this.inertialAlphaOffset = 0;
  51642. }
  51643. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  51644. this.inertialBetaOffset = 0;
  51645. }
  51646. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  51647. this.inertialRadiusOffset = 0;
  51648. }
  51649. }
  51650. // Panning inertia
  51651. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  51652. if (!this._localDirection) {
  51653. this._localDirection = BABYLON.Vector3.Zero();
  51654. this._transformedDirection = BABYLON.Vector3.Zero();
  51655. }
  51656. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  51657. this._localDirection.multiplyInPlace(this.panningAxis);
  51658. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  51659. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  51660. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  51661. if (!this.panningAxis.y) {
  51662. this._transformedDirection.y = 0;
  51663. }
  51664. if (!this._targetHost) {
  51665. if (this.panningDistanceLimit) {
  51666. this._transformedDirection.addInPlace(this._target);
  51667. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  51668. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  51669. this._target.copyFrom(this._transformedDirection);
  51670. }
  51671. }
  51672. else {
  51673. this._target.addInPlace(this._transformedDirection);
  51674. }
  51675. }
  51676. this.inertialPanningX *= this.panningInertia;
  51677. this.inertialPanningY *= this.panningInertia;
  51678. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  51679. this.inertialPanningX = 0;
  51680. }
  51681. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  51682. this.inertialPanningY = 0;
  51683. }
  51684. }
  51685. // Limits
  51686. this._checkLimits();
  51687. _super.prototype._checkInputs.call(this);
  51688. };
  51689. ArcRotateCamera.prototype._checkLimits = function () {
  51690. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  51691. if (this.allowUpsideDown && this.beta > Math.PI) {
  51692. this.beta = this.beta - (2 * Math.PI);
  51693. }
  51694. }
  51695. else {
  51696. if (this.beta < this.lowerBetaLimit) {
  51697. this.beta = this.lowerBetaLimit;
  51698. }
  51699. }
  51700. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  51701. if (this.allowUpsideDown && this.beta < -Math.PI) {
  51702. this.beta = this.beta + (2 * Math.PI);
  51703. }
  51704. }
  51705. else {
  51706. if (this.beta > this.upperBetaLimit) {
  51707. this.beta = this.upperBetaLimit;
  51708. }
  51709. }
  51710. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  51711. this.alpha = this.lowerAlphaLimit;
  51712. }
  51713. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  51714. this.alpha = this.upperAlphaLimit;
  51715. }
  51716. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  51717. this.radius = this.lowerRadiusLimit;
  51718. this.inertialRadiusOffset = 0;
  51719. }
  51720. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  51721. this.radius = this.upperRadiusLimit;
  51722. this.inertialRadiusOffset = 0;
  51723. }
  51724. };
  51725. /**
  51726. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  51727. */
  51728. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  51729. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  51730. this.radius = this._computationVector.length();
  51731. if (this.radius === 0) {
  51732. this.radius = 0.0001; // Just to avoid division by zero
  51733. }
  51734. // Alpha
  51735. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  51736. if (this._computationVector.z < 0) {
  51737. this.alpha = 2 * Math.PI - this.alpha;
  51738. }
  51739. // Beta
  51740. this.beta = Math.acos(this._computationVector.y / this.radius);
  51741. this._checkLimits();
  51742. };
  51743. /**
  51744. * Use a position to define the current camera related information like aplha, beta and radius
  51745. * @param position Defines the position to set the camera at
  51746. */
  51747. ArcRotateCamera.prototype.setPosition = function (position) {
  51748. if (this.position.equals(position)) {
  51749. return;
  51750. }
  51751. this.position.copyFrom(position);
  51752. this.rebuildAnglesAndRadius();
  51753. };
  51754. /**
  51755. * Defines the target the camera should look at.
  51756. * This will automatically adapt alpha beta and radius to fit within the new target.
  51757. * @param target Defines the new target as a Vector or a mesh
  51758. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  51759. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  51760. */
  51761. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  51762. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  51763. if (allowSamePosition === void 0) { allowSamePosition = false; }
  51764. if (target.getBoundingInfo) {
  51765. if (toBoundingCenter) {
  51766. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  51767. }
  51768. else {
  51769. this._targetBoundingCenter = null;
  51770. }
  51771. this._targetHost = target;
  51772. this._target = this._getTargetPosition();
  51773. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  51774. }
  51775. else {
  51776. var newTarget = target;
  51777. var currentTarget = this._getTargetPosition();
  51778. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  51779. return;
  51780. }
  51781. this._targetHost = null;
  51782. this._target = newTarget;
  51783. this._targetBoundingCenter = null;
  51784. this.onMeshTargetChangedObservable.notifyObservers(null);
  51785. }
  51786. this.rebuildAnglesAndRadius();
  51787. };
  51788. /** @hidden */
  51789. ArcRotateCamera.prototype._getViewMatrix = function () {
  51790. // Compute
  51791. var cosa = Math.cos(this.alpha);
  51792. var sina = Math.sin(this.alpha);
  51793. var cosb = Math.cos(this.beta);
  51794. var sinb = Math.sin(this.beta);
  51795. if (sinb === 0) {
  51796. sinb = 0.0001;
  51797. }
  51798. var target = this._getTargetPosition();
  51799. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  51800. target.addToRef(this._computationVector, this._newPosition);
  51801. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  51802. if (!this._collider) {
  51803. this._collider = new BABYLON.Collider();
  51804. }
  51805. this._collider._radius = this.collisionRadius;
  51806. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  51807. this._collisionTriggered = true;
  51808. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  51809. }
  51810. else {
  51811. this.position.copyFrom(this._newPosition);
  51812. var up = this.upVector;
  51813. if (this.allowUpsideDown && sinb < 0) {
  51814. up = up.clone();
  51815. up = up.negate();
  51816. }
  51817. this._computeViewMatrix(this.position, target, up);
  51818. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  51819. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  51820. }
  51821. this._currentTarget = target;
  51822. return this._viewMatrix;
  51823. };
  51824. /**
  51825. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  51826. * @param meshes Defines the mesh to zoom on
  51827. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  51828. */
  51829. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  51830. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51831. meshes = meshes || this.getScene().meshes;
  51832. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  51833. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  51834. this.radius = distance * this.zoomOnFactor;
  51835. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  51836. };
  51837. /**
  51838. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  51839. * The target will be changed but the radius
  51840. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  51841. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  51842. */
  51843. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  51844. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51845. var meshesOrMinMaxVector;
  51846. var distance;
  51847. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  51848. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  51849. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  51850. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  51851. }
  51852. else { //minMaxVector and distance
  51853. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  51854. meshesOrMinMaxVector = minMaxVectorAndDistance;
  51855. distance = minMaxVectorAndDistance.distance;
  51856. }
  51857. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  51858. if (!doNotUpdateMaxZ) {
  51859. this.maxZ = distance * 2;
  51860. }
  51861. };
  51862. /**
  51863. * @override
  51864. * Override Camera.createRigCamera
  51865. */
  51866. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  51867. var alphaShift = 0;
  51868. switch (this.cameraRigMode) {
  51869. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51872. case BABYLON.Camera.RIG_MODE_VR:
  51873. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  51874. break;
  51875. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51876. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  51877. break;
  51878. }
  51879. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  51880. rigCam._cameraRigParams = {};
  51881. return rigCam;
  51882. };
  51883. /**
  51884. * @hidden
  51885. * @override
  51886. * Override Camera._updateRigCameras
  51887. */
  51888. ArcRotateCamera.prototype._updateRigCameras = function () {
  51889. var camLeft = this._rigCameras[0];
  51890. var camRight = this._rigCameras[1];
  51891. camLeft.beta = camRight.beta = this.beta;
  51892. camLeft.radius = camRight.radius = this.radius;
  51893. switch (this.cameraRigMode) {
  51894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51897. case BABYLON.Camera.RIG_MODE_VR:
  51898. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51899. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51900. break;
  51901. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51902. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51903. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51904. break;
  51905. }
  51906. _super.prototype._updateRigCameras.call(this);
  51907. };
  51908. /**
  51909. * Destroy the camera and release the current resources hold by it.
  51910. */
  51911. ArcRotateCamera.prototype.dispose = function () {
  51912. this.inputs.clear();
  51913. _super.prototype.dispose.call(this);
  51914. };
  51915. /**
  51916. * Gets the current object class name.
  51917. * @return the class name
  51918. */
  51919. ArcRotateCamera.prototype.getClassName = function () {
  51920. return "ArcRotateCamera";
  51921. };
  51922. __decorate([
  51923. BABYLON.serialize()
  51924. ], ArcRotateCamera.prototype, "alpha", void 0);
  51925. __decorate([
  51926. BABYLON.serialize()
  51927. ], ArcRotateCamera.prototype, "beta", void 0);
  51928. __decorate([
  51929. BABYLON.serialize()
  51930. ], ArcRotateCamera.prototype, "radius", void 0);
  51931. __decorate([
  51932. BABYLON.serializeAsVector3("target")
  51933. ], ArcRotateCamera.prototype, "_target", void 0);
  51934. __decorate([
  51935. BABYLON.serialize()
  51936. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  51937. __decorate([
  51938. BABYLON.serialize()
  51939. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  51940. __decorate([
  51941. BABYLON.serialize()
  51942. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  51943. __decorate([
  51944. BABYLON.serialize()
  51945. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  51946. __decorate([
  51947. BABYLON.serialize()
  51948. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  51949. __decorate([
  51950. BABYLON.serialize()
  51951. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  51952. __decorate([
  51953. BABYLON.serialize()
  51954. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  51955. __decorate([
  51956. BABYLON.serialize()
  51957. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  51958. __decorate([
  51959. BABYLON.serialize()
  51960. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  51961. __decorate([
  51962. BABYLON.serialize()
  51963. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  51964. __decorate([
  51965. BABYLON.serialize()
  51966. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  51967. __decorate([
  51968. BABYLON.serialize()
  51969. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  51970. __decorate([
  51971. BABYLON.serialize()
  51972. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  51973. __decorate([
  51974. BABYLON.serializeAsVector3()
  51975. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  51976. __decorate([
  51977. BABYLON.serialize()
  51978. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  51979. __decorate([
  51980. BABYLON.serialize()
  51981. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  51982. __decorate([
  51983. BABYLON.serialize()
  51984. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  51985. __decorate([
  51986. BABYLON.serialize()
  51987. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  51988. __decorate([
  51989. BABYLON.serialize()
  51990. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  51991. return ArcRotateCamera;
  51992. }(BABYLON.TargetCamera));
  51993. BABYLON.ArcRotateCamera = ArcRotateCamera;
  51994. })(BABYLON || (BABYLON = {}));
  51995. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  51996. var BABYLON;
  51997. (function (BABYLON) {
  51998. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  51999. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  52000. });
  52001. /**
  52002. * The HemisphericLight simulates the ambient environment light,
  52003. * so the passed direction is the light reflection direction, not the incoming direction.
  52004. */
  52005. var HemisphericLight = /** @class */ (function (_super) {
  52006. __extends(HemisphericLight, _super);
  52007. /**
  52008. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  52009. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  52010. * The HemisphericLight can't cast shadows.
  52011. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52012. * @param name The friendly name of the light
  52013. * @param direction The direction of the light reflection
  52014. * @param scene The scene the light belongs to
  52015. */
  52016. function HemisphericLight(name, direction, scene) {
  52017. var _this = _super.call(this, name, scene) || this;
  52018. /**
  52019. * The groundColor is the light in the opposite direction to the one specified during creation.
  52020. * 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.
  52021. */
  52022. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  52023. _this.direction = direction || BABYLON.Vector3.Up();
  52024. return _this;
  52025. }
  52026. HemisphericLight.prototype._buildUniformLayout = function () {
  52027. this._uniformBuffer.addUniform("vLightData", 4);
  52028. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52029. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52030. this._uniformBuffer.addUniform("vLightGround", 3);
  52031. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52032. this._uniformBuffer.addUniform("depthValues", 2);
  52033. this._uniformBuffer.create();
  52034. };
  52035. /**
  52036. * Returns the string "HemisphericLight".
  52037. * @return The class name
  52038. */
  52039. HemisphericLight.prototype.getClassName = function () {
  52040. return "HemisphericLight";
  52041. };
  52042. /**
  52043. * Sets the HemisphericLight direction towards the passed target (Vector3).
  52044. * Returns the updated direction.
  52045. * @param target The target the direction should point to
  52046. * @return The computed direction
  52047. */
  52048. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52049. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52050. return this.direction;
  52051. };
  52052. /**
  52053. * Returns the shadow generator associated to the light.
  52054. * @returns Always null for hemispheric lights because it does not support shadows.
  52055. */
  52056. HemisphericLight.prototype.getShadowGenerator = function () {
  52057. return null;
  52058. };
  52059. /**
  52060. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52061. * @param effect The effect to update
  52062. * @param lightIndex The index of the light in the effect to update
  52063. * @returns The hemispheric light
  52064. */
  52065. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52066. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52067. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52068. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52069. return this;
  52070. };
  52071. /**
  52072. * Computes the world matrix of the node
  52073. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52074. * @param useWasUpdatedFlag defines a reserved property
  52075. * @returns the world matrix
  52076. */
  52077. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52078. if (!this._worldMatrix) {
  52079. this._worldMatrix = BABYLON.Matrix.Identity();
  52080. }
  52081. return this._worldMatrix;
  52082. };
  52083. /**
  52084. * Returns the integer 3.
  52085. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52086. */
  52087. HemisphericLight.prototype.getTypeID = function () {
  52088. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52089. };
  52090. /**
  52091. * Prepares the list of defines specific to the light type.
  52092. * @param defines the list of defines
  52093. * @param lightIndex defines the index of the light for the effect
  52094. */
  52095. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52096. defines["HEMILIGHT" + lightIndex] = true;
  52097. };
  52098. __decorate([
  52099. BABYLON.serializeAsColor3()
  52100. ], HemisphericLight.prototype, "groundColor", void 0);
  52101. __decorate([
  52102. BABYLON.serializeAsVector3()
  52103. ], HemisphericLight.prototype, "direction", void 0);
  52104. return HemisphericLight;
  52105. }(BABYLON.Light));
  52106. BABYLON.HemisphericLight = HemisphericLight;
  52107. })(BABYLON || (BABYLON = {}));
  52108. //# sourceMappingURL=babylon.hemisphericLight.js.map
  52109. var BABYLON;
  52110. (function (BABYLON) {
  52111. /**
  52112. * Base implementation IShadowLight
  52113. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52114. */
  52115. var ShadowLight = /** @class */ (function (_super) {
  52116. __extends(ShadowLight, _super);
  52117. function ShadowLight() {
  52118. var _this = _super !== null && _super.apply(this, arguments) || this;
  52119. _this._needProjectionMatrixCompute = true;
  52120. return _this;
  52121. }
  52122. ShadowLight.prototype._setPosition = function (value) {
  52123. this._position = value;
  52124. };
  52125. Object.defineProperty(ShadowLight.prototype, "position", {
  52126. /**
  52127. * Sets the position the shadow will be casted from. Also use as the light position for both
  52128. * point and spot lights.
  52129. */
  52130. get: function () {
  52131. return this._position;
  52132. },
  52133. /**
  52134. * Sets the position the shadow will be casted from. Also use as the light position for both
  52135. * point and spot lights.
  52136. */
  52137. set: function (value) {
  52138. this._setPosition(value);
  52139. },
  52140. enumerable: true,
  52141. configurable: true
  52142. });
  52143. ShadowLight.prototype._setDirection = function (value) {
  52144. this._direction = value;
  52145. };
  52146. Object.defineProperty(ShadowLight.prototype, "direction", {
  52147. /**
  52148. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52149. * Also use as the light direction on spot and directional lights.
  52150. */
  52151. get: function () {
  52152. return this._direction;
  52153. },
  52154. /**
  52155. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52156. * Also use as the light direction on spot and directional lights.
  52157. */
  52158. set: function (value) {
  52159. this._setDirection(value);
  52160. },
  52161. enumerable: true,
  52162. configurable: true
  52163. });
  52164. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52165. /**
  52166. * Gets the shadow projection clipping minimum z value.
  52167. */
  52168. get: function () {
  52169. return this._shadowMinZ;
  52170. },
  52171. /**
  52172. * Sets the shadow projection clipping minimum z value.
  52173. */
  52174. set: function (value) {
  52175. this._shadowMinZ = value;
  52176. this.forceProjectionMatrixCompute();
  52177. },
  52178. enumerable: true,
  52179. configurable: true
  52180. });
  52181. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52182. /**
  52183. * Sets the shadow projection clipping maximum z value.
  52184. */
  52185. get: function () {
  52186. return this._shadowMaxZ;
  52187. },
  52188. /**
  52189. * Gets the shadow projection clipping maximum z value.
  52190. */
  52191. set: function (value) {
  52192. this._shadowMaxZ = value;
  52193. this.forceProjectionMatrixCompute();
  52194. },
  52195. enumerable: true,
  52196. configurable: true
  52197. });
  52198. /**
  52199. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52200. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52201. */
  52202. ShadowLight.prototype.computeTransformedInformation = function () {
  52203. if (this.parent && this.parent.getWorldMatrix) {
  52204. if (!this.transformedPosition) {
  52205. this.transformedPosition = BABYLON.Vector3.Zero();
  52206. }
  52207. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52208. // In case the direction is present.
  52209. if (this.direction) {
  52210. if (!this.transformedDirection) {
  52211. this.transformedDirection = BABYLON.Vector3.Zero();
  52212. }
  52213. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52214. }
  52215. return true;
  52216. }
  52217. return false;
  52218. };
  52219. /**
  52220. * Return the depth scale used for the shadow map.
  52221. * @returns the depth scale.
  52222. */
  52223. ShadowLight.prototype.getDepthScale = function () {
  52224. return 50.0;
  52225. };
  52226. /**
  52227. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52228. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52229. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52230. */
  52231. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52232. return this.transformedDirection ? this.transformedDirection : this.direction;
  52233. };
  52234. /**
  52235. * Returns the ShadowLight absolute position in the World.
  52236. * @returns the position vector in world space
  52237. */
  52238. ShadowLight.prototype.getAbsolutePosition = function () {
  52239. return this.transformedPosition ? this.transformedPosition : this.position;
  52240. };
  52241. /**
  52242. * Sets the ShadowLight direction toward the passed target.
  52243. * @param target The point tot target in local space
  52244. * @returns the updated ShadowLight direction
  52245. */
  52246. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52247. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52248. return this.direction;
  52249. };
  52250. /**
  52251. * Returns the light rotation in euler definition.
  52252. * @returns the x y z rotation in local space.
  52253. */
  52254. ShadowLight.prototype.getRotation = function () {
  52255. this.direction.normalize();
  52256. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52257. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52258. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52259. };
  52260. /**
  52261. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52262. * @returns true if a cube texture needs to be use
  52263. */
  52264. ShadowLight.prototype.needCube = function () {
  52265. return false;
  52266. };
  52267. /**
  52268. * Detects if the projection matrix requires to be recomputed this frame.
  52269. * @returns true if it requires to be recomputed otherwise, false.
  52270. */
  52271. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  52272. return this._needProjectionMatrixCompute;
  52273. };
  52274. /**
  52275. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  52276. */
  52277. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  52278. this._needProjectionMatrixCompute = true;
  52279. };
  52280. /** @hidden */
  52281. ShadowLight.prototype._initCache = function () {
  52282. _super.prototype._initCache.call(this);
  52283. this._cache.position = BABYLON.Vector3.Zero();
  52284. };
  52285. /** @hidden */
  52286. ShadowLight.prototype._isSynchronized = function () {
  52287. if (!this._cache.position.equals(this.position)) {
  52288. return false;
  52289. }
  52290. return true;
  52291. };
  52292. /**
  52293. * Computes the world matrix of the node
  52294. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52295. * @returns the world matrix
  52296. */
  52297. ShadowLight.prototype.computeWorldMatrix = function (force) {
  52298. if (!force && this.isSynchronized()) {
  52299. this._currentRenderId = this.getScene().getRenderId();
  52300. return this._worldMatrix;
  52301. }
  52302. this._updateCache();
  52303. this._cache.position.copyFrom(this.position);
  52304. if (!this._worldMatrix) {
  52305. this._worldMatrix = BABYLON.Matrix.Identity();
  52306. }
  52307. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  52308. if (this.parent && this.parent.getWorldMatrix) {
  52309. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  52310. this._markSyncedWithParent();
  52311. }
  52312. // Cache the determinant
  52313. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  52314. return this._worldMatrix;
  52315. };
  52316. /**
  52317. * Gets the minZ used for shadow according to both the scene and the light.
  52318. * @param activeCamera The camera we are returning the min for
  52319. * @returns the depth min z
  52320. */
  52321. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  52322. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  52323. };
  52324. /**
  52325. * Gets the maxZ used for shadow according to both the scene and the light.
  52326. * @param activeCamera The camera we are returning the max for
  52327. * @returns the depth max z
  52328. */
  52329. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  52330. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  52331. };
  52332. /**
  52333. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  52334. * @param matrix The materix to updated with the projection information
  52335. * @param viewMatrix The transform matrix of the light
  52336. * @param renderList The list of mesh to render in the map
  52337. * @returns The current light
  52338. */
  52339. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52340. if (this.customProjectionMatrixBuilder) {
  52341. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  52342. }
  52343. else {
  52344. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52345. }
  52346. return this;
  52347. };
  52348. __decorate([
  52349. BABYLON.serializeAsVector3()
  52350. ], ShadowLight.prototype, "position", null);
  52351. __decorate([
  52352. BABYLON.serializeAsVector3()
  52353. ], ShadowLight.prototype, "direction", null);
  52354. __decorate([
  52355. BABYLON.serialize()
  52356. ], ShadowLight.prototype, "shadowMinZ", null);
  52357. __decorate([
  52358. BABYLON.serialize()
  52359. ], ShadowLight.prototype, "shadowMaxZ", null);
  52360. return ShadowLight;
  52361. }(BABYLON.Light));
  52362. BABYLON.ShadowLight = ShadowLight;
  52363. })(BABYLON || (BABYLON = {}));
  52364. //# sourceMappingURL=babylon.shadowLight.js.map
  52365. var BABYLON;
  52366. (function (BABYLON) {
  52367. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  52368. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  52369. });
  52370. /**
  52371. * A point light is a light defined by an unique point in world space.
  52372. * The light is emitted in every direction from this point.
  52373. * A good example of a point light is a standard light bulb.
  52374. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52375. */
  52376. var PointLight = /** @class */ (function (_super) {
  52377. __extends(PointLight, _super);
  52378. /**
  52379. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  52380. * A PointLight emits the light in every direction.
  52381. * It can cast shadows.
  52382. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  52383. * ```javascript
  52384. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  52385. * ```
  52386. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52387. * @param name The light friendly name
  52388. * @param position The position of the point light in the scene
  52389. * @param scene The scene the lights belongs to
  52390. */
  52391. function PointLight(name, position, scene) {
  52392. var _this = _super.call(this, name, scene) || this;
  52393. _this._shadowAngle = Math.PI / 2;
  52394. _this.position = position;
  52395. return _this;
  52396. }
  52397. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  52398. /**
  52399. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52400. * This specifies what angle the shadow will use to be created.
  52401. *
  52402. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52403. */
  52404. get: function () {
  52405. return this._shadowAngle;
  52406. },
  52407. /**
  52408. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52409. * This specifies what angle the shadow will use to be created.
  52410. *
  52411. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52412. */
  52413. set: function (value) {
  52414. this._shadowAngle = value;
  52415. this.forceProjectionMatrixCompute();
  52416. },
  52417. enumerable: true,
  52418. configurable: true
  52419. });
  52420. Object.defineProperty(PointLight.prototype, "direction", {
  52421. /**
  52422. * Gets the direction if it has been set.
  52423. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52424. */
  52425. get: function () {
  52426. return this._direction;
  52427. },
  52428. /**
  52429. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52430. */
  52431. set: function (value) {
  52432. var previousNeedCube = this.needCube();
  52433. this._direction = value;
  52434. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  52435. this._shadowGenerator.recreateShadowMap();
  52436. }
  52437. },
  52438. enumerable: true,
  52439. configurable: true
  52440. });
  52441. /**
  52442. * Returns the string "PointLight"
  52443. * @returns the class name
  52444. */
  52445. PointLight.prototype.getClassName = function () {
  52446. return "PointLight";
  52447. };
  52448. /**
  52449. * Returns the integer 0.
  52450. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52451. */
  52452. PointLight.prototype.getTypeID = function () {
  52453. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  52454. };
  52455. /**
  52456. * Specifies wether or not the shadowmap should be a cube texture.
  52457. * @returns true if the shadowmap needs to be a cube texture.
  52458. */
  52459. PointLight.prototype.needCube = function () {
  52460. return !this.direction;
  52461. };
  52462. /**
  52463. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  52464. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52465. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52466. */
  52467. PointLight.prototype.getShadowDirection = function (faceIndex) {
  52468. if (this.direction) {
  52469. return _super.prototype.getShadowDirection.call(this, faceIndex);
  52470. }
  52471. else {
  52472. switch (faceIndex) {
  52473. case 0:
  52474. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  52475. case 1:
  52476. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  52477. case 2:
  52478. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  52479. case 3:
  52480. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  52481. case 4:
  52482. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  52483. case 5:
  52484. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  52485. }
  52486. }
  52487. return BABYLON.Vector3.Zero();
  52488. };
  52489. /**
  52490. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  52491. * - fov = PI / 2
  52492. * - aspect ratio : 1.0
  52493. * - z-near and far equal to the active camera minZ and maxZ.
  52494. * Returns the PointLight.
  52495. */
  52496. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52497. var activeCamera = this.getScene().activeCamera;
  52498. if (!activeCamera) {
  52499. return;
  52500. }
  52501. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52502. };
  52503. PointLight.prototype._buildUniformLayout = function () {
  52504. this._uniformBuffer.addUniform("vLightData", 4);
  52505. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52506. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52507. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52508. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52509. this._uniformBuffer.addUniform("depthValues", 2);
  52510. this._uniformBuffer.create();
  52511. };
  52512. /**
  52513. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  52514. * @param effect The effect to update
  52515. * @param lightIndex The index of the light in the effect to update
  52516. * @returns The point light
  52517. */
  52518. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  52519. if (this.computeTransformedInformation()) {
  52520. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  52521. }
  52522. else {
  52523. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  52524. }
  52525. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  52526. return this;
  52527. };
  52528. /**
  52529. * Prepares the list of defines specific to the light type.
  52530. * @param defines the list of defines
  52531. * @param lightIndex defines the index of the light for the effect
  52532. */
  52533. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52534. defines["POINTLIGHT" + lightIndex] = true;
  52535. };
  52536. __decorate([
  52537. BABYLON.serialize()
  52538. ], PointLight.prototype, "shadowAngle", null);
  52539. return PointLight;
  52540. }(BABYLON.ShadowLight));
  52541. BABYLON.PointLight = PointLight;
  52542. })(BABYLON || (BABYLON = {}));
  52543. //# sourceMappingURL=babylon.pointLight.js.map
  52544. var BABYLON;
  52545. (function (BABYLON) {
  52546. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  52547. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  52548. });
  52549. /**
  52550. * A directional light is defined by a direction (what a surprise!).
  52551. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  52552. * 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.
  52553. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52554. */
  52555. var DirectionalLight = /** @class */ (function (_super) {
  52556. __extends(DirectionalLight, _super);
  52557. /**
  52558. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  52559. * The directional light is emitted from everywhere in the given direction.
  52560. * It can cast shadows.
  52561. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52562. * @param name The friendly name of the light
  52563. * @param direction The direction of the light
  52564. * @param scene The scene the light belongs to
  52565. */
  52566. function DirectionalLight(name, direction, scene) {
  52567. var _this = _super.call(this, name, scene) || this;
  52568. _this._shadowFrustumSize = 0;
  52569. _this._shadowOrthoScale = 0.1;
  52570. /**
  52571. * Automatically compute the projection matrix to best fit (including all the casters)
  52572. * on each frame.
  52573. */
  52574. _this.autoUpdateExtends = true;
  52575. // Cache
  52576. _this._orthoLeft = Number.MAX_VALUE;
  52577. _this._orthoRight = Number.MIN_VALUE;
  52578. _this._orthoTop = Number.MIN_VALUE;
  52579. _this._orthoBottom = Number.MAX_VALUE;
  52580. _this.position = direction.scale(-1.0);
  52581. _this.direction = direction;
  52582. return _this;
  52583. }
  52584. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  52585. /**
  52586. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  52587. */
  52588. get: function () {
  52589. return this._shadowFrustumSize;
  52590. },
  52591. /**
  52592. * Specifies a fix frustum size for the shadow generation.
  52593. */
  52594. set: function (value) {
  52595. this._shadowFrustumSize = value;
  52596. this.forceProjectionMatrixCompute();
  52597. },
  52598. enumerable: true,
  52599. configurable: true
  52600. });
  52601. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  52602. /**
  52603. * Gets the shadow projection scale against the optimal computed one.
  52604. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52605. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52606. */
  52607. get: function () {
  52608. return this._shadowOrthoScale;
  52609. },
  52610. /**
  52611. * Sets the shadow projection scale against the optimal computed one.
  52612. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52613. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52614. */
  52615. set: function (value) {
  52616. this._shadowOrthoScale = value;
  52617. this.forceProjectionMatrixCompute();
  52618. },
  52619. enumerable: true,
  52620. configurable: true
  52621. });
  52622. /**
  52623. * Returns the string "DirectionalLight".
  52624. * @return The class name
  52625. */
  52626. DirectionalLight.prototype.getClassName = function () {
  52627. return "DirectionalLight";
  52628. };
  52629. /**
  52630. * Returns the integer 1.
  52631. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52632. */
  52633. DirectionalLight.prototype.getTypeID = function () {
  52634. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  52635. };
  52636. /**
  52637. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  52638. * Returns the DirectionalLight Shadow projection matrix.
  52639. */
  52640. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52641. if (this.shadowFrustumSize > 0) {
  52642. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  52643. }
  52644. else {
  52645. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52646. }
  52647. };
  52648. /**
  52649. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  52650. * Returns the DirectionalLight Shadow projection matrix.
  52651. */
  52652. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  52653. var activeCamera = this.getScene().activeCamera;
  52654. if (!activeCamera) {
  52655. return;
  52656. }
  52657. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  52658. };
  52659. /**
  52660. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  52661. * Returns the DirectionalLight Shadow projection matrix.
  52662. */
  52663. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52664. var activeCamera = this.getScene().activeCamera;
  52665. if (!activeCamera) {
  52666. return;
  52667. }
  52668. // Check extends
  52669. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  52670. var tempVector3 = BABYLON.Vector3.Zero();
  52671. this._orthoLeft = Number.MAX_VALUE;
  52672. this._orthoRight = Number.MIN_VALUE;
  52673. this._orthoTop = Number.MIN_VALUE;
  52674. this._orthoBottom = Number.MAX_VALUE;
  52675. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  52676. var mesh = renderList[meshIndex];
  52677. if (!mesh) {
  52678. continue;
  52679. }
  52680. var boundingInfo = mesh.getBoundingInfo();
  52681. var boundingBox = boundingInfo.boundingBox;
  52682. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  52683. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  52684. if (tempVector3.x < this._orthoLeft) {
  52685. this._orthoLeft = tempVector3.x;
  52686. }
  52687. if (tempVector3.y < this._orthoBottom) {
  52688. this._orthoBottom = tempVector3.y;
  52689. }
  52690. if (tempVector3.x > this._orthoRight) {
  52691. this._orthoRight = tempVector3.x;
  52692. }
  52693. if (tempVector3.y > this._orthoTop) {
  52694. this._orthoTop = tempVector3.y;
  52695. }
  52696. }
  52697. }
  52698. }
  52699. var xOffset = this._orthoRight - this._orthoLeft;
  52700. var yOffset = this._orthoTop - this._orthoBottom;
  52701. 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);
  52702. };
  52703. DirectionalLight.prototype._buildUniformLayout = function () {
  52704. this._uniformBuffer.addUniform("vLightData", 4);
  52705. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52706. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52707. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52708. this._uniformBuffer.addUniform("depthValues", 2);
  52709. this._uniformBuffer.create();
  52710. };
  52711. /**
  52712. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  52713. * @param effect The effect to update
  52714. * @param lightIndex The index of the light in the effect to update
  52715. * @returns The directional light
  52716. */
  52717. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  52718. if (this.computeTransformedInformation()) {
  52719. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  52720. return this;
  52721. }
  52722. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  52723. return this;
  52724. };
  52725. /**
  52726. * Gets the minZ used for shadow according to both the scene and the light.
  52727. *
  52728. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52729. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52730. * @param activeCamera The camera we are returning the min for
  52731. * @returns the depth min z
  52732. */
  52733. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  52734. return 1;
  52735. };
  52736. /**
  52737. * Gets the maxZ used for shadow according to both the scene and the light.
  52738. *
  52739. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52740. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52741. * @param activeCamera The camera we are returning the max for
  52742. * @returns the depth max z
  52743. */
  52744. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  52745. return 1;
  52746. };
  52747. /**
  52748. * Prepares the list of defines specific to the light type.
  52749. * @param defines the list of defines
  52750. * @param lightIndex defines the index of the light for the effect
  52751. */
  52752. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52753. defines["DIRLIGHT" + lightIndex] = true;
  52754. };
  52755. __decorate([
  52756. BABYLON.serialize()
  52757. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  52758. __decorate([
  52759. BABYLON.serialize()
  52760. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  52761. __decorate([
  52762. BABYLON.serialize()
  52763. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  52764. return DirectionalLight;
  52765. }(BABYLON.ShadowLight));
  52766. BABYLON.DirectionalLight = DirectionalLight;
  52767. })(BABYLON || (BABYLON = {}));
  52768. //# sourceMappingURL=babylon.directionalLight.js.map
  52769. var BABYLON;
  52770. (function (BABYLON) {
  52771. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  52772. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  52773. });
  52774. /**
  52775. * A spot light is defined by a position, a direction, an angle, and an exponent.
  52776. * These values define a cone of light starting from the position, emitting toward the direction.
  52777. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  52778. * and the exponent defines the speed of the decay of the light with distance (reach).
  52779. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52780. */
  52781. var SpotLight = /** @class */ (function (_super) {
  52782. __extends(SpotLight, _super);
  52783. /**
  52784. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  52785. * It can cast shadows.
  52786. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52787. * @param name The light friendly name
  52788. * @param position The position of the spot light in the scene
  52789. * @param direction The direction of the light in the scene
  52790. * @param angle The cone angle of the light in Radians
  52791. * @param exponent The light decay speed with the distance from the emission spot
  52792. * @param scene The scene the lights belongs to
  52793. */
  52794. function SpotLight(name, position, direction, angle, exponent, scene) {
  52795. var _this = _super.call(this, name, scene) || this;
  52796. _this._innerAngle = 0;
  52797. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  52798. _this._projectionTextureLightNear = 1e-6;
  52799. _this._projectionTextureLightFar = 1000.0;
  52800. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  52801. _this._projectionTextureViewLightDirty = true;
  52802. _this._projectionTextureProjectionLightDirty = true;
  52803. _this._projectionTextureDirty = true;
  52804. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  52805. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  52806. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  52807. _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);
  52808. _this.position = position;
  52809. _this.direction = direction;
  52810. _this.angle = angle;
  52811. _this.exponent = exponent;
  52812. return _this;
  52813. }
  52814. Object.defineProperty(SpotLight.prototype, "angle", {
  52815. /**
  52816. * Gets the cone angle of the spot light in Radians.
  52817. */
  52818. get: function () {
  52819. return this._angle;
  52820. },
  52821. /**
  52822. * Sets the cone angle of the spot light in Radians.
  52823. */
  52824. set: function (value) {
  52825. this._angle = value;
  52826. this._cosHalfAngle = Math.cos(value * 0.5);
  52827. this._projectionTextureProjectionLightDirty = true;
  52828. this.forceProjectionMatrixCompute();
  52829. this._computeAngleValues();
  52830. },
  52831. enumerable: true,
  52832. configurable: true
  52833. });
  52834. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  52835. /**
  52836. * Only used in gltf falloff mode, this defines the angle where
  52837. * the directional falloff will start before cutting at angle which could be seen
  52838. * as outer angle.
  52839. */
  52840. get: function () {
  52841. return this._innerAngle;
  52842. },
  52843. /**
  52844. * Only used in gltf falloff mode, this defines the angle where
  52845. * the directional falloff will start before cutting at angle which could be seen
  52846. * as outer angle.
  52847. */
  52848. set: function (value) {
  52849. this._innerAngle = value;
  52850. this._computeAngleValues();
  52851. },
  52852. enumerable: true,
  52853. configurable: true
  52854. });
  52855. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  52856. /**
  52857. * Allows scaling the angle of the light for shadow generation only.
  52858. */
  52859. get: function () {
  52860. return this._shadowAngleScale;
  52861. },
  52862. /**
  52863. * Allows scaling the angle of the light for shadow generation only.
  52864. */
  52865. set: function (value) {
  52866. this._shadowAngleScale = value;
  52867. this.forceProjectionMatrixCompute();
  52868. },
  52869. enumerable: true,
  52870. configurable: true
  52871. });
  52872. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  52873. /**
  52874. * Allows reading the projecton texture
  52875. */
  52876. get: function () {
  52877. return this._projectionTextureMatrix;
  52878. },
  52879. enumerable: true,
  52880. configurable: true
  52881. });
  52882. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  52883. /**
  52884. * Gets the near clip of the Spotlight for texture projection.
  52885. */
  52886. get: function () {
  52887. return this._projectionTextureLightNear;
  52888. },
  52889. /**
  52890. * Sets the near clip of the Spotlight for texture projection.
  52891. */
  52892. set: function (value) {
  52893. this._projectionTextureLightNear = value;
  52894. this._projectionTextureProjectionLightDirty = true;
  52895. },
  52896. enumerable: true,
  52897. configurable: true
  52898. });
  52899. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  52900. /**
  52901. * Gets the far clip of the Spotlight for texture projection.
  52902. */
  52903. get: function () {
  52904. return this._projectionTextureLightFar;
  52905. },
  52906. /**
  52907. * Sets the far clip of the Spotlight for texture projection.
  52908. */
  52909. set: function (value) {
  52910. this._projectionTextureLightFar = value;
  52911. this._projectionTextureProjectionLightDirty = true;
  52912. },
  52913. enumerable: true,
  52914. configurable: true
  52915. });
  52916. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  52917. /**
  52918. * Gets the Up vector of the Spotlight for texture projection.
  52919. */
  52920. get: function () {
  52921. return this._projectionTextureUpDirection;
  52922. },
  52923. /**
  52924. * Sets the Up vector of the Spotlight for texture projection.
  52925. */
  52926. set: function (value) {
  52927. this._projectionTextureUpDirection = value;
  52928. this._projectionTextureProjectionLightDirty = true;
  52929. },
  52930. enumerable: true,
  52931. configurable: true
  52932. });
  52933. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  52934. /**
  52935. * Gets the projection texture of the light.
  52936. */
  52937. get: function () {
  52938. return this._projectionTexture;
  52939. },
  52940. /**
  52941. * Sets the projection texture of the light.
  52942. */
  52943. set: function (value) {
  52944. this._projectionTexture = value;
  52945. this._projectionTextureDirty = true;
  52946. },
  52947. enumerable: true,
  52948. configurable: true
  52949. });
  52950. /**
  52951. * Returns the string "SpotLight".
  52952. * @returns the class name
  52953. */
  52954. SpotLight.prototype.getClassName = function () {
  52955. return "SpotLight";
  52956. };
  52957. /**
  52958. * Returns the integer 2.
  52959. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52960. */
  52961. SpotLight.prototype.getTypeID = function () {
  52962. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  52963. };
  52964. /**
  52965. * Overrides the direction setter to recompute the projection texture view light Matrix.
  52966. */
  52967. SpotLight.prototype._setDirection = function (value) {
  52968. _super.prototype._setDirection.call(this, value);
  52969. this._projectionTextureViewLightDirty = true;
  52970. };
  52971. /**
  52972. * Overrides the position setter to recompute the projection texture view light Matrix.
  52973. */
  52974. SpotLight.prototype._setPosition = function (value) {
  52975. _super.prototype._setPosition.call(this, value);
  52976. this._projectionTextureViewLightDirty = true;
  52977. };
  52978. /**
  52979. * 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.
  52980. * Returns the SpotLight.
  52981. */
  52982. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52983. var activeCamera = this.getScene().activeCamera;
  52984. if (!activeCamera) {
  52985. return;
  52986. }
  52987. this._shadowAngleScale = this._shadowAngleScale || 1;
  52988. var angle = this._shadowAngleScale * this._angle;
  52989. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52990. };
  52991. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  52992. this._projectionTextureViewLightDirty = false;
  52993. this._projectionTextureDirty = true;
  52994. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  52995. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  52996. };
  52997. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  52998. this._projectionTextureProjectionLightDirty = false;
  52999. this._projectionTextureDirty = true;
  53000. var light_far = this.projectionTextureLightFar;
  53001. var light_near = this.projectionTextureLightNear;
  53002. var P = light_far / (light_far - light_near);
  53003. var Q = -P * light_near;
  53004. var S = 1.0 / Math.tan(this._angle / 2.0);
  53005. var A = 1.0;
  53006. 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);
  53007. };
  53008. /**
  53009. * Main function for light texture projection matrix computing.
  53010. */
  53011. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  53012. this._projectionTextureDirty = false;
  53013. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  53014. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  53015. };
  53016. SpotLight.prototype._buildUniformLayout = function () {
  53017. this._uniformBuffer.addUniform("vLightData", 4);
  53018. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53019. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53020. this._uniformBuffer.addUniform("vLightDirection", 3);
  53021. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53022. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53023. this._uniformBuffer.addUniform("depthValues", 2);
  53024. this._uniformBuffer.create();
  53025. };
  53026. SpotLight.prototype._computeAngleValues = function () {
  53027. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  53028. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  53029. };
  53030. /**
  53031. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  53032. * @param effect The effect to update
  53033. * @param lightIndex The index of the light in the effect to update
  53034. * @returns The spot light
  53035. */
  53036. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  53037. var normalizeDirection;
  53038. if (this.computeTransformedInformation()) {
  53039. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  53040. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  53041. }
  53042. else {
  53043. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  53044. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  53045. }
  53046. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  53047. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  53048. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53049. if (this._projectionTextureViewLightDirty) {
  53050. this._computeProjectionTextureViewLightMatrix();
  53051. }
  53052. if (this._projectionTextureProjectionLightDirty) {
  53053. this._computeProjectionTextureProjectionLightMatrix();
  53054. }
  53055. if (this._projectionTextureDirty) {
  53056. this._computeProjectionTextureMatrix();
  53057. }
  53058. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53059. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53060. }
  53061. return this;
  53062. };
  53063. /**
  53064. * Disposes the light and the associated resources.
  53065. */
  53066. SpotLight.prototype.dispose = function () {
  53067. _super.prototype.dispose.call(this);
  53068. if (this._projectionTexture) {
  53069. this._projectionTexture.dispose();
  53070. }
  53071. };
  53072. /**
  53073. * Prepares the list of defines specific to the light type.
  53074. * @param defines the list of defines
  53075. * @param lightIndex defines the index of the light for the effect
  53076. */
  53077. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53078. defines["SPOTLIGHT" + lightIndex] = true;
  53079. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53080. };
  53081. __decorate([
  53082. BABYLON.serialize()
  53083. ], SpotLight.prototype, "angle", null);
  53084. __decorate([
  53085. BABYLON.serialize()
  53086. ], SpotLight.prototype, "innerAngle", null);
  53087. __decorate([
  53088. BABYLON.serialize()
  53089. ], SpotLight.prototype, "shadowAngleScale", null);
  53090. __decorate([
  53091. BABYLON.serialize()
  53092. ], SpotLight.prototype, "exponent", void 0);
  53093. __decorate([
  53094. BABYLON.serialize()
  53095. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53096. __decorate([
  53097. BABYLON.serialize()
  53098. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53099. __decorate([
  53100. BABYLON.serialize()
  53101. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53102. __decorate([
  53103. BABYLON.serializeAsTexture("projectedLightTexture")
  53104. ], SpotLight.prototype, "_projectionTexture", void 0);
  53105. return SpotLight;
  53106. }(BABYLON.ShadowLight));
  53107. BABYLON.SpotLight = SpotLight;
  53108. })(BABYLON || (BABYLON = {}));
  53109. //# sourceMappingURL=babylon.spotLight.js.map
  53110. var BABYLON;
  53111. (function (BABYLON) {
  53112. /**
  53113. * Class used to override all child animations of a given target
  53114. */
  53115. var AnimationPropertiesOverride = /** @class */ (function () {
  53116. function AnimationPropertiesOverride() {
  53117. /**
  53118. * Gets or sets a value indicating if animation blending must be used
  53119. */
  53120. this.enableBlending = false;
  53121. /**
  53122. * Gets or sets the blending speed to use when enableBlending is true
  53123. */
  53124. this.blendingSpeed = 0.01;
  53125. /**
  53126. * Gets or sets the default loop mode to use
  53127. */
  53128. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53129. }
  53130. return AnimationPropertiesOverride;
  53131. }());
  53132. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53133. })(BABYLON || (BABYLON = {}));
  53134. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. /**
  53138. * Represents the range of an animation
  53139. */
  53140. var AnimationRange = /** @class */ (function () {
  53141. /**
  53142. * Initializes the range of an animation
  53143. * @param name The name of the animation range
  53144. * @param from The starting frame of the animation
  53145. * @param to The ending frame of the animation
  53146. */
  53147. function AnimationRange(
  53148. /**The name of the animation range**/
  53149. name,
  53150. /**The starting frame of the animation */
  53151. from,
  53152. /**The ending frame of the animation*/
  53153. to) {
  53154. this.name = name;
  53155. this.from = from;
  53156. this.to = to;
  53157. }
  53158. /**
  53159. * Makes a copy of the animation range
  53160. * @returns A copy of the animation range
  53161. */
  53162. AnimationRange.prototype.clone = function () {
  53163. return new AnimationRange(this.name, this.from, this.to);
  53164. };
  53165. return AnimationRange;
  53166. }());
  53167. BABYLON.AnimationRange = AnimationRange;
  53168. /**
  53169. * Composed of a frame, and an action function
  53170. */
  53171. var AnimationEvent = /** @class */ (function () {
  53172. /**
  53173. * Initializes the animation event
  53174. * @param frame The frame for which the event is triggered
  53175. * @param action The event to perform when triggered
  53176. * @param onlyOnce Specifies if the event should be triggered only once
  53177. */
  53178. function AnimationEvent(
  53179. /** The frame for which the event is triggered **/
  53180. frame,
  53181. /** The event to perform when triggered **/
  53182. action,
  53183. /** Specifies if the event should be triggered only once**/
  53184. onlyOnce) {
  53185. this.frame = frame;
  53186. this.action = action;
  53187. this.onlyOnce = onlyOnce;
  53188. /**
  53189. * Specifies if the animation event is done
  53190. */
  53191. this.isDone = false;
  53192. }
  53193. /** @hidden */
  53194. AnimationEvent.prototype._clone = function () {
  53195. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53196. };
  53197. return AnimationEvent;
  53198. }());
  53199. BABYLON.AnimationEvent = AnimationEvent;
  53200. /**
  53201. * A cursor which tracks a point on a path
  53202. */
  53203. var PathCursor = /** @class */ (function () {
  53204. /**
  53205. * Initializes the path cursor
  53206. * @param path The path to track
  53207. */
  53208. function PathCursor(path) {
  53209. this.path = path;
  53210. /**
  53211. * Stores path cursor callbacks for when an onchange event is triggered
  53212. */
  53213. this._onchange = new Array();
  53214. /**
  53215. * The value of the path cursor
  53216. */
  53217. this.value = 0;
  53218. /**
  53219. * The animation array of the path cursor
  53220. */
  53221. this.animations = new Array();
  53222. }
  53223. /**
  53224. * Gets the cursor point on the path
  53225. * @returns A point on the path cursor at the cursor location
  53226. */
  53227. PathCursor.prototype.getPoint = function () {
  53228. var point = this.path.getPointAtLengthPosition(this.value);
  53229. return new BABYLON.Vector3(point.x, 0, point.y);
  53230. };
  53231. /**
  53232. * Moves the cursor ahead by the step amount
  53233. * @param step The amount to move the cursor forward
  53234. * @returns This path cursor
  53235. */
  53236. PathCursor.prototype.moveAhead = function (step) {
  53237. if (step === void 0) { step = 0.002; }
  53238. this.move(step);
  53239. return this;
  53240. };
  53241. /**
  53242. * Moves the cursor behind by the step amount
  53243. * @param step The amount to move the cursor back
  53244. * @returns This path cursor
  53245. */
  53246. PathCursor.prototype.moveBack = function (step) {
  53247. if (step === void 0) { step = 0.002; }
  53248. this.move(-step);
  53249. return this;
  53250. };
  53251. /**
  53252. * Moves the cursor by the step amount
  53253. * If the step amount is greater than one, an exception is thrown
  53254. * @param step The amount to move the cursor
  53255. * @returns This path cursor
  53256. */
  53257. PathCursor.prototype.move = function (step) {
  53258. if (Math.abs(step) > 1) {
  53259. throw "step size should be less than 1.";
  53260. }
  53261. this.value += step;
  53262. this.ensureLimits();
  53263. this.raiseOnChange();
  53264. return this;
  53265. };
  53266. /**
  53267. * Ensures that the value is limited between zero and one
  53268. * @returns This path cursor
  53269. */
  53270. PathCursor.prototype.ensureLimits = function () {
  53271. while (this.value > 1) {
  53272. this.value -= 1;
  53273. }
  53274. while (this.value < 0) {
  53275. this.value += 1;
  53276. }
  53277. return this;
  53278. };
  53279. /**
  53280. * Runs onchange callbacks on change (used by the animation engine)
  53281. * @returns This path cursor
  53282. */
  53283. PathCursor.prototype.raiseOnChange = function () {
  53284. var _this = this;
  53285. this._onchange.forEach(function (f) { return f(_this); });
  53286. return this;
  53287. };
  53288. /**
  53289. * Executes a function on change
  53290. * @param f A path cursor onchange callback
  53291. * @returns This path cursor
  53292. */
  53293. PathCursor.prototype.onchange = function (f) {
  53294. this._onchange.push(f);
  53295. return this;
  53296. };
  53297. return PathCursor;
  53298. }());
  53299. BABYLON.PathCursor = PathCursor;
  53300. /**
  53301. * Enum for the animation key frame interpolation type
  53302. */
  53303. var AnimationKeyInterpolation;
  53304. (function (AnimationKeyInterpolation) {
  53305. /**
  53306. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  53307. */
  53308. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  53309. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  53310. /**
  53311. * Class used to store any kind of animation
  53312. */
  53313. var Animation = /** @class */ (function () {
  53314. /**
  53315. * Initializes the animation
  53316. * @param name Name of the animation
  53317. * @param targetProperty Property to animate
  53318. * @param framePerSecond The frames per second of the animation
  53319. * @param dataType The data type of the animation
  53320. * @param loopMode The loop mode of the animation
  53321. * @param enableBlendings Specifies if blending should be enabled
  53322. */
  53323. function Animation(
  53324. /**Name of the animation */
  53325. name,
  53326. /**Property to animate */
  53327. targetProperty,
  53328. /**The frames per second of the animation */
  53329. framePerSecond,
  53330. /**The data type of the animation */
  53331. dataType,
  53332. /**The loop mode of the animation */
  53333. loopMode,
  53334. /**Specifies if blending should be enabled */
  53335. enableBlending) {
  53336. this.name = name;
  53337. this.targetProperty = targetProperty;
  53338. this.framePerSecond = framePerSecond;
  53339. this.dataType = dataType;
  53340. this.loopMode = loopMode;
  53341. this.enableBlending = enableBlending;
  53342. /**
  53343. * @hidden Internal use only
  53344. */
  53345. this._runtimeAnimations = new Array();
  53346. /**
  53347. * The set of event that will be linked to this animation
  53348. */
  53349. this._events = new Array();
  53350. /**
  53351. * Stores the blending speed of the animation
  53352. */
  53353. this.blendingSpeed = 0.01;
  53354. /**
  53355. * Stores the animation ranges for the animation
  53356. */
  53357. this._ranges = {};
  53358. this.targetPropertyPath = targetProperty.split(".");
  53359. this.dataType = dataType;
  53360. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  53361. }
  53362. /**
  53363. * @hidden Internal use
  53364. */
  53365. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  53366. var dataType = undefined;
  53367. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  53368. dataType = Animation.ANIMATIONTYPE_FLOAT;
  53369. }
  53370. else if (from instanceof BABYLON.Quaternion) {
  53371. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  53372. }
  53373. else if (from instanceof BABYLON.Vector3) {
  53374. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  53375. }
  53376. else if (from instanceof BABYLON.Vector2) {
  53377. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  53378. }
  53379. else if (from instanceof BABYLON.Color3) {
  53380. dataType = Animation.ANIMATIONTYPE_COLOR3;
  53381. }
  53382. else if (from instanceof BABYLON.Size) {
  53383. dataType = Animation.ANIMATIONTYPE_SIZE;
  53384. }
  53385. if (dataType == undefined) {
  53386. return null;
  53387. }
  53388. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  53389. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  53390. animation.setKeys(keys);
  53391. if (easingFunction !== undefined) {
  53392. animation.setEasingFunction(easingFunction);
  53393. }
  53394. return animation;
  53395. };
  53396. /**
  53397. * Sets up an animation
  53398. * @param property The property to animate
  53399. * @param animationType The animation type to apply
  53400. * @param framePerSecond The frames per second of the animation
  53401. * @param easingFunction The easing function used in the animation
  53402. * @returns The created animation
  53403. */
  53404. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  53405. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  53406. animation.setEasingFunction(easingFunction);
  53407. return animation;
  53408. };
  53409. /**
  53410. * Create and start an animation on a node
  53411. * @param name defines the name of the global animation that will be run on all nodes
  53412. * @param node defines the root node where the animation will take place
  53413. * @param targetProperty defines property to animate
  53414. * @param framePerSecond defines the number of frame per second yo use
  53415. * @param totalFrame defines the number of frames in total
  53416. * @param from defines the initial value
  53417. * @param to defines the final value
  53418. * @param loopMode defines which loop mode you want to use (off by default)
  53419. * @param easingFunction defines the easing function to use (linear by default)
  53420. * @param onAnimationEnd defines the callback to call when animation end
  53421. * @returns the animatable created for this animation
  53422. */
  53423. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53424. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53425. if (!animation) {
  53426. return null;
  53427. }
  53428. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53429. };
  53430. /**
  53431. * Create and start an animation on a node and its descendants
  53432. * @param name defines the name of the global animation that will be run on all nodes
  53433. * @param node defines the root node where the animation will take place
  53434. * @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
  53435. * @param targetProperty defines property to animate
  53436. * @param framePerSecond defines the number of frame per second to use
  53437. * @param totalFrame defines the number of frames in total
  53438. * @param from defines the initial value
  53439. * @param to defines the final value
  53440. * @param loopMode defines which loop mode you want to use (off by default)
  53441. * @param easingFunction defines the easing function to use (linear by default)
  53442. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  53443. * @returns the list of animatables created for all nodes
  53444. * @example https://www.babylonjs-playground.com/#MH0VLI
  53445. */
  53446. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53447. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53448. if (!animation) {
  53449. return null;
  53450. }
  53451. var scene = node.getScene();
  53452. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53453. };
  53454. /**
  53455. * Creates a new animation, merges it with the existing animations and starts it
  53456. * @param name Name of the animation
  53457. * @param node Node which contains the scene that begins the animations
  53458. * @param targetProperty Specifies which property to animate
  53459. * @param framePerSecond The frames per second of the animation
  53460. * @param totalFrame The total number of frames
  53461. * @param from The frame at the beginning of the animation
  53462. * @param to The frame at the end of the animation
  53463. * @param loopMode Specifies the loop mode of the animation
  53464. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  53465. * @param onAnimationEnd Callback to run once the animation is complete
  53466. * @returns Nullable animation
  53467. */
  53468. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53469. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53470. if (!animation) {
  53471. return null;
  53472. }
  53473. node.animations.push(animation);
  53474. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53475. };
  53476. /**
  53477. * Transition property of an host to the target Value
  53478. * @param property The property to transition
  53479. * @param targetValue The target Value of the property
  53480. * @param host The object where the property to animate belongs
  53481. * @param scene Scene used to run the animation
  53482. * @param frameRate Framerate (in frame/s) to use
  53483. * @param transition The transition type we want to use
  53484. * @param duration The duration of the animation, in milliseconds
  53485. * @param onAnimationEnd Callback trigger at the end of the animation
  53486. * @returns Nullable animation
  53487. */
  53488. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  53489. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  53490. if (duration <= 0) {
  53491. host[property] = targetValue;
  53492. if (onAnimationEnd) {
  53493. onAnimationEnd();
  53494. }
  53495. return null;
  53496. }
  53497. var endFrame = frameRate * (duration / 1000);
  53498. transition.setKeys([{
  53499. frame: 0,
  53500. value: host[property].clone ? host[property].clone() : host[property]
  53501. },
  53502. {
  53503. frame: endFrame,
  53504. value: targetValue
  53505. }]);
  53506. if (!host.animations) {
  53507. host.animations = [];
  53508. }
  53509. host.animations.push(transition);
  53510. var animation = scene.beginAnimation(host, 0, endFrame, false);
  53511. animation.onAnimationEnd = onAnimationEnd;
  53512. return animation;
  53513. };
  53514. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  53515. /**
  53516. * Return the array of runtime animations currently using this animation
  53517. */
  53518. get: function () {
  53519. return this._runtimeAnimations;
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  53525. /**
  53526. * Specifies if any of the runtime animations are currently running
  53527. */
  53528. get: function () {
  53529. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  53530. var runtimeAnimation = _a[_i];
  53531. if (!runtimeAnimation.isStopped) {
  53532. return true;
  53533. }
  53534. }
  53535. return false;
  53536. },
  53537. enumerable: true,
  53538. configurable: true
  53539. });
  53540. // Methods
  53541. /**
  53542. * Converts the animation to a string
  53543. * @param fullDetails support for multiple levels of logging within scene loading
  53544. * @returns String form of the animation
  53545. */
  53546. Animation.prototype.toString = function (fullDetails) {
  53547. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  53548. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  53549. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  53550. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53551. if (fullDetails) {
  53552. ret += ", Ranges: {";
  53553. var first = true;
  53554. for (var name in this._ranges) {
  53555. if (first) {
  53556. ret += ", ";
  53557. first = false;
  53558. }
  53559. ret += name;
  53560. }
  53561. ret += "}";
  53562. }
  53563. return ret;
  53564. };
  53565. /**
  53566. * Add an event to this animation
  53567. * @param event Event to add
  53568. */
  53569. Animation.prototype.addEvent = function (event) {
  53570. this._events.push(event);
  53571. };
  53572. /**
  53573. * Remove all events found at the given frame
  53574. * @param frame The frame to remove events from
  53575. */
  53576. Animation.prototype.removeEvents = function (frame) {
  53577. for (var index = 0; index < this._events.length; index++) {
  53578. if (this._events[index].frame === frame) {
  53579. this._events.splice(index, 1);
  53580. index--;
  53581. }
  53582. }
  53583. };
  53584. /**
  53585. * Retrieves all the events from the animation
  53586. * @returns Events from the animation
  53587. */
  53588. Animation.prototype.getEvents = function () {
  53589. return this._events;
  53590. };
  53591. /**
  53592. * Creates an animation range
  53593. * @param name Name of the animation range
  53594. * @param from Starting frame of the animation range
  53595. * @param to Ending frame of the animation
  53596. */
  53597. Animation.prototype.createRange = function (name, from, to) {
  53598. // check name not already in use; could happen for bones after serialized
  53599. if (!this._ranges[name]) {
  53600. this._ranges[name] = new AnimationRange(name, from, to);
  53601. }
  53602. };
  53603. /**
  53604. * Deletes an animation range by name
  53605. * @param name Name of the animation range to delete
  53606. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  53607. */
  53608. Animation.prototype.deleteRange = function (name, deleteFrames) {
  53609. if (deleteFrames === void 0) { deleteFrames = true; }
  53610. var range = this._ranges[name];
  53611. if (!range) {
  53612. return;
  53613. }
  53614. if (deleteFrames) {
  53615. var from = range.from;
  53616. var to = range.to;
  53617. // this loop MUST go high to low for multiple splices to work
  53618. for (var key = this._keys.length - 1; key >= 0; key--) {
  53619. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  53620. this._keys.splice(key, 1);
  53621. }
  53622. }
  53623. }
  53624. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  53625. };
  53626. /**
  53627. * Gets the animation range by name, or null if not defined
  53628. * @param name Name of the animation range
  53629. * @returns Nullable animation range
  53630. */
  53631. Animation.prototype.getRange = function (name) {
  53632. return this._ranges[name];
  53633. };
  53634. /**
  53635. * Gets the key frames from the animation
  53636. * @returns The key frames of the animation
  53637. */
  53638. Animation.prototype.getKeys = function () {
  53639. return this._keys;
  53640. };
  53641. /**
  53642. * Gets the highest frame rate of the animation
  53643. * @returns Highest frame rate of the animation
  53644. */
  53645. Animation.prototype.getHighestFrame = function () {
  53646. var ret = 0;
  53647. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  53648. if (ret < this._keys[key].frame) {
  53649. ret = this._keys[key].frame;
  53650. }
  53651. }
  53652. return ret;
  53653. };
  53654. /**
  53655. * Gets the easing function of the animation
  53656. * @returns Easing function of the animation
  53657. */
  53658. Animation.prototype.getEasingFunction = function () {
  53659. return this._easingFunction;
  53660. };
  53661. /**
  53662. * Sets the easing function of the animation
  53663. * @param easingFunction A custom mathematical formula for animation
  53664. */
  53665. Animation.prototype.setEasingFunction = function (easingFunction) {
  53666. this._easingFunction = easingFunction;
  53667. };
  53668. /**
  53669. * Interpolates a scalar linearly
  53670. * @param startValue Start value of the animation curve
  53671. * @param endValue End value of the animation curve
  53672. * @param gradient Scalar amount to interpolate
  53673. * @returns Interpolated scalar value
  53674. */
  53675. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  53676. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  53677. };
  53678. /**
  53679. * Interpolates a scalar cubically
  53680. * @param startValue Start value of the animation curve
  53681. * @param outTangent End tangent of the animation
  53682. * @param endValue End value of the animation curve
  53683. * @param inTangent Start tangent of the animation curve
  53684. * @param gradient Scalar amount to interpolate
  53685. * @returns Interpolated scalar value
  53686. */
  53687. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53688. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53689. };
  53690. /**
  53691. * Interpolates a quaternion using a spherical linear interpolation
  53692. * @param startValue Start value of the animation curve
  53693. * @param endValue End value of the animation curve
  53694. * @param gradient Scalar amount to interpolate
  53695. * @returns Interpolated quaternion value
  53696. */
  53697. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  53698. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  53699. };
  53700. /**
  53701. * Interpolates a quaternion cubically
  53702. * @param startValue Start value of the animation curve
  53703. * @param outTangent End tangent of the animation curve
  53704. * @param endValue End value of the animation curve
  53705. * @param inTangent Start tangent of the animation curve
  53706. * @param gradient Scalar amount to interpolate
  53707. * @returns Interpolated quaternion value
  53708. */
  53709. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53710. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  53711. };
  53712. /**
  53713. * Interpolates a Vector3 linearl
  53714. * @param startValue Start value of the animation curve
  53715. * @param endValue End value of the animation curve
  53716. * @param gradient Scalar amount to interpolate
  53717. * @returns Interpolated scalar value
  53718. */
  53719. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  53720. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  53721. };
  53722. /**
  53723. * Interpolates a Vector3 cubically
  53724. * @param startValue Start value of the animation curve
  53725. * @param outTangent End tangent of the animation
  53726. * @param endValue End value of the animation curve
  53727. * @param inTangent Start tangent of the animation curve
  53728. * @param gradient Scalar amount to interpolate
  53729. * @returns InterpolatedVector3 value
  53730. */
  53731. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53732. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53733. };
  53734. /**
  53735. * Interpolates a Vector2 linearly
  53736. * @param startValue Start value of the animation curve
  53737. * @param endValue End value of the animation curve
  53738. * @param gradient Scalar amount to interpolate
  53739. * @returns Interpolated Vector2 value
  53740. */
  53741. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  53742. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  53743. };
  53744. /**
  53745. * Interpolates a Vector2 cubically
  53746. * @param startValue Start value of the animation curve
  53747. * @param outTangent End tangent of the animation
  53748. * @param endValue End value of the animation curve
  53749. * @param inTangent Start tangent of the animation curve
  53750. * @param gradient Scalar amount to interpolate
  53751. * @returns Interpolated Vector2 value
  53752. */
  53753. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53754. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53755. };
  53756. /**
  53757. * Interpolates a size linearly
  53758. * @param startValue Start value of the animation curve
  53759. * @param endValue End value of the animation curve
  53760. * @param gradient Scalar amount to interpolate
  53761. * @returns Interpolated Size value
  53762. */
  53763. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  53764. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  53765. };
  53766. /**
  53767. * Interpolates a Color3 linearly
  53768. * @param startValue Start value of the animation curve
  53769. * @param endValue End value of the animation curve
  53770. * @param gradient Scalar amount to interpolate
  53771. * @returns Interpolated Color3 value
  53772. */
  53773. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  53774. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  53775. };
  53776. /**
  53777. * @hidden Internal use only
  53778. */
  53779. Animation.prototype._getKeyValue = function (value) {
  53780. if (typeof value === "function") {
  53781. return value();
  53782. }
  53783. return value;
  53784. };
  53785. /**
  53786. * @hidden Internal use only
  53787. */
  53788. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  53789. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  53790. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  53791. }
  53792. var keys = this.getKeys();
  53793. // Try to get a hash to find the right key
  53794. 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));
  53795. if (keys[startKeyIndex].frame >= currentFrame) {
  53796. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  53797. startKeyIndex--;
  53798. }
  53799. }
  53800. for (var key = startKeyIndex; key < keys.length; key++) {
  53801. var endKey = keys[key + 1];
  53802. if (endKey.frame >= currentFrame) {
  53803. var startKey = keys[key];
  53804. var startValue = this._getKeyValue(startKey.value);
  53805. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  53806. return startValue;
  53807. }
  53808. var endValue = this._getKeyValue(endKey.value);
  53809. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  53810. var frameDelta = endKey.frame - startKey.frame;
  53811. // gradient : percent of currentFrame between the frame inf and the frame sup
  53812. var gradient = (currentFrame - startKey.frame) / frameDelta;
  53813. // check for easingFunction and correction of gradient
  53814. var easingFunction = this.getEasingFunction();
  53815. if (easingFunction != null) {
  53816. gradient = easingFunction.ease(gradient);
  53817. }
  53818. switch (this.dataType) {
  53819. // Float
  53820. case Animation.ANIMATIONTYPE_FLOAT:
  53821. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  53822. switch (loopMode) {
  53823. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53824. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53825. return floatValue;
  53826. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53827. return offsetValue * repeatCount + floatValue;
  53828. }
  53829. break;
  53830. // Quaternion
  53831. case Animation.ANIMATIONTYPE_QUATERNION:
  53832. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  53833. switch (loopMode) {
  53834. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53835. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53836. return quatValue;
  53837. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53838. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  53839. }
  53840. return quatValue;
  53841. // Vector3
  53842. case Animation.ANIMATIONTYPE_VECTOR3:
  53843. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  53844. switch (loopMode) {
  53845. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53846. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53847. return vec3Value;
  53848. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53849. return vec3Value.add(offsetValue.scale(repeatCount));
  53850. }
  53851. // Vector2
  53852. case Animation.ANIMATIONTYPE_VECTOR2:
  53853. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  53854. switch (loopMode) {
  53855. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53856. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53857. return vec2Value;
  53858. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53859. return vec2Value.add(offsetValue.scale(repeatCount));
  53860. }
  53861. // Size
  53862. case Animation.ANIMATIONTYPE_SIZE:
  53863. switch (loopMode) {
  53864. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53865. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53866. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  53867. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53868. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53869. }
  53870. // Color3
  53871. case Animation.ANIMATIONTYPE_COLOR3:
  53872. switch (loopMode) {
  53873. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53874. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53875. return this.color3InterpolateFunction(startValue, endValue, gradient);
  53876. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53877. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53878. }
  53879. // Matrix
  53880. case Animation.ANIMATIONTYPE_MATRIX:
  53881. switch (loopMode) {
  53882. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53883. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53884. if (Animation.AllowMatricesInterpolation) {
  53885. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  53886. }
  53887. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53888. return startValue;
  53889. }
  53890. default:
  53891. break;
  53892. }
  53893. break;
  53894. }
  53895. }
  53896. return this._getKeyValue(keys[keys.length - 1].value);
  53897. };
  53898. /**
  53899. * Defines the function to use to interpolate matrices
  53900. * @param startValue defines the start matrix
  53901. * @param endValue defines the end matrix
  53902. * @param gradient defines the gradient between both matrices
  53903. * @param result defines an optional target matrix where to store the interpolation
  53904. * @returns the interpolated matrix
  53905. */
  53906. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  53907. if (Animation.AllowMatrixDecomposeForInterpolation) {
  53908. if (result) {
  53909. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  53910. return result;
  53911. }
  53912. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  53913. }
  53914. if (result) {
  53915. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  53916. return result;
  53917. }
  53918. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  53919. };
  53920. /**
  53921. * Makes a copy of the animation
  53922. * @returns Cloned animation
  53923. */
  53924. Animation.prototype.clone = function () {
  53925. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  53926. clone.enableBlending = this.enableBlending;
  53927. clone.blendingSpeed = this.blendingSpeed;
  53928. if (this._keys) {
  53929. clone.setKeys(this._keys);
  53930. }
  53931. if (this._ranges) {
  53932. clone._ranges = {};
  53933. for (var name in this._ranges) {
  53934. var range = this._ranges[name];
  53935. if (!range) {
  53936. continue;
  53937. }
  53938. clone._ranges[name] = range.clone();
  53939. }
  53940. }
  53941. return clone;
  53942. };
  53943. /**
  53944. * Sets the key frames of the animation
  53945. * @param values The animation key frames to set
  53946. */
  53947. Animation.prototype.setKeys = function (values) {
  53948. this._keys = values.slice(0);
  53949. };
  53950. /**
  53951. * Serializes the animation to an object
  53952. * @returns Serialized object
  53953. */
  53954. Animation.prototype.serialize = function () {
  53955. var serializationObject = {};
  53956. serializationObject.name = this.name;
  53957. serializationObject.property = this.targetProperty;
  53958. serializationObject.framePerSecond = this.framePerSecond;
  53959. serializationObject.dataType = this.dataType;
  53960. serializationObject.loopBehavior = this.loopMode;
  53961. serializationObject.enableBlending = this.enableBlending;
  53962. serializationObject.blendingSpeed = this.blendingSpeed;
  53963. var dataType = this.dataType;
  53964. serializationObject.keys = [];
  53965. var keys = this.getKeys();
  53966. for (var index = 0; index < keys.length; index++) {
  53967. var animationKey = keys[index];
  53968. var key = {};
  53969. key.frame = animationKey.frame;
  53970. switch (dataType) {
  53971. case Animation.ANIMATIONTYPE_FLOAT:
  53972. key.values = [animationKey.value];
  53973. break;
  53974. case Animation.ANIMATIONTYPE_QUATERNION:
  53975. case Animation.ANIMATIONTYPE_MATRIX:
  53976. case Animation.ANIMATIONTYPE_VECTOR3:
  53977. case Animation.ANIMATIONTYPE_COLOR3:
  53978. key.values = animationKey.value.asArray();
  53979. break;
  53980. }
  53981. serializationObject.keys.push(key);
  53982. }
  53983. serializationObject.ranges = [];
  53984. for (var name in this._ranges) {
  53985. var source = this._ranges[name];
  53986. if (!source) {
  53987. continue;
  53988. }
  53989. var range = {};
  53990. range.name = name;
  53991. range.from = source.from;
  53992. range.to = source.to;
  53993. serializationObject.ranges.push(range);
  53994. }
  53995. return serializationObject;
  53996. };
  53997. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  53998. /**
  53999. * Get the float animation type
  54000. */
  54001. get: function () {
  54002. return Animation._ANIMATIONTYPE_FLOAT;
  54003. },
  54004. enumerable: true,
  54005. configurable: true
  54006. });
  54007. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  54008. /**
  54009. * Get the Vector3 animation type
  54010. */
  54011. get: function () {
  54012. return Animation._ANIMATIONTYPE_VECTOR3;
  54013. },
  54014. enumerable: true,
  54015. configurable: true
  54016. });
  54017. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  54018. /**
  54019. * Get the Vector2 animation type
  54020. */
  54021. get: function () {
  54022. return Animation._ANIMATIONTYPE_VECTOR2;
  54023. },
  54024. enumerable: true,
  54025. configurable: true
  54026. });
  54027. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  54028. /**
  54029. * Get the Size animation type
  54030. */
  54031. get: function () {
  54032. return Animation._ANIMATIONTYPE_SIZE;
  54033. },
  54034. enumerable: true,
  54035. configurable: true
  54036. });
  54037. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  54038. /**
  54039. * Get the Quaternion animation type
  54040. */
  54041. get: function () {
  54042. return Animation._ANIMATIONTYPE_QUATERNION;
  54043. },
  54044. enumerable: true,
  54045. configurable: true
  54046. });
  54047. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  54048. /**
  54049. * Get the Matrix animation type
  54050. */
  54051. get: function () {
  54052. return Animation._ANIMATIONTYPE_MATRIX;
  54053. },
  54054. enumerable: true,
  54055. configurable: true
  54056. });
  54057. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54058. /**
  54059. * Get the Color3 animation type
  54060. */
  54061. get: function () {
  54062. return Animation._ANIMATIONTYPE_COLOR3;
  54063. },
  54064. enumerable: true,
  54065. configurable: true
  54066. });
  54067. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54068. /**
  54069. * Get the Relative Loop Mode
  54070. */
  54071. get: function () {
  54072. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54073. },
  54074. enumerable: true,
  54075. configurable: true
  54076. });
  54077. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54078. /**
  54079. * Get the Cycle Loop Mode
  54080. */
  54081. get: function () {
  54082. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54083. },
  54084. enumerable: true,
  54085. configurable: true
  54086. });
  54087. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54088. /**
  54089. * Get the Constant Loop Mode
  54090. */
  54091. get: function () {
  54092. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54093. },
  54094. enumerable: true,
  54095. configurable: true
  54096. });
  54097. /** @hidden */
  54098. Animation._UniversalLerp = function (left, right, amount) {
  54099. var constructor = left.constructor;
  54100. if (constructor.Lerp) { // Lerp supported
  54101. return constructor.Lerp(left, right, amount);
  54102. }
  54103. else if (constructor.Slerp) { // Slerp supported
  54104. return constructor.Slerp(left, right, amount);
  54105. }
  54106. else if (left.toFixed) { // Number
  54107. return left * (1.0 - amount) + amount * right;
  54108. }
  54109. else { // Blending not supported
  54110. return right;
  54111. }
  54112. };
  54113. /**
  54114. * Parses an animation object and creates an animation
  54115. * @param parsedAnimation Parsed animation object
  54116. * @returns Animation object
  54117. */
  54118. Animation.Parse = function (parsedAnimation) {
  54119. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54120. var dataType = parsedAnimation.dataType;
  54121. var keys = [];
  54122. var data;
  54123. var index;
  54124. if (parsedAnimation.enableBlending) {
  54125. animation.enableBlending = parsedAnimation.enableBlending;
  54126. }
  54127. if (parsedAnimation.blendingSpeed) {
  54128. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54129. }
  54130. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54131. var key = parsedAnimation.keys[index];
  54132. var inTangent;
  54133. var outTangent;
  54134. switch (dataType) {
  54135. case Animation.ANIMATIONTYPE_FLOAT:
  54136. data = key.values[0];
  54137. if (key.values.length >= 1) {
  54138. inTangent = key.values[1];
  54139. }
  54140. if (key.values.length >= 2) {
  54141. outTangent = key.values[2];
  54142. }
  54143. break;
  54144. case Animation.ANIMATIONTYPE_QUATERNION:
  54145. data = BABYLON.Quaternion.FromArray(key.values);
  54146. if (key.values.length >= 8) {
  54147. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54148. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54149. inTangent = _inTangent;
  54150. }
  54151. }
  54152. if (key.values.length >= 12) {
  54153. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54154. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54155. outTangent = _outTangent;
  54156. }
  54157. }
  54158. break;
  54159. case Animation.ANIMATIONTYPE_MATRIX:
  54160. data = BABYLON.Matrix.FromArray(key.values);
  54161. break;
  54162. case Animation.ANIMATIONTYPE_COLOR3:
  54163. data = BABYLON.Color3.FromArray(key.values);
  54164. break;
  54165. case Animation.ANIMATIONTYPE_VECTOR3:
  54166. default:
  54167. data = BABYLON.Vector3.FromArray(key.values);
  54168. break;
  54169. }
  54170. var keyData = {};
  54171. keyData.frame = key.frame;
  54172. keyData.value = data;
  54173. if (inTangent != undefined) {
  54174. keyData.inTangent = inTangent;
  54175. }
  54176. if (outTangent != undefined) {
  54177. keyData.outTangent = outTangent;
  54178. }
  54179. keys.push(keyData);
  54180. }
  54181. animation.setKeys(keys);
  54182. if (parsedAnimation.ranges) {
  54183. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54184. data = parsedAnimation.ranges[index];
  54185. animation.createRange(data.name, data.from, data.to);
  54186. }
  54187. }
  54188. return animation;
  54189. };
  54190. /**
  54191. * Appends the serialized animations from the source animations
  54192. * @param source Source containing the animations
  54193. * @param destination Target to store the animations
  54194. */
  54195. Animation.AppendSerializedAnimations = function (source, destination) {
  54196. if (source.animations) {
  54197. destination.animations = [];
  54198. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54199. var animation = source.animations[animationIndex];
  54200. destination.animations.push(animation.serialize());
  54201. }
  54202. }
  54203. };
  54204. /**
  54205. * Use matrix interpolation instead of using direct key value when animating matrices
  54206. */
  54207. Animation.AllowMatricesInterpolation = false;
  54208. /**
  54209. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54210. */
  54211. Animation.AllowMatrixDecomposeForInterpolation = true;
  54212. // Statics
  54213. /**
  54214. * Float animation type
  54215. */
  54216. Animation._ANIMATIONTYPE_FLOAT = 0;
  54217. /**
  54218. * Vector3 animation type
  54219. */
  54220. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54221. /**
  54222. * Quaternion animation type
  54223. */
  54224. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54225. /**
  54226. * Matrix animation type
  54227. */
  54228. Animation._ANIMATIONTYPE_MATRIX = 3;
  54229. /**
  54230. * Color3 animation type
  54231. */
  54232. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54233. /**
  54234. * Vector2 animation type
  54235. */
  54236. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54237. /**
  54238. * Size animation type
  54239. */
  54240. Animation._ANIMATIONTYPE_SIZE = 6;
  54241. /**
  54242. * Relative Loop Mode
  54243. */
  54244. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54245. /**
  54246. * Cycle Loop Mode
  54247. */
  54248. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54249. /**
  54250. * Constant Loop Mode
  54251. */
  54252. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54253. return Animation;
  54254. }());
  54255. BABYLON.Animation = Animation;
  54256. })(BABYLON || (BABYLON = {}));
  54257. //# sourceMappingURL=babylon.animation.js.map
  54258. var BABYLON;
  54259. (function (BABYLON) {
  54260. /**
  54261. * This class defines the direct association between an animation and a target
  54262. */
  54263. var TargetedAnimation = /** @class */ (function () {
  54264. function TargetedAnimation() {
  54265. }
  54266. return TargetedAnimation;
  54267. }());
  54268. BABYLON.TargetedAnimation = TargetedAnimation;
  54269. /**
  54270. * Use this class to create coordinated animations on multiple targets
  54271. */
  54272. var AnimationGroup = /** @class */ (function () {
  54273. /**
  54274. * Instantiates a new Animation Group.
  54275. * This helps managing several animations at once.
  54276. * @see http://doc.babylonjs.com/how_to/group
  54277. * @param name Defines the name of the group
  54278. * @param scene Defines the scene the group belongs to
  54279. */
  54280. function AnimationGroup(
  54281. /** The name of the animation group */
  54282. name, scene) {
  54283. if (scene === void 0) { scene = null; }
  54284. this.name = name;
  54285. this._targetedAnimations = new Array();
  54286. this._animatables = new Array();
  54287. this._from = Number.MAX_VALUE;
  54288. this._to = -Number.MAX_VALUE;
  54289. this._speedRatio = 1;
  54290. /**
  54291. * This observable will notify when one animation have ended.
  54292. */
  54293. this.onAnimationEndObservable = new BABYLON.Observable();
  54294. /**
  54295. * This observable will notify when all animations have ended.
  54296. */
  54297. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  54298. /**
  54299. * This observable will notify when all animations have paused.
  54300. */
  54301. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  54302. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54303. this._scene.animationGroups.push(this);
  54304. }
  54305. Object.defineProperty(AnimationGroup.prototype, "from", {
  54306. /**
  54307. * Gets the first frame
  54308. */
  54309. get: function () {
  54310. return this._from;
  54311. },
  54312. enumerable: true,
  54313. configurable: true
  54314. });
  54315. Object.defineProperty(AnimationGroup.prototype, "to", {
  54316. /**
  54317. * Gets the last frame
  54318. */
  54319. get: function () {
  54320. return this._to;
  54321. },
  54322. enumerable: true,
  54323. configurable: true
  54324. });
  54325. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  54326. /**
  54327. * Define if the animations are started
  54328. */
  54329. get: function () {
  54330. return this._isStarted;
  54331. },
  54332. enumerable: true,
  54333. configurable: true
  54334. });
  54335. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  54336. /**
  54337. * Gets or sets the speed ratio to use for all animations
  54338. */
  54339. get: function () {
  54340. return this._speedRatio;
  54341. },
  54342. /**
  54343. * Gets or sets the speed ratio to use for all animations
  54344. */
  54345. set: function (value) {
  54346. if (this._speedRatio === value) {
  54347. return;
  54348. }
  54349. this._speedRatio = value;
  54350. for (var index = 0; index < this._animatables.length; index++) {
  54351. var animatable = this._animatables[index];
  54352. animatable.speedRatio = this._speedRatio;
  54353. }
  54354. },
  54355. enumerable: true,
  54356. configurable: true
  54357. });
  54358. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  54359. /**
  54360. * Gets the targeted animations for this animation group
  54361. */
  54362. get: function () {
  54363. return this._targetedAnimations;
  54364. },
  54365. enumerable: true,
  54366. configurable: true
  54367. });
  54368. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  54369. /**
  54370. * returning the list of animatables controlled by this animation group.
  54371. */
  54372. get: function () {
  54373. return this._animatables;
  54374. },
  54375. enumerable: true,
  54376. configurable: true
  54377. });
  54378. /**
  54379. * Add an animation (with its target) in the group
  54380. * @param animation defines the animation we want to add
  54381. * @param target defines the target of the animation
  54382. * @returns the TargetedAnimation object
  54383. */
  54384. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  54385. var targetedAnimation = {
  54386. animation: animation,
  54387. target: target
  54388. };
  54389. var keys = animation.getKeys();
  54390. if (this._from > keys[0].frame) {
  54391. this._from = keys[0].frame;
  54392. }
  54393. if (this._to < keys[keys.length - 1].frame) {
  54394. this._to = keys[keys.length - 1].frame;
  54395. }
  54396. this._targetedAnimations.push(targetedAnimation);
  54397. return targetedAnimation;
  54398. };
  54399. /**
  54400. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  54401. * It can add constant keys at begin or end
  54402. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  54403. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  54404. * @returns the animation group
  54405. */
  54406. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  54407. if (beginFrame === void 0) { beginFrame = null; }
  54408. if (endFrame === void 0) { endFrame = null; }
  54409. if (beginFrame == null) {
  54410. beginFrame = this._from;
  54411. }
  54412. if (endFrame == null) {
  54413. endFrame = this._to;
  54414. }
  54415. for (var index = 0; index < this._targetedAnimations.length; index++) {
  54416. var targetedAnimation = this._targetedAnimations[index];
  54417. var keys = targetedAnimation.animation.getKeys();
  54418. var startKey = keys[0];
  54419. var endKey = keys[keys.length - 1];
  54420. if (startKey.frame > beginFrame) {
  54421. var newKey = {
  54422. frame: beginFrame,
  54423. value: startKey.value,
  54424. inTangent: startKey.inTangent,
  54425. outTangent: startKey.outTangent,
  54426. interpolation: startKey.interpolation
  54427. };
  54428. keys.splice(0, 0, newKey);
  54429. }
  54430. if (endKey.frame < endFrame) {
  54431. var newKey = {
  54432. frame: endFrame,
  54433. value: endKey.value,
  54434. inTangent: endKey.outTangent,
  54435. outTangent: endKey.outTangent,
  54436. interpolation: endKey.interpolation
  54437. };
  54438. keys.push(newKey);
  54439. }
  54440. }
  54441. this._from = beginFrame;
  54442. this._to = endFrame;
  54443. return this;
  54444. };
  54445. /**
  54446. * Start all animations on given targets
  54447. * @param loop defines if animations must loop
  54448. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  54449. * @param from defines the from key (optional)
  54450. * @param to defines the to key (optional)
  54451. * @returns the current animation group
  54452. */
  54453. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  54454. var _this = this;
  54455. if (loop === void 0) { loop = false; }
  54456. if (speedRatio === void 0) { speedRatio = 1; }
  54457. if (this._isStarted || this._targetedAnimations.length === 0) {
  54458. return this;
  54459. }
  54460. var _loop_1 = function (targetedAnimation) {
  54461. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  54462. animatable.onAnimationEnd = function () {
  54463. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  54464. _this._checkAnimationGroupEnded(animatable);
  54465. };
  54466. this_1._animatables.push(animatable);
  54467. };
  54468. var this_1 = this;
  54469. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  54470. var targetedAnimation = _a[_i];
  54471. _loop_1(targetedAnimation);
  54472. }
  54473. this._speedRatio = speedRatio;
  54474. this._isStarted = true;
  54475. return this;
  54476. };
  54477. /**
  54478. * Pause all animations
  54479. * @returns the animation group
  54480. */
  54481. AnimationGroup.prototype.pause = function () {
  54482. if (!this._isStarted) {
  54483. return this;
  54484. }
  54485. for (var index = 0; index < this._animatables.length; index++) {
  54486. var animatable = this._animatables[index];
  54487. animatable.pause();
  54488. }
  54489. this.onAnimationGroupPauseObservable.notifyObservers(this);
  54490. return this;
  54491. };
  54492. /**
  54493. * Play all animations to initial state
  54494. * This function will start() the animations if they were not started or will restart() them if they were paused
  54495. * @param loop defines if animations must loop
  54496. * @returns the animation group
  54497. */
  54498. AnimationGroup.prototype.play = function (loop) {
  54499. // only if all animatables are ready and exist
  54500. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  54501. if (loop !== undefined) {
  54502. for (var index = 0; index < this._animatables.length; index++) {
  54503. var animatable = this._animatables[index];
  54504. animatable.loopAnimation = loop;
  54505. }
  54506. }
  54507. this.restart();
  54508. }
  54509. else {
  54510. this.stop();
  54511. this.start(loop, this._speedRatio);
  54512. }
  54513. return this;
  54514. };
  54515. /**
  54516. * Reset all animations to initial state
  54517. * @returns the animation group
  54518. */
  54519. AnimationGroup.prototype.reset = function () {
  54520. if (!this._isStarted) {
  54521. return this;
  54522. }
  54523. for (var index = 0; index < this._animatables.length; index++) {
  54524. var animatable = this._animatables[index];
  54525. animatable.reset();
  54526. }
  54527. return this;
  54528. };
  54529. /**
  54530. * Restart animations from key 0
  54531. * @returns the animation group
  54532. */
  54533. AnimationGroup.prototype.restart = function () {
  54534. if (!this._isStarted) {
  54535. return this;
  54536. }
  54537. for (var index = 0; index < this._animatables.length; index++) {
  54538. var animatable = this._animatables[index];
  54539. animatable.restart();
  54540. }
  54541. return this;
  54542. };
  54543. /**
  54544. * Stop all animations
  54545. * @returns the animation group
  54546. */
  54547. AnimationGroup.prototype.stop = function () {
  54548. if (!this._isStarted) {
  54549. return this;
  54550. }
  54551. var list = this._animatables.slice();
  54552. for (var index = 0; index < list.length; index++) {
  54553. list[index].stop();
  54554. }
  54555. this._isStarted = false;
  54556. return this;
  54557. };
  54558. /**
  54559. * Set animation weight for all animatables
  54560. * @param weight defines the weight to use
  54561. * @return the animationGroup
  54562. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54563. */
  54564. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  54565. for (var index = 0; index < this._animatables.length; index++) {
  54566. var animatable = this._animatables[index];
  54567. animatable.weight = weight;
  54568. }
  54569. return this;
  54570. };
  54571. /**
  54572. * Synchronize and normalize all animatables with a source animatable
  54573. * @param root defines the root animatable to synchronize with
  54574. * @return the animationGroup
  54575. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54576. */
  54577. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  54578. for (var index = 0; index < this._animatables.length; index++) {
  54579. var animatable = this._animatables[index];
  54580. animatable.syncWith(root);
  54581. }
  54582. return this;
  54583. };
  54584. /**
  54585. * Goes to a specific frame in this animation group
  54586. * @param frame the frame number to go to
  54587. * @return the animationGroup
  54588. */
  54589. AnimationGroup.prototype.goToFrame = function (frame) {
  54590. if (!this._isStarted) {
  54591. return this;
  54592. }
  54593. for (var index = 0; index < this._animatables.length; index++) {
  54594. var animatable = this._animatables[index];
  54595. animatable.goToFrame(frame);
  54596. }
  54597. return this;
  54598. };
  54599. /**
  54600. * Dispose all associated resources
  54601. */
  54602. AnimationGroup.prototype.dispose = function () {
  54603. this._targetedAnimations = [];
  54604. this._animatables = [];
  54605. var index = this._scene.animationGroups.indexOf(this);
  54606. if (index > -1) {
  54607. this._scene.animationGroups.splice(index, 1);
  54608. }
  54609. };
  54610. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  54611. // animatable should be taken out of the array
  54612. var idx = this._animatables.indexOf(animatable);
  54613. if (idx > -1) {
  54614. this._animatables.splice(idx, 1);
  54615. }
  54616. // all animatables were removed? animation group ended!
  54617. if (this._animatables.length === 0) {
  54618. this._isStarted = false;
  54619. this.onAnimationGroupEndObservable.notifyObservers(this);
  54620. }
  54621. };
  54622. // Statics
  54623. /**
  54624. * Returns a new AnimationGroup object parsed from the source provided.
  54625. * @param parsedAnimationGroup defines the source
  54626. * @param scene defines the scene that will receive the animationGroup
  54627. * @returns a new AnimationGroup
  54628. */
  54629. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  54630. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  54631. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  54632. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  54633. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  54634. var id = targetedAnimation.targetId;
  54635. var targetNode = scene.getNodeByID(id);
  54636. if (targetNode != null) {
  54637. animationGroup.addTargetedAnimation(animation, targetNode);
  54638. }
  54639. }
  54640. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  54641. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  54642. }
  54643. return animationGroup;
  54644. };
  54645. /**
  54646. * Returns the string "AnimationGroup"
  54647. * @returns "AnimationGroup"
  54648. */
  54649. AnimationGroup.prototype.getClassName = function () {
  54650. return "AnimationGroup";
  54651. };
  54652. /**
  54653. * Creates a detailled string about the object
  54654. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  54655. * @returns a string representing the object
  54656. */
  54657. AnimationGroup.prototype.toString = function (fullDetails) {
  54658. var ret = "Name: " + this.name;
  54659. ret += ", type: " + this.getClassName();
  54660. if (fullDetails) {
  54661. ret += ", from: " + this._from;
  54662. ret += ", to: " + this._to;
  54663. ret += ", isStarted: " + this._isStarted;
  54664. ret += ", speedRatio: " + this._speedRatio;
  54665. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  54666. ret += ", animatables length: " + this._animatables;
  54667. }
  54668. return ret;
  54669. };
  54670. return AnimationGroup;
  54671. }());
  54672. BABYLON.AnimationGroup = AnimationGroup;
  54673. })(BABYLON || (BABYLON = {}));
  54674. //# sourceMappingURL=babylon.animationGroup.js.map
  54675. var BABYLON;
  54676. (function (BABYLON) {
  54677. // Static values to help the garbage collector
  54678. // Quaternion
  54679. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  54680. // Vector3
  54681. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  54682. // Vector2
  54683. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  54684. // Size
  54685. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  54686. // Color3
  54687. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  54688. /**
  54689. * Defines a runtime animation
  54690. */
  54691. var RuntimeAnimation = /** @class */ (function () {
  54692. /**
  54693. * Create a new RuntimeAnimation object
  54694. * @param target defines the target of the animation
  54695. * @param animation defines the source animation object
  54696. * @param scene defines the hosting scene
  54697. * @param host defines the initiating Animatable
  54698. */
  54699. function RuntimeAnimation(target, animation, scene, host) {
  54700. var _this = this;
  54701. this._events = new Array();
  54702. /**
  54703. * The current frame of the runtime animation
  54704. */
  54705. this._currentFrame = 0;
  54706. /**
  54707. * The original value of the runtime animation
  54708. */
  54709. this._originalValue = new Array();
  54710. /**
  54711. * The offsets cache of the runtime animation
  54712. */
  54713. this._offsetsCache = {};
  54714. /**
  54715. * The high limits cache of the runtime animation
  54716. */
  54717. this._highLimitsCache = {};
  54718. /**
  54719. * Specifies if the runtime animation has been stopped
  54720. */
  54721. this._stopped = false;
  54722. /**
  54723. * The blending factor of the runtime animation
  54724. */
  54725. this._blendingFactor = 0;
  54726. /**
  54727. * The target path of the runtime animation
  54728. */
  54729. this._targetPath = "";
  54730. /**
  54731. * The weight of the runtime animation
  54732. */
  54733. this._weight = 1.0;
  54734. /**
  54735. * The ratio offset of the runtime animation
  54736. */
  54737. this._ratioOffset = 0;
  54738. /**
  54739. * The previous delay of the runtime animation
  54740. */
  54741. this._previousDelay = 0;
  54742. /**
  54743. * The previous ratio of the runtime animation
  54744. */
  54745. this._previousRatio = 0;
  54746. this._animation = animation;
  54747. this._target = target;
  54748. this._scene = scene;
  54749. this._host = host;
  54750. animation._runtimeAnimations.push(this);
  54751. // Cloning events locally
  54752. var events = animation.getEvents();
  54753. if (events && events.length > 0) {
  54754. events.forEach(function (e) {
  54755. _this._events.push(e._clone());
  54756. });
  54757. }
  54758. }
  54759. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  54760. /**
  54761. * Gets the current frame of the runtime animation
  54762. */
  54763. get: function () {
  54764. return this._currentFrame;
  54765. },
  54766. enumerable: true,
  54767. configurable: true
  54768. });
  54769. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  54770. /**
  54771. * Gets the weight of the runtime animation
  54772. */
  54773. get: function () {
  54774. return this._weight;
  54775. },
  54776. enumerable: true,
  54777. configurable: true
  54778. });
  54779. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  54780. /**
  54781. * Gets the current value of the runtime animation
  54782. */
  54783. get: function () {
  54784. return this._currentValue;
  54785. },
  54786. enumerable: true,
  54787. configurable: true
  54788. });
  54789. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  54790. /**
  54791. * Gets the target path of the runtime animation
  54792. */
  54793. get: function () {
  54794. return this._targetPath;
  54795. },
  54796. enumerable: true,
  54797. configurable: true
  54798. });
  54799. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  54800. /**
  54801. * Gets the actual target of the runtime animation
  54802. */
  54803. get: function () {
  54804. return this._activeTarget;
  54805. },
  54806. enumerable: true,
  54807. configurable: true
  54808. });
  54809. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  54810. /**
  54811. * Gets the animation from the runtime animation
  54812. */
  54813. get: function () {
  54814. return this._animation;
  54815. },
  54816. enumerable: true,
  54817. configurable: true
  54818. });
  54819. /**
  54820. * Resets the runtime animation to the beginning
  54821. * @param restoreOriginal defines whether to restore the target property to the original value
  54822. */
  54823. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  54824. if (restoreOriginal === void 0) { restoreOriginal = false; }
  54825. if (restoreOriginal) {
  54826. if (this._target instanceof Array) {
  54827. var index = 0;
  54828. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54829. var target = _a[_i];
  54830. if (this._originalValue[index] !== undefined) {
  54831. this._setValue(target, this._originalValue[index], -1);
  54832. }
  54833. index++;
  54834. }
  54835. }
  54836. else {
  54837. if (this._originalValue[0] !== undefined) {
  54838. this._setValue(this._target, this._originalValue[0], -1);
  54839. }
  54840. }
  54841. }
  54842. this._offsetsCache = {};
  54843. this._highLimitsCache = {};
  54844. this._currentFrame = 0;
  54845. this._blendingFactor = 0;
  54846. this._originalValue = new Array();
  54847. // Events
  54848. for (var index = 0; index < this._events.length; index++) {
  54849. this._events[index].isDone = false;
  54850. }
  54851. };
  54852. /**
  54853. * Specifies if the runtime animation is stopped
  54854. * @returns Boolean specifying if the runtime animation is stopped
  54855. */
  54856. RuntimeAnimation.prototype.isStopped = function () {
  54857. return this._stopped;
  54858. };
  54859. /**
  54860. * Disposes of the runtime animation
  54861. */
  54862. RuntimeAnimation.prototype.dispose = function () {
  54863. var index = this._animation.runtimeAnimations.indexOf(this);
  54864. if (index > -1) {
  54865. this._animation.runtimeAnimations.splice(index, 1);
  54866. }
  54867. };
  54868. /**
  54869. * Interpolates the animation from the current frame
  54870. * @param currentFrame The frame to interpolate the animation to
  54871. * @param repeatCount The number of times that the animation should loop
  54872. * @param loopMode The type of looping mode to use
  54873. * @param offsetValue Animation offset value
  54874. * @param highLimitValue The high limit value
  54875. * @returns The interpolated value
  54876. */
  54877. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  54878. this._currentFrame = currentFrame;
  54879. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  54880. this._workValue = BABYLON.Matrix.Zero();
  54881. }
  54882. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  54883. };
  54884. /**
  54885. * Apply the interpolated value to the target
  54886. * @param currentValue defines the value computed by the animation
  54887. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  54888. */
  54889. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  54890. if (weight === void 0) { weight = 1.0; }
  54891. if (this._target instanceof Array) {
  54892. var index = 0;
  54893. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54894. var target = _a[_i];
  54895. this._setValue(target, currentValue, weight, index);
  54896. index++;
  54897. }
  54898. }
  54899. else {
  54900. this._setValue(this._target, currentValue, weight);
  54901. }
  54902. };
  54903. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  54904. if (targetIndex === void 0) { targetIndex = 0; }
  54905. // Set value
  54906. var path;
  54907. var destination;
  54908. var targetPropertyPath = this._animation.targetPropertyPath;
  54909. if (targetPropertyPath.length > 1) {
  54910. var property = target[targetPropertyPath[0]];
  54911. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  54912. property = property[targetPropertyPath[index]];
  54913. }
  54914. path = targetPropertyPath[targetPropertyPath.length - 1];
  54915. destination = property;
  54916. }
  54917. else {
  54918. path = targetPropertyPath[0];
  54919. destination = target;
  54920. }
  54921. this._targetPath = path;
  54922. this._activeTarget = destination;
  54923. this._weight = weight;
  54924. if (this._originalValue[targetIndex] === undefined) {
  54925. var originalValue = void 0;
  54926. if (destination.getRestPose && path === "_matrix") { // For bones
  54927. originalValue = destination.getRestPose();
  54928. }
  54929. else {
  54930. originalValue = destination[path];
  54931. }
  54932. if (originalValue && originalValue.clone) {
  54933. this._originalValue[targetIndex] = originalValue.clone();
  54934. }
  54935. else {
  54936. this._originalValue[targetIndex] = originalValue;
  54937. }
  54938. }
  54939. // Blending
  54940. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  54941. if (enableBlending && this._blendingFactor <= 1.0) {
  54942. if (!this._originalBlendValue) {
  54943. var originalValue = destination[path];
  54944. if (originalValue.clone) {
  54945. this._originalBlendValue = originalValue.clone();
  54946. }
  54947. else {
  54948. this._originalBlendValue = originalValue;
  54949. }
  54950. }
  54951. if (this._originalBlendValue.m) { // Matrix
  54952. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  54953. if (this._currentValue) {
  54954. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  54955. }
  54956. else {
  54957. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54958. }
  54959. }
  54960. else {
  54961. if (this._currentValue) {
  54962. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  54963. }
  54964. else {
  54965. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54966. }
  54967. }
  54968. }
  54969. else {
  54970. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  54971. }
  54972. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  54973. this._blendingFactor += blendingSpeed;
  54974. }
  54975. else {
  54976. this._currentValue = currentValue;
  54977. }
  54978. if (weight !== -1.0) {
  54979. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  54980. }
  54981. else {
  54982. destination[path] = this._currentValue;
  54983. }
  54984. if (target.markAsDirty) {
  54985. target.markAsDirty(this._animation.targetProperty);
  54986. }
  54987. };
  54988. /**
  54989. * Gets the loop pmode of the runtime animation
  54990. * @returns Loop Mode
  54991. */
  54992. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  54993. if (this._target && this._target.animationPropertiesOverride) {
  54994. return this._target.animationPropertiesOverride.loopMode;
  54995. }
  54996. return this._animation.loopMode;
  54997. };
  54998. /**
  54999. * Move the current animation to a given frame
  55000. * @param frame defines the frame to move to
  55001. */
  55002. RuntimeAnimation.prototype.goToFrame = function (frame) {
  55003. var keys = this._animation.getKeys();
  55004. if (frame < keys[0].frame) {
  55005. frame = keys[0].frame;
  55006. }
  55007. else if (frame > keys[keys.length - 1].frame) {
  55008. frame = keys[keys.length - 1].frame;
  55009. }
  55010. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  55011. this.setValue(currentValue, -1);
  55012. };
  55013. /**
  55014. * @hidden Internal use only
  55015. */
  55016. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  55017. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  55018. this._ratioOffset = this._previousRatio - newRatio;
  55019. };
  55020. /**
  55021. * Execute the current animation
  55022. * @param delay defines the delay to add to the current frame
  55023. * @param from defines the lower bound of the animation range
  55024. * @param to defines the upper bound of the animation range
  55025. * @param loop defines if the current animation must loop
  55026. * @param speedRatio defines the current speed ratio
  55027. * @param weight defines the weight of the animation (default is -1 so no weight)
  55028. * @returns a boolean indicating if the animation is running
  55029. */
  55030. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  55031. if (weight === void 0) { weight = -1.0; }
  55032. var targetPropertyPath = this._animation.targetPropertyPath;
  55033. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  55034. this._stopped = true;
  55035. return false;
  55036. }
  55037. var returnValue = true;
  55038. var keys = this._animation.getKeys();
  55039. // Adding a start key at frame 0 if missing
  55040. if (keys[0].frame !== 0) {
  55041. var newKey = { frame: 0, value: keys[0].value };
  55042. keys.splice(0, 0, newKey);
  55043. }
  55044. // Adding a duplicate key when there is only one key at frame zero
  55045. else if (keys.length === 1) {
  55046. var newKey = { frame: 0.001, value: keys[0].value };
  55047. keys.push(newKey);
  55048. }
  55049. // Check limits
  55050. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55051. from = keys[0].frame;
  55052. }
  55053. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55054. to = keys[keys.length - 1].frame;
  55055. }
  55056. //to and from cannot be the same key
  55057. if (from === to) {
  55058. if (from > keys[0].frame) {
  55059. from--;
  55060. }
  55061. else if (to < keys[keys.length - 1].frame) {
  55062. to++;
  55063. }
  55064. }
  55065. // Compute ratio
  55066. var range = to - from;
  55067. var offsetValue;
  55068. // ratio represents the frame delta between from and to
  55069. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55070. var highLimitValue = 0;
  55071. this._previousDelay = delay;
  55072. this._previousRatio = ratio;
  55073. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55074. returnValue = false;
  55075. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55076. }
  55077. else {
  55078. // Get max value if required
  55079. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55080. var keyOffset = to.toString() + from.toString();
  55081. if (!this._offsetsCache[keyOffset]) {
  55082. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55083. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55084. switch (this._animation.dataType) {
  55085. // Float
  55086. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55087. this._offsetsCache[keyOffset] = toValue - fromValue;
  55088. break;
  55089. // Quaternion
  55090. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55091. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55092. break;
  55093. // Vector3
  55094. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55095. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55096. // Vector2
  55097. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55098. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55099. // Size
  55100. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55101. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55102. // Color3
  55103. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55104. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55105. default:
  55106. break;
  55107. }
  55108. this._highLimitsCache[keyOffset] = toValue;
  55109. }
  55110. highLimitValue = this._highLimitsCache[keyOffset];
  55111. offsetValue = this._offsetsCache[keyOffset];
  55112. }
  55113. }
  55114. if (offsetValue === undefined) {
  55115. switch (this._animation.dataType) {
  55116. // Float
  55117. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55118. offsetValue = 0;
  55119. break;
  55120. // Quaternion
  55121. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55122. offsetValue = _staticOffsetValueQuaternion;
  55123. break;
  55124. // Vector3
  55125. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55126. offsetValue = _staticOffsetValueVector3;
  55127. break;
  55128. // Vector2
  55129. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55130. offsetValue = _staticOffsetValueVector2;
  55131. break;
  55132. // Size
  55133. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55134. offsetValue = _staticOffsetValueSize;
  55135. break;
  55136. // Color3
  55137. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55138. offsetValue = _staticOffsetValueColor3;
  55139. }
  55140. }
  55141. // Compute value
  55142. var repeatCount = (ratio / range) >> 0;
  55143. var currentFrame = returnValue ? from + ratio % range : to;
  55144. // Need to normalize?
  55145. if (this._host && this._host.syncRoot) {
  55146. var syncRoot = this._host.syncRoot;
  55147. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55148. currentFrame = from + (to - from) * hostNormalizedFrame;
  55149. }
  55150. // Reset events if looping
  55151. var events = this._events;
  55152. if (range > 0 && this.currentFrame > currentFrame ||
  55153. range < 0 && this.currentFrame < currentFrame) {
  55154. // Need to reset animation events
  55155. for (var index = 0; index < events.length; index++) {
  55156. if (!events[index].onlyOnce) {
  55157. // reset event, the animation is looping
  55158. events[index].isDone = false;
  55159. }
  55160. }
  55161. }
  55162. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55163. // Set value
  55164. this.setValue(currentValue, weight);
  55165. // Check events
  55166. for (var index = 0; index < events.length; index++) {
  55167. // Make sure current frame has passed event frame and that event frame is within the current range
  55168. // Also, handle both forward and reverse animations
  55169. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55170. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55171. var event = events[index];
  55172. if (!event.isDone) {
  55173. // If event should be done only once, remove it.
  55174. if (event.onlyOnce) {
  55175. events.splice(index, 1);
  55176. index--;
  55177. }
  55178. event.isDone = true;
  55179. event.action(currentFrame);
  55180. } // Don't do anything if the event has already be done.
  55181. }
  55182. }
  55183. if (!returnValue) {
  55184. this._stopped = true;
  55185. }
  55186. return returnValue;
  55187. };
  55188. return RuntimeAnimation;
  55189. }());
  55190. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55191. })(BABYLON || (BABYLON = {}));
  55192. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  55193. var BABYLON;
  55194. (function (BABYLON) {
  55195. /**
  55196. * Class used to store an actual running animation
  55197. */
  55198. var Animatable = /** @class */ (function () {
  55199. /**
  55200. * Creates a new Animatable
  55201. * @param scene defines the hosting scene
  55202. * @param target defines the target object
  55203. * @param fromFrame defines the starting frame number (default is 0)
  55204. * @param toFrame defines the ending frame number (default is 100)
  55205. * @param loopAnimation defines if the animation must loop (default is false)
  55206. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55207. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55208. * @param animations defines a group of animation to add to the new Animatable
  55209. */
  55210. function Animatable(scene,
  55211. /** defines the target object */
  55212. target,
  55213. /** defines the starting frame number (default is 0) */
  55214. fromFrame,
  55215. /** defines the ending frame number (default is 100) */
  55216. toFrame,
  55217. /** defines if the animation must loop (default is false) */
  55218. loopAnimation, speedRatio,
  55219. /** defines a callback to call when animation ends if it is not looping */
  55220. onAnimationEnd, animations) {
  55221. if (fromFrame === void 0) { fromFrame = 0; }
  55222. if (toFrame === void 0) { toFrame = 100; }
  55223. if (loopAnimation === void 0) { loopAnimation = false; }
  55224. if (speedRatio === void 0) { speedRatio = 1.0; }
  55225. this.target = target;
  55226. this.fromFrame = fromFrame;
  55227. this.toFrame = toFrame;
  55228. this.loopAnimation = loopAnimation;
  55229. this.onAnimationEnd = onAnimationEnd;
  55230. this._localDelayOffset = null;
  55231. this._pausedDelay = null;
  55232. this._runtimeAnimations = new Array();
  55233. this._paused = false;
  55234. this._speedRatio = 1;
  55235. this._weight = -1.0;
  55236. /**
  55237. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  55238. * This will only apply for non looping animation (default is true)
  55239. */
  55240. this.disposeOnEnd = true;
  55241. /**
  55242. * Gets a boolean indicating if the animation has started
  55243. */
  55244. this.animationStarted = false;
  55245. /**
  55246. * Observer raised when the animation ends
  55247. */
  55248. this.onAnimationEndObservable = new BABYLON.Observable();
  55249. this._scene = scene;
  55250. if (animations) {
  55251. this.appendAnimations(target, animations);
  55252. }
  55253. this._speedRatio = speedRatio;
  55254. scene._activeAnimatables.push(this);
  55255. }
  55256. Object.defineProperty(Animatable.prototype, "syncRoot", {
  55257. /**
  55258. * Gets the root Animatable used to synchronize and normalize animations
  55259. */
  55260. get: function () {
  55261. return this._syncRoot;
  55262. },
  55263. enumerable: true,
  55264. configurable: true
  55265. });
  55266. Object.defineProperty(Animatable.prototype, "masterFrame", {
  55267. /**
  55268. * Gets the current frame of the first RuntimeAnimation
  55269. * Used to synchronize Animatables
  55270. */
  55271. get: function () {
  55272. if (this._runtimeAnimations.length === 0) {
  55273. return 0;
  55274. }
  55275. return this._runtimeAnimations[0].currentFrame;
  55276. },
  55277. enumerable: true,
  55278. configurable: true
  55279. });
  55280. Object.defineProperty(Animatable.prototype, "weight", {
  55281. /**
  55282. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  55283. */
  55284. get: function () {
  55285. return this._weight;
  55286. },
  55287. set: function (value) {
  55288. if (value === -1) { // -1 is ok and means no weight
  55289. this._weight = -1;
  55290. return;
  55291. }
  55292. // Else weight must be in [0, 1] range
  55293. this._weight = Math.min(Math.max(value, 0), 1.0);
  55294. },
  55295. enumerable: true,
  55296. configurable: true
  55297. });
  55298. Object.defineProperty(Animatable.prototype, "speedRatio", {
  55299. /**
  55300. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  55301. */
  55302. get: function () {
  55303. return this._speedRatio;
  55304. },
  55305. set: function (value) {
  55306. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  55307. var animation = this._runtimeAnimations[index];
  55308. animation._prepareForSpeedRatioChange(value);
  55309. }
  55310. this._speedRatio = value;
  55311. },
  55312. enumerable: true,
  55313. configurable: true
  55314. });
  55315. // Methods
  55316. /**
  55317. * Synchronize and normalize current Animatable with a source Animatable
  55318. * This is useful when using animation weights and when animations are not of the same length
  55319. * @param root defines the root Animatable to synchronize with
  55320. * @returns the current Animatable
  55321. */
  55322. Animatable.prototype.syncWith = function (root) {
  55323. this._syncRoot = root;
  55324. if (root) {
  55325. // Make sure this animatable will animate after the root
  55326. var index = this._scene._activeAnimatables.indexOf(this);
  55327. if (index > -1) {
  55328. this._scene._activeAnimatables.splice(index, 1);
  55329. this._scene._activeAnimatables.push(this);
  55330. }
  55331. }
  55332. return this;
  55333. };
  55334. /**
  55335. * Gets the list of runtime animations
  55336. * @returns an array of RuntimeAnimation
  55337. */
  55338. Animatable.prototype.getAnimations = function () {
  55339. return this._runtimeAnimations;
  55340. };
  55341. /**
  55342. * Adds more animations to the current animatable
  55343. * @param target defines the target of the animations
  55344. * @param animations defines the new animations to add
  55345. */
  55346. Animatable.prototype.appendAnimations = function (target, animations) {
  55347. for (var index = 0; index < animations.length; index++) {
  55348. var animation = animations[index];
  55349. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  55350. }
  55351. };
  55352. /**
  55353. * Gets the source animation for a specific property
  55354. * @param property defines the propertyu to look for
  55355. * @returns null or the source animation for the given property
  55356. */
  55357. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  55358. var runtimeAnimations = this._runtimeAnimations;
  55359. for (var index = 0; index < runtimeAnimations.length; index++) {
  55360. if (runtimeAnimations[index].animation.targetProperty === property) {
  55361. return runtimeAnimations[index].animation;
  55362. }
  55363. }
  55364. return null;
  55365. };
  55366. /**
  55367. * Gets the runtime animation for a specific property
  55368. * @param property defines the propertyu to look for
  55369. * @returns null or the runtime animation for the given property
  55370. */
  55371. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  55372. var runtimeAnimations = this._runtimeAnimations;
  55373. for (var index = 0; index < runtimeAnimations.length; index++) {
  55374. if (runtimeAnimations[index].animation.targetProperty === property) {
  55375. return runtimeAnimations[index];
  55376. }
  55377. }
  55378. return null;
  55379. };
  55380. /**
  55381. * Resets the animatable to its original state
  55382. */
  55383. Animatable.prototype.reset = function () {
  55384. var runtimeAnimations = this._runtimeAnimations;
  55385. for (var index = 0; index < runtimeAnimations.length; index++) {
  55386. runtimeAnimations[index].reset(true);
  55387. }
  55388. this._localDelayOffset = null;
  55389. this._pausedDelay = null;
  55390. };
  55391. /**
  55392. * Allows the animatable to blend with current running animations
  55393. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55394. * @param blendingSpeed defines the blending speed to use
  55395. */
  55396. Animatable.prototype.enableBlending = function (blendingSpeed) {
  55397. var runtimeAnimations = this._runtimeAnimations;
  55398. for (var index = 0; index < runtimeAnimations.length; index++) {
  55399. runtimeAnimations[index].animation.enableBlending = true;
  55400. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  55401. }
  55402. };
  55403. /**
  55404. * Disable animation blending
  55405. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55406. */
  55407. Animatable.prototype.disableBlending = function () {
  55408. var runtimeAnimations = this._runtimeAnimations;
  55409. for (var index = 0; index < runtimeAnimations.length; index++) {
  55410. runtimeAnimations[index].animation.enableBlending = false;
  55411. }
  55412. };
  55413. /**
  55414. * Jump directly to a given frame
  55415. * @param frame defines the frame to jump to
  55416. */
  55417. Animatable.prototype.goToFrame = function (frame) {
  55418. var runtimeAnimations = this._runtimeAnimations;
  55419. if (runtimeAnimations[0]) {
  55420. var fps = runtimeAnimations[0].animation.framePerSecond;
  55421. var currentFrame = runtimeAnimations[0].currentFrame;
  55422. var adjustTime = frame - currentFrame;
  55423. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  55424. if (this._localDelayOffset === null) {
  55425. this._localDelayOffset = 0;
  55426. }
  55427. this._localDelayOffset -= delay;
  55428. }
  55429. for (var index = 0; index < runtimeAnimations.length; index++) {
  55430. runtimeAnimations[index].goToFrame(frame);
  55431. }
  55432. };
  55433. /**
  55434. * Pause the animation
  55435. */
  55436. Animatable.prototype.pause = function () {
  55437. if (this._paused) {
  55438. return;
  55439. }
  55440. this._paused = true;
  55441. };
  55442. /**
  55443. * Restart the animation
  55444. */
  55445. Animatable.prototype.restart = function () {
  55446. this._paused = false;
  55447. };
  55448. Animatable.prototype._raiseOnAnimationEnd = function () {
  55449. if (this.onAnimationEnd) {
  55450. this.onAnimationEnd();
  55451. }
  55452. this.onAnimationEndObservable.notifyObservers(this);
  55453. };
  55454. /**
  55455. * Stop and delete the current animation
  55456. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  55457. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  55458. */
  55459. Animatable.prototype.stop = function (animationName, targetMask) {
  55460. if (animationName || targetMask) {
  55461. var idx = this._scene._activeAnimatables.indexOf(this);
  55462. if (idx > -1) {
  55463. var runtimeAnimations = this._runtimeAnimations;
  55464. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  55465. var runtimeAnimation = runtimeAnimations[index];
  55466. if (animationName && runtimeAnimation.animation.name != animationName) {
  55467. continue;
  55468. }
  55469. if (targetMask && !targetMask(runtimeAnimation.target)) {
  55470. continue;
  55471. }
  55472. runtimeAnimation.dispose();
  55473. runtimeAnimations.splice(index, 1);
  55474. }
  55475. if (runtimeAnimations.length == 0) {
  55476. this._scene._activeAnimatables.splice(idx, 1);
  55477. this._raiseOnAnimationEnd();
  55478. }
  55479. }
  55480. }
  55481. else {
  55482. var index = this._scene._activeAnimatables.indexOf(this);
  55483. if (index > -1) {
  55484. this._scene._activeAnimatables.splice(index, 1);
  55485. var runtimeAnimations = this._runtimeAnimations;
  55486. for (var index = 0; index < runtimeAnimations.length; index++) {
  55487. runtimeAnimations[index].dispose();
  55488. }
  55489. this._raiseOnAnimationEnd();
  55490. }
  55491. }
  55492. };
  55493. /**
  55494. * Wait asynchronously for the animation to end
  55495. * @returns a promise which will be fullfilled when the animation ends
  55496. */
  55497. Animatable.prototype.waitAsync = function () {
  55498. var _this = this;
  55499. return new Promise(function (resolve, reject) {
  55500. _this.onAnimationEndObservable.add(function () {
  55501. resolve(_this);
  55502. }, undefined, undefined, _this, true);
  55503. });
  55504. };
  55505. /** @hidden */
  55506. Animatable.prototype._animate = function (delay) {
  55507. if (this._paused) {
  55508. this.animationStarted = false;
  55509. if (this._pausedDelay === null) {
  55510. this._pausedDelay = delay;
  55511. }
  55512. return true;
  55513. }
  55514. if (this._localDelayOffset === null) {
  55515. this._localDelayOffset = delay;
  55516. this._pausedDelay = null;
  55517. }
  55518. else if (this._pausedDelay !== null) {
  55519. this._localDelayOffset += delay - this._pausedDelay;
  55520. this._pausedDelay = null;
  55521. }
  55522. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  55523. return true;
  55524. }
  55525. // Animating
  55526. var running = false;
  55527. var runtimeAnimations = this._runtimeAnimations;
  55528. var index;
  55529. for (index = 0; index < runtimeAnimations.length; index++) {
  55530. var animation = runtimeAnimations[index];
  55531. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  55532. running = running || isRunning;
  55533. }
  55534. this.animationStarted = running;
  55535. if (!running) {
  55536. if (this.disposeOnEnd) {
  55537. // Remove from active animatables
  55538. index = this._scene._activeAnimatables.indexOf(this);
  55539. this._scene._activeAnimatables.splice(index, 1);
  55540. // Dispose all runtime animations
  55541. for (index = 0; index < runtimeAnimations.length; index++) {
  55542. runtimeAnimations[index].dispose();
  55543. }
  55544. }
  55545. this._raiseOnAnimationEnd();
  55546. if (this.disposeOnEnd) {
  55547. this.onAnimationEnd = null;
  55548. this.onAnimationEndObservable.clear();
  55549. }
  55550. }
  55551. return running;
  55552. };
  55553. return Animatable;
  55554. }());
  55555. BABYLON.Animatable = Animatable;
  55556. })(BABYLON || (BABYLON = {}));
  55557. //# sourceMappingURL=babylon.animatable.js.map
  55558. var BABYLON;
  55559. (function (BABYLON) {
  55560. /**
  55561. * Base class used for every default easing function.
  55562. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55563. */
  55564. var EasingFunction = /** @class */ (function () {
  55565. function EasingFunction() {
  55566. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  55567. }
  55568. /**
  55569. * Sets the easing mode of the current function.
  55570. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  55571. */
  55572. EasingFunction.prototype.setEasingMode = function (easingMode) {
  55573. var n = Math.min(Math.max(easingMode, 0), 2);
  55574. this._easingMode = n;
  55575. };
  55576. /**
  55577. * Gets the current easing mode.
  55578. * @returns the easing mode
  55579. */
  55580. EasingFunction.prototype.getEasingMode = function () {
  55581. return this._easingMode;
  55582. };
  55583. /**
  55584. * @hidden
  55585. */
  55586. EasingFunction.prototype.easeInCore = function (gradient) {
  55587. throw new Error('You must implement this method');
  55588. };
  55589. /**
  55590. * Given an input gradient between 0 and 1, this returns the corrseponding value
  55591. * of the easing function.
  55592. * @param gradient Defines the value between 0 and 1 we want the easing value for
  55593. * @returns the corresponding value on the curve defined by the easing function
  55594. */
  55595. EasingFunction.prototype.ease = function (gradient) {
  55596. switch (this._easingMode) {
  55597. case EasingFunction.EASINGMODE_EASEIN:
  55598. return this.easeInCore(gradient);
  55599. case EasingFunction.EASINGMODE_EASEOUT:
  55600. return (1 - this.easeInCore(1 - gradient));
  55601. }
  55602. if (gradient >= 0.5) {
  55603. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  55604. }
  55605. return (this.easeInCore(gradient * 2) * 0.5);
  55606. };
  55607. /**
  55608. * Interpolation follows the mathematical formula associated with the easing function.
  55609. */
  55610. EasingFunction.EASINGMODE_EASEIN = 0;
  55611. /**
  55612. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  55613. */
  55614. EasingFunction.EASINGMODE_EASEOUT = 1;
  55615. /**
  55616. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  55617. */
  55618. EasingFunction.EASINGMODE_EASEINOUT = 2;
  55619. return EasingFunction;
  55620. }());
  55621. BABYLON.EasingFunction = EasingFunction;
  55622. /**
  55623. * Easing function with a circle shape (see link below).
  55624. * @see https://easings.net/#easeInCirc
  55625. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55626. */
  55627. var CircleEase = /** @class */ (function (_super) {
  55628. __extends(CircleEase, _super);
  55629. function CircleEase() {
  55630. return _super !== null && _super.apply(this, arguments) || this;
  55631. }
  55632. /** @hidden */
  55633. CircleEase.prototype.easeInCore = function (gradient) {
  55634. gradient = Math.max(0, Math.min(1, gradient));
  55635. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  55636. };
  55637. return CircleEase;
  55638. }(EasingFunction));
  55639. BABYLON.CircleEase = CircleEase;
  55640. /**
  55641. * Easing function with a ease back shape (see link below).
  55642. * @see https://easings.net/#easeInBack
  55643. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55644. */
  55645. var BackEase = /** @class */ (function (_super) {
  55646. __extends(BackEase, _super);
  55647. /**
  55648. * Instantiates a back ease easing
  55649. * @see https://easings.net/#easeInBack
  55650. * @param amplitude Defines the amplitude of the function
  55651. */
  55652. function BackEase(
  55653. /** Defines the amplitude of the function */
  55654. amplitude) {
  55655. if (amplitude === void 0) { amplitude = 1; }
  55656. var _this = _super.call(this) || this;
  55657. _this.amplitude = amplitude;
  55658. return _this;
  55659. }
  55660. /** @hidden */
  55661. BackEase.prototype.easeInCore = function (gradient) {
  55662. var num = Math.max(0, this.amplitude);
  55663. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  55664. };
  55665. return BackEase;
  55666. }(EasingFunction));
  55667. BABYLON.BackEase = BackEase;
  55668. /**
  55669. * Easing function with a bouncing shape (see link below).
  55670. * @see https://easings.net/#easeInBounce
  55671. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55672. */
  55673. var BounceEase = /** @class */ (function (_super) {
  55674. __extends(BounceEase, _super);
  55675. /**
  55676. * Instantiates a bounce easing
  55677. * @see https://easings.net/#easeInBounce
  55678. * @param bounces Defines the number of bounces
  55679. * @param bounciness Defines the amplitude of the bounce
  55680. */
  55681. function BounceEase(
  55682. /** Defines the number of bounces */
  55683. bounces,
  55684. /** Defines the amplitude of the bounce */
  55685. bounciness) {
  55686. if (bounces === void 0) { bounces = 3; }
  55687. if (bounciness === void 0) { bounciness = 2; }
  55688. var _this = _super.call(this) || this;
  55689. _this.bounces = bounces;
  55690. _this.bounciness = bounciness;
  55691. return _this;
  55692. }
  55693. /** @hidden */
  55694. BounceEase.prototype.easeInCore = function (gradient) {
  55695. var y = Math.max(0.0, this.bounces);
  55696. var bounciness = this.bounciness;
  55697. if (bounciness <= 1.0) {
  55698. bounciness = 1.001;
  55699. }
  55700. var num9 = Math.pow(bounciness, y);
  55701. var num5 = 1.0 - bounciness;
  55702. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  55703. var num15 = gradient * num4;
  55704. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  55705. var num3 = Math.floor(num65);
  55706. var num13 = num3 + 1.0;
  55707. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  55708. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  55709. var num7 = (num8 + num12) * 0.5;
  55710. var num6 = gradient - num7;
  55711. var num2 = num7 - num8;
  55712. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  55713. };
  55714. return BounceEase;
  55715. }(EasingFunction));
  55716. BABYLON.BounceEase = BounceEase;
  55717. /**
  55718. * Easing function with a power of 3 shape (see link below).
  55719. * @see https://easings.net/#easeInCubic
  55720. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55721. */
  55722. var CubicEase = /** @class */ (function (_super) {
  55723. __extends(CubicEase, _super);
  55724. function CubicEase() {
  55725. return _super !== null && _super.apply(this, arguments) || this;
  55726. }
  55727. /** @hidden */
  55728. CubicEase.prototype.easeInCore = function (gradient) {
  55729. return (gradient * gradient * gradient);
  55730. };
  55731. return CubicEase;
  55732. }(EasingFunction));
  55733. BABYLON.CubicEase = CubicEase;
  55734. /**
  55735. * Easing function with an elastic shape (see link below).
  55736. * @see https://easings.net/#easeInElastic
  55737. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55738. */
  55739. var ElasticEase = /** @class */ (function (_super) {
  55740. __extends(ElasticEase, _super);
  55741. /**
  55742. * Instantiates an elastic easing function
  55743. * @see https://easings.net/#easeInElastic
  55744. * @param oscillations Defines the number of oscillations
  55745. * @param springiness Defines the amplitude of the oscillations
  55746. */
  55747. function ElasticEase(
  55748. /** Defines the number of oscillations*/
  55749. oscillations,
  55750. /** Defines the amplitude of the oscillations*/
  55751. springiness) {
  55752. if (oscillations === void 0) { oscillations = 3; }
  55753. if (springiness === void 0) { springiness = 3; }
  55754. var _this = _super.call(this) || this;
  55755. _this.oscillations = oscillations;
  55756. _this.springiness = springiness;
  55757. return _this;
  55758. }
  55759. /** @hidden */
  55760. ElasticEase.prototype.easeInCore = function (gradient) {
  55761. var num2;
  55762. var num3 = Math.max(0.0, this.oscillations);
  55763. var num = Math.max(0.0, this.springiness);
  55764. if (num == 0) {
  55765. num2 = gradient;
  55766. }
  55767. else {
  55768. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  55769. }
  55770. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  55771. };
  55772. return ElasticEase;
  55773. }(EasingFunction));
  55774. BABYLON.ElasticEase = ElasticEase;
  55775. /**
  55776. * Easing function with an exponential shape (see link below).
  55777. * @see https://easings.net/#easeInExpo
  55778. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55779. */
  55780. var ExponentialEase = /** @class */ (function (_super) {
  55781. __extends(ExponentialEase, _super);
  55782. /**
  55783. * Instantiates an exponential easing function
  55784. * @see https://easings.net/#easeInExpo
  55785. * @param exponent Defines the exponent of the function
  55786. */
  55787. function ExponentialEase(
  55788. /** Defines the exponent of the function */
  55789. exponent) {
  55790. if (exponent === void 0) { exponent = 2; }
  55791. var _this = _super.call(this) || this;
  55792. _this.exponent = exponent;
  55793. return _this;
  55794. }
  55795. /** @hidden */
  55796. ExponentialEase.prototype.easeInCore = function (gradient) {
  55797. if (this.exponent <= 0) {
  55798. return gradient;
  55799. }
  55800. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  55801. };
  55802. return ExponentialEase;
  55803. }(EasingFunction));
  55804. BABYLON.ExponentialEase = ExponentialEase;
  55805. /**
  55806. * Easing function with a power shape (see link below).
  55807. * @see https://easings.net/#easeInQuad
  55808. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55809. */
  55810. var PowerEase = /** @class */ (function (_super) {
  55811. __extends(PowerEase, _super);
  55812. /**
  55813. * Instantiates an power base easing function
  55814. * @see https://easings.net/#easeInQuad
  55815. * @param power Defines the power of the function
  55816. */
  55817. function PowerEase(
  55818. /** Defines the power of the function */
  55819. power) {
  55820. if (power === void 0) { power = 2; }
  55821. var _this = _super.call(this) || this;
  55822. _this.power = power;
  55823. return _this;
  55824. }
  55825. /** @hidden */
  55826. PowerEase.prototype.easeInCore = function (gradient) {
  55827. var y = Math.max(0.0, this.power);
  55828. return Math.pow(gradient, y);
  55829. };
  55830. return PowerEase;
  55831. }(EasingFunction));
  55832. BABYLON.PowerEase = PowerEase;
  55833. /**
  55834. * Easing function with a power of 2 shape (see link below).
  55835. * @see https://easings.net/#easeInQuad
  55836. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55837. */
  55838. var QuadraticEase = /** @class */ (function (_super) {
  55839. __extends(QuadraticEase, _super);
  55840. function QuadraticEase() {
  55841. return _super !== null && _super.apply(this, arguments) || this;
  55842. }
  55843. /** @hidden */
  55844. QuadraticEase.prototype.easeInCore = function (gradient) {
  55845. return (gradient * gradient);
  55846. };
  55847. return QuadraticEase;
  55848. }(EasingFunction));
  55849. BABYLON.QuadraticEase = QuadraticEase;
  55850. /**
  55851. * Easing function with a power of 4 shape (see link below).
  55852. * @see https://easings.net/#easeInQuart
  55853. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55854. */
  55855. var QuarticEase = /** @class */ (function (_super) {
  55856. __extends(QuarticEase, _super);
  55857. function QuarticEase() {
  55858. return _super !== null && _super.apply(this, arguments) || this;
  55859. }
  55860. /** @hidden */
  55861. QuarticEase.prototype.easeInCore = function (gradient) {
  55862. return (gradient * gradient * gradient * gradient);
  55863. };
  55864. return QuarticEase;
  55865. }(EasingFunction));
  55866. BABYLON.QuarticEase = QuarticEase;
  55867. /**
  55868. * Easing function with a power of 5 shape (see link below).
  55869. * @see https://easings.net/#easeInQuint
  55870. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55871. */
  55872. var QuinticEase = /** @class */ (function (_super) {
  55873. __extends(QuinticEase, _super);
  55874. function QuinticEase() {
  55875. return _super !== null && _super.apply(this, arguments) || this;
  55876. }
  55877. /** @hidden */
  55878. QuinticEase.prototype.easeInCore = function (gradient) {
  55879. return (gradient * gradient * gradient * gradient * gradient);
  55880. };
  55881. return QuinticEase;
  55882. }(EasingFunction));
  55883. BABYLON.QuinticEase = QuinticEase;
  55884. /**
  55885. * Easing function with a sin shape (see link below).
  55886. * @see https://easings.net/#easeInSine
  55887. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55888. */
  55889. var SineEase = /** @class */ (function (_super) {
  55890. __extends(SineEase, _super);
  55891. function SineEase() {
  55892. return _super !== null && _super.apply(this, arguments) || this;
  55893. }
  55894. /** @hidden */
  55895. SineEase.prototype.easeInCore = function (gradient) {
  55896. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  55897. };
  55898. return SineEase;
  55899. }(EasingFunction));
  55900. BABYLON.SineEase = SineEase;
  55901. /**
  55902. * Easing function with a bezier shape (see link below).
  55903. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55904. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55905. */
  55906. var BezierCurveEase = /** @class */ (function (_super) {
  55907. __extends(BezierCurveEase, _super);
  55908. /**
  55909. * Instantiates a bezier function
  55910. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55911. * @param x1 Defines the x component of the start tangent in the bezier curve
  55912. * @param y1 Defines the y component of the start tangent in the bezier curve
  55913. * @param x2 Defines the x component of the end tangent in the bezier curve
  55914. * @param y2 Defines the y component of the end tangent in the bezier curve
  55915. */
  55916. function BezierCurveEase(
  55917. /** Defines the x component of the start tangent in the bezier curve */
  55918. x1,
  55919. /** Defines the y component of the start tangent in the bezier curve */
  55920. y1,
  55921. /** Defines the x component of the end tangent in the bezier curve */
  55922. x2,
  55923. /** Defines the y component of the end tangent in the bezier curve */
  55924. y2) {
  55925. if (x1 === void 0) { x1 = 0; }
  55926. if (y1 === void 0) { y1 = 0; }
  55927. if (x2 === void 0) { x2 = 1; }
  55928. if (y2 === void 0) { y2 = 1; }
  55929. var _this = _super.call(this) || this;
  55930. _this.x1 = x1;
  55931. _this.y1 = y1;
  55932. _this.x2 = x2;
  55933. _this.y2 = y2;
  55934. return _this;
  55935. }
  55936. /** @hidden */
  55937. BezierCurveEase.prototype.easeInCore = function (gradient) {
  55938. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  55939. };
  55940. return BezierCurveEase;
  55941. }(EasingFunction));
  55942. BABYLON.BezierCurveEase = BezierCurveEase;
  55943. })(BABYLON || (BABYLON = {}));
  55944. //# sourceMappingURL=babylon.easing.js.map
  55945. var BABYLON;
  55946. (function (BABYLON) {
  55947. /**
  55948. * A Condition applied to an Action
  55949. */
  55950. var Condition = /** @class */ (function () {
  55951. /**
  55952. * Creates a new Condition
  55953. * @param actionManager the manager of the action the condition is applied to
  55954. */
  55955. function Condition(actionManager) {
  55956. this._actionManager = actionManager;
  55957. }
  55958. /**
  55959. * Check if the current condition is valid
  55960. * @returns a boolean
  55961. */
  55962. Condition.prototype.isValid = function () {
  55963. return true;
  55964. };
  55965. /**
  55966. * Internal only
  55967. * @hidden
  55968. */
  55969. Condition.prototype._getProperty = function (propertyPath) {
  55970. return this._actionManager._getProperty(propertyPath);
  55971. };
  55972. /**
  55973. * Internal only
  55974. * @hidden
  55975. */
  55976. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  55977. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55978. };
  55979. /**
  55980. * Serialize placeholder for child classes
  55981. * @returns the serialized object
  55982. */
  55983. Condition.prototype.serialize = function () {
  55984. };
  55985. /**
  55986. * Internal only
  55987. * @hidden
  55988. */
  55989. Condition.prototype._serialize = function (serializedCondition) {
  55990. return {
  55991. type: 2,
  55992. children: [],
  55993. name: serializedCondition.name,
  55994. properties: serializedCondition.properties
  55995. };
  55996. };
  55997. return Condition;
  55998. }());
  55999. BABYLON.Condition = Condition;
  56000. /**
  56001. * Defines specific conditional operators as extensions of Condition
  56002. */
  56003. var ValueCondition = /** @class */ (function (_super) {
  56004. __extends(ValueCondition, _super);
  56005. /**
  56006. * Creates a new ValueCondition
  56007. * @param actionManager manager for the action the condition applies to
  56008. * @param target for the action
  56009. * @param propertyPath path to specify the property of the target the conditional operator uses
  56010. * @param value the value compared by the conditional operator against the current value of the property
  56011. * @param operator the conditional operator, default ValueCondition.IsEqual
  56012. */
  56013. function ValueCondition(actionManager, target,
  56014. /** path to specify the property of the target the conditional operator uses */
  56015. propertyPath,
  56016. /** the value compared by the conditional operator against the current value of the property */
  56017. value,
  56018. /** the conditional operator, default ValueCondition.IsEqual */
  56019. operator) {
  56020. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  56021. var _this = _super.call(this, actionManager) || this;
  56022. _this.propertyPath = propertyPath;
  56023. _this.value = value;
  56024. _this.operator = operator;
  56025. _this._target = target;
  56026. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  56027. _this._property = _this._getProperty(_this.propertyPath);
  56028. return _this;
  56029. }
  56030. Object.defineProperty(ValueCondition, "IsEqual", {
  56031. /**
  56032. * returns the number for IsEqual
  56033. */
  56034. get: function () {
  56035. return ValueCondition._IsEqual;
  56036. },
  56037. enumerable: true,
  56038. configurable: true
  56039. });
  56040. Object.defineProperty(ValueCondition, "IsDifferent", {
  56041. /**
  56042. * Returns the number for IsDifferent
  56043. */
  56044. get: function () {
  56045. return ValueCondition._IsDifferent;
  56046. },
  56047. enumerable: true,
  56048. configurable: true
  56049. });
  56050. Object.defineProperty(ValueCondition, "IsGreater", {
  56051. /**
  56052. * Returns the number for IsGreater
  56053. */
  56054. get: function () {
  56055. return ValueCondition._IsGreater;
  56056. },
  56057. enumerable: true,
  56058. configurable: true
  56059. });
  56060. Object.defineProperty(ValueCondition, "IsLesser", {
  56061. /**
  56062. * Returns the number for IsLesser
  56063. */
  56064. get: function () {
  56065. return ValueCondition._IsLesser;
  56066. },
  56067. enumerable: true,
  56068. configurable: true
  56069. });
  56070. /**
  56071. * Compares the given value with the property value for the specified conditional operator
  56072. * @returns the result of the comparison
  56073. */
  56074. ValueCondition.prototype.isValid = function () {
  56075. switch (this.operator) {
  56076. case ValueCondition.IsGreater:
  56077. return this._effectiveTarget[this._property] > this.value;
  56078. case ValueCondition.IsLesser:
  56079. return this._effectiveTarget[this._property] < this.value;
  56080. case ValueCondition.IsEqual:
  56081. case ValueCondition.IsDifferent:
  56082. var check;
  56083. if (this.value.equals) {
  56084. check = this.value.equals(this._effectiveTarget[this._property]);
  56085. }
  56086. else {
  56087. check = this.value === this._effectiveTarget[this._property];
  56088. }
  56089. return this.operator === ValueCondition.IsEqual ? check : !check;
  56090. }
  56091. return false;
  56092. };
  56093. /**
  56094. * Serialize the ValueCondition into a JSON compatible object
  56095. * @returns serialization object
  56096. */
  56097. ValueCondition.prototype.serialize = function () {
  56098. return this._serialize({
  56099. name: "ValueCondition",
  56100. properties: [
  56101. BABYLON.Action._GetTargetProperty(this._target),
  56102. { name: "propertyPath", value: this.propertyPath },
  56103. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56104. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56105. ]
  56106. });
  56107. };
  56108. /**
  56109. * Gets the name of the conditional operator for the ValueCondition
  56110. * @param operator the conditional operator
  56111. * @returns the name
  56112. */
  56113. ValueCondition.GetOperatorName = function (operator) {
  56114. switch (operator) {
  56115. case ValueCondition._IsEqual: return "IsEqual";
  56116. case ValueCondition._IsDifferent: return "IsDifferent";
  56117. case ValueCondition._IsGreater: return "IsGreater";
  56118. case ValueCondition._IsLesser: return "IsLesser";
  56119. default: return "";
  56120. }
  56121. };
  56122. /**
  56123. * Internal only
  56124. * @hidden
  56125. */
  56126. ValueCondition._IsEqual = 0;
  56127. /**
  56128. * Internal only
  56129. * @hidden
  56130. */
  56131. ValueCondition._IsDifferent = 1;
  56132. /**
  56133. * Internal only
  56134. * @hidden
  56135. */
  56136. ValueCondition._IsGreater = 2;
  56137. /**
  56138. * Internal only
  56139. * @hidden
  56140. */
  56141. ValueCondition._IsLesser = 3;
  56142. return ValueCondition;
  56143. }(Condition));
  56144. BABYLON.ValueCondition = ValueCondition;
  56145. /**
  56146. * Defines a predicate condition as an extension of Condition
  56147. */
  56148. var PredicateCondition = /** @class */ (function (_super) {
  56149. __extends(PredicateCondition, _super);
  56150. /**
  56151. * Creates a new PredicateCondition
  56152. * @param actionManager manager for the action the condition applies to
  56153. * @param predicate defines the predicate function used to validate the condition
  56154. */
  56155. function PredicateCondition(actionManager,
  56156. /** defines the predicate function used to validate the condition */
  56157. predicate) {
  56158. var _this = _super.call(this, actionManager) || this;
  56159. _this.predicate = predicate;
  56160. return _this;
  56161. }
  56162. /**
  56163. * @returns the validity of the predicate condition
  56164. */
  56165. PredicateCondition.prototype.isValid = function () {
  56166. return this.predicate();
  56167. };
  56168. return PredicateCondition;
  56169. }(Condition));
  56170. BABYLON.PredicateCondition = PredicateCondition;
  56171. /**
  56172. * Defines a state condition as an extension of Condition
  56173. */
  56174. var StateCondition = /** @class */ (function (_super) {
  56175. __extends(StateCondition, _super);
  56176. /**
  56177. * Creates a new StateCondition
  56178. * @param actionManager manager for the action the condition applies to
  56179. * @param target of the condition
  56180. * @param value to compare with target state
  56181. */
  56182. function StateCondition(actionManager, target,
  56183. /** Value to compare with target state */
  56184. value) {
  56185. var _this = _super.call(this, actionManager) || this;
  56186. _this.value = value;
  56187. _this._target = target;
  56188. return _this;
  56189. }
  56190. /**
  56191. * Gets a boolean indicating if the current condition is met
  56192. * @returns the validity of the state
  56193. */
  56194. StateCondition.prototype.isValid = function () {
  56195. return this._target.state === this.value;
  56196. };
  56197. /**
  56198. * Serialize the StateCondition into a JSON compatible object
  56199. * @returns serialization object
  56200. */
  56201. StateCondition.prototype.serialize = function () {
  56202. return this._serialize({
  56203. name: "StateCondition",
  56204. properties: [
  56205. BABYLON.Action._GetTargetProperty(this._target),
  56206. { name: "value", value: this.value }
  56207. ]
  56208. });
  56209. };
  56210. return StateCondition;
  56211. }(Condition));
  56212. BABYLON.StateCondition = StateCondition;
  56213. })(BABYLON || (BABYLON = {}));
  56214. //# sourceMappingURL=babylon.condition.js.map
  56215. var BABYLON;
  56216. (function (BABYLON) {
  56217. /**
  56218. * The action to be carried out following a trigger
  56219. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  56220. */
  56221. var Action = /** @class */ (function () {
  56222. /**
  56223. * Creates a new Action
  56224. * @param triggerOptions the trigger, with or without parameters, for the action
  56225. * @param condition an optional determinant of action
  56226. */
  56227. function Action(
  56228. /** the trigger, with or without parameters, for the action */
  56229. triggerOptions, condition) {
  56230. this.triggerOptions = triggerOptions;
  56231. /**
  56232. * An event triggered prior to action being executed.
  56233. */
  56234. this.onBeforeExecuteObservable = new BABYLON.Observable();
  56235. if (triggerOptions.parameter) {
  56236. this.trigger = triggerOptions.trigger;
  56237. this._triggerParameter = triggerOptions.parameter;
  56238. }
  56239. else if (triggerOptions.trigger) {
  56240. this.trigger = triggerOptions.trigger;
  56241. }
  56242. else {
  56243. this.trigger = triggerOptions;
  56244. }
  56245. this._nextActiveAction = this;
  56246. this._condition = condition;
  56247. }
  56248. /**
  56249. * Internal only
  56250. * @hidden
  56251. */
  56252. Action.prototype._prepare = function () {
  56253. };
  56254. /**
  56255. * Gets the trigger parameters
  56256. * @returns the trigger parameters
  56257. */
  56258. Action.prototype.getTriggerParameter = function () {
  56259. return this._triggerParameter;
  56260. };
  56261. /**
  56262. * Internal only - executes current action event
  56263. * @hidden
  56264. */
  56265. Action.prototype._executeCurrent = function (evt) {
  56266. if (this._nextActiveAction._condition) {
  56267. var condition = this._nextActiveAction._condition;
  56268. var currentRenderId = this._actionManager.getScene().getRenderId();
  56269. // We cache the current evaluation for the current frame
  56270. if (condition._evaluationId === currentRenderId) {
  56271. if (!condition._currentResult) {
  56272. return;
  56273. }
  56274. }
  56275. else {
  56276. condition._evaluationId = currentRenderId;
  56277. if (!condition.isValid()) {
  56278. condition._currentResult = false;
  56279. return;
  56280. }
  56281. condition._currentResult = true;
  56282. }
  56283. }
  56284. this.onBeforeExecuteObservable.notifyObservers(this);
  56285. this._nextActiveAction.execute(evt);
  56286. this.skipToNextActiveAction();
  56287. };
  56288. /**
  56289. * Execute placeholder for child classes
  56290. * @param evt optional action event
  56291. */
  56292. Action.prototype.execute = function (evt) {
  56293. };
  56294. /**
  56295. * Skips to next active action
  56296. */
  56297. Action.prototype.skipToNextActiveAction = function () {
  56298. if (this._nextActiveAction._child) {
  56299. if (!this._nextActiveAction._child._actionManager) {
  56300. this._nextActiveAction._child._actionManager = this._actionManager;
  56301. }
  56302. this._nextActiveAction = this._nextActiveAction._child;
  56303. }
  56304. else {
  56305. this._nextActiveAction = this;
  56306. }
  56307. };
  56308. /**
  56309. * Adds action to chain of actions, may be a DoNothingAction
  56310. * @param action defines the next action to execute
  56311. * @returns The action passed in
  56312. * @see https://www.babylonjs-playground.com/#1T30HR#0
  56313. */
  56314. Action.prototype.then = function (action) {
  56315. this._child = action;
  56316. action._actionManager = this._actionManager;
  56317. action._prepare();
  56318. return action;
  56319. };
  56320. /**
  56321. * Internal only
  56322. * @hidden
  56323. */
  56324. Action.prototype._getProperty = function (propertyPath) {
  56325. return this._actionManager._getProperty(propertyPath);
  56326. };
  56327. /**
  56328. * Internal only
  56329. * @hidden
  56330. */
  56331. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  56332. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56333. };
  56334. /**
  56335. * Serialize placeholder for child classes
  56336. * @param parent of child
  56337. * @returns the serialized object
  56338. */
  56339. Action.prototype.serialize = function (parent) {
  56340. };
  56341. /**
  56342. * Internal only called by serialize
  56343. * @hidden
  56344. */
  56345. Action.prototype._serialize = function (serializedAction, parent) {
  56346. var serializationObject = {
  56347. type: 1,
  56348. children: [],
  56349. name: serializedAction.name,
  56350. properties: serializedAction.properties || []
  56351. };
  56352. // Serialize child
  56353. if (this._child) {
  56354. this._child.serialize(serializationObject);
  56355. }
  56356. // Check if "this" has a condition
  56357. if (this._condition) {
  56358. var serializedCondition = this._condition.serialize();
  56359. serializedCondition.children.push(serializationObject);
  56360. if (parent) {
  56361. parent.children.push(serializedCondition);
  56362. }
  56363. return serializedCondition;
  56364. }
  56365. if (parent) {
  56366. parent.children.push(serializationObject);
  56367. }
  56368. return serializationObject;
  56369. };
  56370. /**
  56371. * Internal only
  56372. * @hidden
  56373. */
  56374. Action._SerializeValueAsString = function (value) {
  56375. if (typeof value === "number") {
  56376. return value.toString();
  56377. }
  56378. if (typeof value === "boolean") {
  56379. return value ? "true" : "false";
  56380. }
  56381. if (value instanceof BABYLON.Vector2) {
  56382. return value.x + ", " + value.y;
  56383. }
  56384. if (value instanceof BABYLON.Vector3) {
  56385. return value.x + ", " + value.y + ", " + value.z;
  56386. }
  56387. if (value instanceof BABYLON.Color3) {
  56388. return value.r + ", " + value.g + ", " + value.b;
  56389. }
  56390. if (value instanceof BABYLON.Color4) {
  56391. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  56392. }
  56393. return value; // string
  56394. };
  56395. /**
  56396. * Internal only
  56397. * @hidden
  56398. */
  56399. Action._GetTargetProperty = function (target) {
  56400. return {
  56401. name: "target",
  56402. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  56403. : target instanceof BABYLON.Light ? "LightProperties"
  56404. : target instanceof BABYLON.Camera ? "CameraProperties"
  56405. : "SceneProperties",
  56406. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  56407. };
  56408. };
  56409. return Action;
  56410. }());
  56411. BABYLON.Action = Action;
  56412. })(BABYLON || (BABYLON = {}));
  56413. //# sourceMappingURL=babylon.action.js.map
  56414. var BABYLON;
  56415. (function (BABYLON) {
  56416. /**
  56417. * ActionEvent is the event being sent when an action is triggered.
  56418. */
  56419. var ActionEvent = /** @class */ (function () {
  56420. /**
  56421. * Creates a new ActionEvent
  56422. * @param source The mesh or sprite that triggered the action
  56423. * @param pointerX The X mouse cursor position at the time of the event
  56424. * @param pointerY The Y mouse cursor position at the time of the event
  56425. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  56426. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  56427. * @param additionalData additional data for the event
  56428. */
  56429. function ActionEvent(
  56430. /** The mesh or sprite that triggered the action */
  56431. source,
  56432. /** The X mouse cursor position at the time of the event */
  56433. pointerX,
  56434. /** The Y mouse cursor position at the time of the event */
  56435. pointerY,
  56436. /** The mesh that is currently pointed at (can be null) */
  56437. meshUnderPointer,
  56438. /** the original (browser) event that triggered the ActionEvent */
  56439. sourceEvent,
  56440. /** additional data for the event */
  56441. additionalData) {
  56442. this.source = source;
  56443. this.pointerX = pointerX;
  56444. this.pointerY = pointerY;
  56445. this.meshUnderPointer = meshUnderPointer;
  56446. this.sourceEvent = sourceEvent;
  56447. this.additionalData = additionalData;
  56448. }
  56449. /**
  56450. * Helper function to auto-create an ActionEvent from a source mesh.
  56451. * @param source The source mesh that triggered the event
  56452. * @param evt The original (browser) event
  56453. * @param additionalData additional data for the event
  56454. * @returns the new ActionEvent
  56455. */
  56456. ActionEvent.CreateNew = function (source, evt, additionalData) {
  56457. var scene = source.getScene();
  56458. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56459. };
  56460. /**
  56461. * Helper function to auto-create an ActionEvent from a source sprite
  56462. * @param source The source sprite that triggered the event
  56463. * @param scene Scene associated with the sprite
  56464. * @param evt The original (browser) event
  56465. * @param additionalData additional data for the event
  56466. * @returns the new ActionEvent
  56467. */
  56468. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  56469. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56470. };
  56471. /**
  56472. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  56473. * @param scene the scene where the event occurred
  56474. * @param evt The original (browser) event
  56475. * @returns the new ActionEvent
  56476. */
  56477. ActionEvent.CreateNewFromScene = function (scene, evt) {
  56478. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  56479. };
  56480. /**
  56481. * Helper function to auto-create an ActionEvent from a primitive
  56482. * @param prim defines the target primitive
  56483. * @param pointerPos defines the pointer position
  56484. * @param evt The original (browser) event
  56485. * @param additionalData additional data for the event
  56486. * @returns the new ActionEvent
  56487. */
  56488. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  56489. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  56490. };
  56491. return ActionEvent;
  56492. }());
  56493. BABYLON.ActionEvent = ActionEvent;
  56494. /**
  56495. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  56496. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  56497. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56498. */
  56499. var ActionManager = /** @class */ (function () {
  56500. /**
  56501. * Creates a new action manager
  56502. * @param scene defines the hosting scene
  56503. */
  56504. function ActionManager(scene) {
  56505. // Members
  56506. /** Gets the list of actions */
  56507. this.actions = new Array();
  56508. /** Gets the cursor to use when hovering items */
  56509. this.hoverCursor = '';
  56510. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56511. scene.actionManagers.push(this);
  56512. }
  56513. // Methods
  56514. /**
  56515. * Releases all associated resources
  56516. */
  56517. ActionManager.prototype.dispose = function () {
  56518. var index = this._scene.actionManagers.indexOf(this);
  56519. for (var i = 0; i < this.actions.length; i++) {
  56520. var action = this.actions[i];
  56521. ActionManager.Triggers[action.trigger]--;
  56522. if (ActionManager.Triggers[action.trigger] === 0) {
  56523. delete ActionManager.Triggers[action.trigger];
  56524. }
  56525. }
  56526. if (index > -1) {
  56527. this._scene.actionManagers.splice(index, 1);
  56528. }
  56529. };
  56530. /**
  56531. * Gets hosting scene
  56532. * @returns the hosting scene
  56533. */
  56534. ActionManager.prototype.getScene = function () {
  56535. return this._scene;
  56536. };
  56537. /**
  56538. * Does this action manager handles actions of any of the given triggers
  56539. * @param triggers defines the triggers to be tested
  56540. * @return a boolean indicating whether one (or more) of the triggers is handled
  56541. */
  56542. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  56543. for (var index = 0; index < this.actions.length; index++) {
  56544. var action = this.actions[index];
  56545. if (triggers.indexOf(action.trigger) > -1) {
  56546. return true;
  56547. }
  56548. }
  56549. return false;
  56550. };
  56551. /**
  56552. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  56553. * speed.
  56554. * @param triggerA defines the trigger to be tested
  56555. * @param triggerB defines the trigger to be tested
  56556. * @return a boolean indicating whether one (or more) of the triggers is handled
  56557. */
  56558. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  56559. for (var index = 0; index < this.actions.length; index++) {
  56560. var action = this.actions[index];
  56561. if (triggerA == action.trigger || triggerB == action.trigger) {
  56562. return true;
  56563. }
  56564. }
  56565. return false;
  56566. };
  56567. /**
  56568. * Does this action manager handles actions of a given trigger
  56569. * @param trigger defines the trigger to be tested
  56570. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  56571. * @return whether the trigger is handled
  56572. */
  56573. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  56574. for (var index = 0; index < this.actions.length; index++) {
  56575. var action = this.actions[index];
  56576. if (action.trigger === trigger) {
  56577. if (parameterPredicate) {
  56578. if (parameterPredicate(action.getTriggerParameter())) {
  56579. return true;
  56580. }
  56581. }
  56582. else {
  56583. return true;
  56584. }
  56585. }
  56586. }
  56587. return false;
  56588. };
  56589. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  56590. /**
  56591. * Does this action manager has pointer triggers
  56592. */
  56593. get: function () {
  56594. for (var index = 0; index < this.actions.length; index++) {
  56595. var action = this.actions[index];
  56596. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  56597. return true;
  56598. }
  56599. }
  56600. return false;
  56601. },
  56602. enumerable: true,
  56603. configurable: true
  56604. });
  56605. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  56606. /**
  56607. * Does this action manager has pick triggers
  56608. */
  56609. get: function () {
  56610. for (var index = 0; index < this.actions.length; index++) {
  56611. var action = this.actions[index];
  56612. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  56613. return true;
  56614. }
  56615. }
  56616. return false;
  56617. },
  56618. enumerable: true,
  56619. configurable: true
  56620. });
  56621. Object.defineProperty(ActionManager, "HasTriggers", {
  56622. /**
  56623. * Does exist one action manager with at least one trigger
  56624. **/
  56625. get: function () {
  56626. for (var t in ActionManager.Triggers) {
  56627. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56628. return true;
  56629. }
  56630. }
  56631. return false;
  56632. },
  56633. enumerable: true,
  56634. configurable: true
  56635. });
  56636. Object.defineProperty(ActionManager, "HasPickTriggers", {
  56637. /**
  56638. * Does exist one action manager with at least one pick trigger
  56639. **/
  56640. get: function () {
  56641. for (var t in ActionManager.Triggers) {
  56642. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56643. var t_int = parseInt(t);
  56644. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  56645. return true;
  56646. }
  56647. }
  56648. }
  56649. return false;
  56650. },
  56651. enumerable: true,
  56652. configurable: true
  56653. });
  56654. /**
  56655. * Does exist one action manager that handles actions of a given trigger
  56656. * @param trigger defines the trigger to be tested
  56657. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  56658. **/
  56659. ActionManager.HasSpecificTrigger = function (trigger) {
  56660. for (var t in ActionManager.Triggers) {
  56661. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56662. var t_int = parseInt(t);
  56663. if (t_int === trigger) {
  56664. return true;
  56665. }
  56666. }
  56667. }
  56668. return false;
  56669. };
  56670. /**
  56671. * Registers an action to this action manager
  56672. * @param action defines the action to be registered
  56673. * @return the action amended (prepared) after registration
  56674. */
  56675. ActionManager.prototype.registerAction = function (action) {
  56676. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  56677. if (this.getScene().actionManager !== this) {
  56678. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  56679. return null;
  56680. }
  56681. }
  56682. this.actions.push(action);
  56683. if (ActionManager.Triggers[action.trigger]) {
  56684. ActionManager.Triggers[action.trigger]++;
  56685. }
  56686. else {
  56687. ActionManager.Triggers[action.trigger] = 1;
  56688. }
  56689. action._actionManager = this;
  56690. action._prepare();
  56691. return action;
  56692. };
  56693. /**
  56694. * Unregisters an action to this action manager
  56695. * @param action defines the action to be unregistered
  56696. * @return a boolean indicating whether the action has been unregistered
  56697. */
  56698. ActionManager.prototype.unregisterAction = function (action) {
  56699. var index = this.actions.indexOf(action);
  56700. if (index !== -1) {
  56701. this.actions.splice(index, 1);
  56702. ActionManager.Triggers[action.trigger] -= 1;
  56703. if (ActionManager.Triggers[action.trigger] === 0) {
  56704. delete ActionManager.Triggers[action.trigger];
  56705. }
  56706. delete action._actionManager;
  56707. return true;
  56708. }
  56709. return false;
  56710. };
  56711. /**
  56712. * Process a specific trigger
  56713. * @param trigger defines the trigger to process
  56714. * @param evt defines the event details to be processed
  56715. */
  56716. ActionManager.prototype.processTrigger = function (trigger, evt) {
  56717. for (var index = 0; index < this.actions.length; index++) {
  56718. var action = this.actions[index];
  56719. if (action.trigger === trigger) {
  56720. if (evt) {
  56721. if (trigger === ActionManager.OnKeyUpTrigger
  56722. || trigger === ActionManager.OnKeyDownTrigger) {
  56723. var parameter = action.getTriggerParameter();
  56724. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  56725. if (!parameter.toLowerCase) {
  56726. continue;
  56727. }
  56728. var lowerCase = parameter.toLowerCase();
  56729. if (lowerCase !== evt.sourceEvent.key) {
  56730. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  56731. var actualkey = String.fromCharCode(unicode).toLowerCase();
  56732. if (actualkey !== lowerCase) {
  56733. continue;
  56734. }
  56735. }
  56736. }
  56737. }
  56738. }
  56739. action._executeCurrent(evt);
  56740. }
  56741. }
  56742. };
  56743. /** @hidden */
  56744. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  56745. var properties = propertyPath.split(".");
  56746. for (var index = 0; index < properties.length - 1; index++) {
  56747. target = target[properties[index]];
  56748. }
  56749. return target;
  56750. };
  56751. /** @hidden */
  56752. ActionManager.prototype._getProperty = function (propertyPath) {
  56753. var properties = propertyPath.split(".");
  56754. return properties[properties.length - 1];
  56755. };
  56756. /**
  56757. * Serialize this manager to a JSON object
  56758. * @param name defines the property name to store this manager
  56759. * @returns a JSON representation of this manager
  56760. */
  56761. ActionManager.prototype.serialize = function (name) {
  56762. var root = {
  56763. children: new Array(),
  56764. name: name,
  56765. type: 3,
  56766. properties: new Array() // Empty for root but required
  56767. };
  56768. for (var i = 0; i < this.actions.length; i++) {
  56769. var triggerObject = {
  56770. type: 0,
  56771. children: new Array(),
  56772. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  56773. properties: new Array()
  56774. };
  56775. var triggerOptions = this.actions[i].triggerOptions;
  56776. if (triggerOptions && typeof triggerOptions !== "number") {
  56777. if (triggerOptions.parameter instanceof BABYLON.Node) {
  56778. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  56779. }
  56780. else {
  56781. var parameter = {};
  56782. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  56783. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  56784. parameter._meshId = triggerOptions.parameter.mesh.id;
  56785. }
  56786. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  56787. }
  56788. }
  56789. // Serialize child action, recursively
  56790. this.actions[i].serialize(triggerObject);
  56791. // Add serialized trigger
  56792. root.children.push(triggerObject);
  56793. }
  56794. return root;
  56795. };
  56796. /**
  56797. * Creates a new ActionManager from a JSON data
  56798. * @param parsedActions defines the JSON data to read from
  56799. * @param object defines the hosting mesh
  56800. * @param scene defines the hosting scene
  56801. */
  56802. ActionManager.Parse = function (parsedActions, object, scene) {
  56803. var actionManager = new ActionManager(scene);
  56804. if (object === null) {
  56805. scene.actionManager = actionManager;
  56806. }
  56807. else {
  56808. object.actionManager = actionManager;
  56809. }
  56810. // instanciate a new object
  56811. var instanciate = function (name, params) {
  56812. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  56813. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  56814. newInstance.constructor.apply(newInstance, params);
  56815. return newInstance;
  56816. };
  56817. var parseParameter = function (name, value, target, propertyPath) {
  56818. if (propertyPath === null) {
  56819. // String, boolean or float
  56820. var floatValue = parseFloat(value);
  56821. if (value === "true" || value === "false") {
  56822. return value === "true";
  56823. }
  56824. else {
  56825. return isNaN(floatValue) ? value : floatValue;
  56826. }
  56827. }
  56828. var effectiveTarget = propertyPath.split(".");
  56829. var values = value.split(",");
  56830. // Get effective Target
  56831. for (var i = 0; i < effectiveTarget.length; i++) {
  56832. target = target[effectiveTarget[i]];
  56833. }
  56834. // Return appropriate value with its type
  56835. if (typeof (target) === "boolean") {
  56836. return values[0] === "true";
  56837. }
  56838. if (typeof (target) === "string") {
  56839. return values[0];
  56840. }
  56841. // Parameters with multiple values such as Vector3 etc.
  56842. var split = new Array();
  56843. for (var i = 0; i < values.length; i++) {
  56844. split.push(parseFloat(values[i]));
  56845. }
  56846. if (target instanceof BABYLON.Vector3) {
  56847. return BABYLON.Vector3.FromArray(split);
  56848. }
  56849. if (target instanceof BABYLON.Vector4) {
  56850. return BABYLON.Vector4.FromArray(split);
  56851. }
  56852. if (target instanceof BABYLON.Color3) {
  56853. return BABYLON.Color3.FromArray(split);
  56854. }
  56855. if (target instanceof BABYLON.Color4) {
  56856. return BABYLON.Color4.FromArray(split);
  56857. }
  56858. return parseFloat(values[0]);
  56859. };
  56860. // traverse graph per trigger
  56861. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  56862. if (combineArray === void 0) { combineArray = null; }
  56863. if (parsedAction.detached) {
  56864. return;
  56865. }
  56866. var parameters = new Array();
  56867. var target = null;
  56868. var propertyPath = null;
  56869. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  56870. // Parameters
  56871. if (parsedAction.type === 2) {
  56872. parameters.push(actionManager);
  56873. }
  56874. else {
  56875. parameters.push(trigger);
  56876. }
  56877. if (combine) {
  56878. var actions = new Array();
  56879. for (var j = 0; j < parsedAction.combine.length; j++) {
  56880. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  56881. }
  56882. parameters.push(actions);
  56883. }
  56884. else {
  56885. for (var i = 0; i < parsedAction.properties.length; i++) {
  56886. var value = parsedAction.properties[i].value;
  56887. var name = parsedAction.properties[i].name;
  56888. var targetType = parsedAction.properties[i].targetType;
  56889. if (name === "target") {
  56890. if (targetType !== null && targetType === "SceneProperties") {
  56891. value = target = scene;
  56892. }
  56893. else {
  56894. value = target = scene.getNodeByName(value);
  56895. }
  56896. }
  56897. else if (name === "parent") {
  56898. value = scene.getNodeByName(value);
  56899. }
  56900. else if (name === "sound") {
  56901. // Can not externalize to component, so only checks for the presence off the API.
  56902. if (scene.getSoundByName) {
  56903. value = scene.getSoundByName(value);
  56904. }
  56905. }
  56906. else if (name !== "propertyPath") {
  56907. if (parsedAction.type === 2 && name === "operator") {
  56908. value = BABYLON.ValueCondition[value];
  56909. }
  56910. else {
  56911. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  56912. }
  56913. }
  56914. else {
  56915. propertyPath = value;
  56916. }
  56917. parameters.push(value);
  56918. }
  56919. }
  56920. if (combineArray === null) {
  56921. parameters.push(condition);
  56922. }
  56923. else {
  56924. parameters.push(null);
  56925. }
  56926. // If interpolate value action
  56927. if (parsedAction.name === "InterpolateValueAction") {
  56928. var param = parameters[parameters.length - 2];
  56929. parameters[parameters.length - 1] = param;
  56930. parameters[parameters.length - 2] = condition;
  56931. }
  56932. // Action or condition(s) and not CombineAction
  56933. var newAction = instanciate(parsedAction.name, parameters);
  56934. if (newAction instanceof BABYLON.Condition && condition !== null) {
  56935. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  56936. if (action) {
  56937. action.then(nothing);
  56938. }
  56939. else {
  56940. actionManager.registerAction(nothing);
  56941. }
  56942. action = nothing;
  56943. }
  56944. if (combineArray === null) {
  56945. if (newAction instanceof BABYLON.Condition) {
  56946. condition = newAction;
  56947. newAction = action;
  56948. }
  56949. else {
  56950. condition = null;
  56951. if (action) {
  56952. action.then(newAction);
  56953. }
  56954. else {
  56955. actionManager.registerAction(newAction);
  56956. }
  56957. }
  56958. }
  56959. else {
  56960. combineArray.push(newAction);
  56961. }
  56962. for (var i = 0; i < parsedAction.children.length; i++) {
  56963. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  56964. }
  56965. };
  56966. // triggers
  56967. for (var i = 0; i < parsedActions.children.length; i++) {
  56968. var triggerParams;
  56969. var trigger = parsedActions.children[i];
  56970. if (trigger.properties.length > 0) {
  56971. var param = trigger.properties[0].value;
  56972. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  56973. if (value._meshId) {
  56974. value.mesh = scene.getMeshByID(value._meshId);
  56975. }
  56976. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  56977. }
  56978. else {
  56979. triggerParams = ActionManager[trigger.name];
  56980. }
  56981. for (var j = 0; j < trigger.children.length; j++) {
  56982. if (!trigger.detached) {
  56983. traverse(trigger.children[j], triggerParams, null, null);
  56984. }
  56985. }
  56986. }
  56987. };
  56988. /**
  56989. * Get a trigger name by index
  56990. * @param trigger defines the trigger index
  56991. * @returns a trigger name
  56992. */
  56993. ActionManager.GetTriggerName = function (trigger) {
  56994. switch (trigger) {
  56995. case 0: return "NothingTrigger";
  56996. case 1: return "OnPickTrigger";
  56997. case 2: return "OnLeftPickTrigger";
  56998. case 3: return "OnRightPickTrigger";
  56999. case 4: return "OnCenterPickTrigger";
  57000. case 5: return "OnPickDownTrigger";
  57001. case 6: return "OnPickUpTrigger";
  57002. case 7: return "OnLongPressTrigger";
  57003. case 8: return "OnPointerOverTrigger";
  57004. case 9: return "OnPointerOutTrigger";
  57005. case 10: return "OnEveryFrameTrigger";
  57006. case 11: return "OnIntersectionEnterTrigger";
  57007. case 12: return "OnIntersectionExitTrigger";
  57008. case 13: return "OnKeyDownTrigger";
  57009. case 14: return "OnKeyUpTrigger";
  57010. case 15: return "OnPickOutTrigger";
  57011. default: return "";
  57012. }
  57013. };
  57014. /**
  57015. * Nothing
  57016. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57017. */
  57018. ActionManager.NothingTrigger = 0;
  57019. /**
  57020. * On pick
  57021. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57022. */
  57023. ActionManager.OnPickTrigger = 1;
  57024. /**
  57025. * On left pick
  57026. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57027. */
  57028. ActionManager.OnLeftPickTrigger = 2;
  57029. /**
  57030. * On right pick
  57031. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57032. */
  57033. ActionManager.OnRightPickTrigger = 3;
  57034. /**
  57035. * On center pick
  57036. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57037. */
  57038. ActionManager.OnCenterPickTrigger = 4;
  57039. /**
  57040. * On pick down
  57041. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57042. */
  57043. ActionManager.OnPickDownTrigger = 5;
  57044. /**
  57045. * On double pick
  57046. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57047. */
  57048. ActionManager.OnDoublePickTrigger = 6;
  57049. /**
  57050. * On pick up
  57051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57052. */
  57053. ActionManager.OnPickUpTrigger = 7;
  57054. /**
  57055. * On pick out.
  57056. * This trigger will only be raised if you also declared a OnPickDown
  57057. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57058. */
  57059. ActionManager.OnPickOutTrigger = 16;
  57060. /**
  57061. * On long press
  57062. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57063. */
  57064. ActionManager.OnLongPressTrigger = 8;
  57065. /**
  57066. * On pointer over
  57067. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57068. */
  57069. ActionManager.OnPointerOverTrigger = 9;
  57070. /**
  57071. * On pointer out
  57072. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57073. */
  57074. ActionManager.OnPointerOutTrigger = 10;
  57075. /**
  57076. * On every frame
  57077. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57078. */
  57079. ActionManager.OnEveryFrameTrigger = 11;
  57080. /**
  57081. * On intersection enter
  57082. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57083. */
  57084. ActionManager.OnIntersectionEnterTrigger = 12;
  57085. /**
  57086. * On intersection exit
  57087. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57088. */
  57089. ActionManager.OnIntersectionExitTrigger = 13;
  57090. /**
  57091. * On key down
  57092. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57093. */
  57094. ActionManager.OnKeyDownTrigger = 14;
  57095. /**
  57096. * On key up
  57097. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57098. */
  57099. ActionManager.OnKeyUpTrigger = 15;
  57100. /** Gets the list of active triggers */
  57101. ActionManager.Triggers = {};
  57102. return ActionManager;
  57103. }());
  57104. BABYLON.ActionManager = ActionManager;
  57105. })(BABYLON || (BABYLON = {}));
  57106. //# sourceMappingURL=babylon.actionManager.js.map
  57107. var BABYLON;
  57108. (function (BABYLON) {
  57109. /**
  57110. * This defines an action responsible to change the value of a property
  57111. * by interpolating between its current value and the newly set one once triggered.
  57112. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57113. */
  57114. var InterpolateValueAction = /** @class */ (function (_super) {
  57115. __extends(InterpolateValueAction, _super);
  57116. /**
  57117. * Instantiate the action
  57118. * @param triggerOptions defines the trigger options
  57119. * @param target defines the object containing the value to interpolate
  57120. * @param propertyPath defines the path to the property in the target object
  57121. * @param value defines the target value at the end of the interpolation
  57122. * @param duration deines the time it will take for the property to interpolate to the value.
  57123. * @param condition defines the trigger related conditions
  57124. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57125. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57126. */
  57127. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57128. if (duration === void 0) { duration = 1000; }
  57129. var _this = _super.call(this, triggerOptions, condition) || this;
  57130. /**
  57131. * Defines the time it will take for the property to interpolate to the value.
  57132. */
  57133. _this.duration = 1000;
  57134. /**
  57135. * Observable triggered once the interpolation animation has been done.
  57136. */
  57137. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57138. _this.propertyPath = propertyPath;
  57139. _this.value = value;
  57140. _this.duration = duration;
  57141. _this.stopOtherAnimations = stopOtherAnimations;
  57142. _this.onInterpolationDone = onInterpolationDone;
  57143. _this._target = _this._effectiveTarget = target;
  57144. return _this;
  57145. }
  57146. /** @hidden */
  57147. InterpolateValueAction.prototype._prepare = function () {
  57148. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57149. this._property = this._getProperty(this.propertyPath);
  57150. };
  57151. /**
  57152. * Execute the action starts the value interpolation.
  57153. */
  57154. InterpolateValueAction.prototype.execute = function () {
  57155. var _this = this;
  57156. var scene = this._actionManager.getScene();
  57157. var keys = [
  57158. {
  57159. frame: 0,
  57160. value: this._effectiveTarget[this._property]
  57161. }, {
  57162. frame: 100,
  57163. value: this.value
  57164. }
  57165. ];
  57166. var dataType;
  57167. if (typeof this.value === "number") {
  57168. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57169. }
  57170. else if (this.value instanceof BABYLON.Color3) {
  57171. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57172. }
  57173. else if (this.value instanceof BABYLON.Vector3) {
  57174. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57175. }
  57176. else if (this.value instanceof BABYLON.Matrix) {
  57177. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57178. }
  57179. else if (this.value instanceof BABYLON.Quaternion) {
  57180. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57181. }
  57182. else {
  57183. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57184. return;
  57185. }
  57186. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57187. animation.setKeys(keys);
  57188. if (this.stopOtherAnimations) {
  57189. scene.stopAnimation(this._effectiveTarget);
  57190. }
  57191. var wrapper = function () {
  57192. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57193. if (_this.onInterpolationDone) {
  57194. _this.onInterpolationDone();
  57195. }
  57196. };
  57197. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57198. };
  57199. /**
  57200. * Serializes the actions and its related information.
  57201. * @param parent defines the object to serialize in
  57202. * @returns the serialized object
  57203. */
  57204. InterpolateValueAction.prototype.serialize = function (parent) {
  57205. return _super.prototype._serialize.call(this, {
  57206. name: "InterpolateValueAction",
  57207. properties: [
  57208. BABYLON.Action._GetTargetProperty(this._target),
  57209. { name: "propertyPath", value: this.propertyPath },
  57210. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  57211. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  57212. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  57213. ]
  57214. }, parent);
  57215. };
  57216. return InterpolateValueAction;
  57217. }(BABYLON.Action));
  57218. BABYLON.InterpolateValueAction = InterpolateValueAction;
  57219. })(BABYLON || (BABYLON = {}));
  57220. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  57221. var BABYLON;
  57222. (function (BABYLON) {
  57223. /**
  57224. * This defines an action responsible to toggle a boolean once triggered.
  57225. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57226. */
  57227. var SwitchBooleanAction = /** @class */ (function (_super) {
  57228. __extends(SwitchBooleanAction, _super);
  57229. /**
  57230. * Instantiate the action
  57231. * @param triggerOptions defines the trigger options
  57232. * @param target defines the object containing the boolean
  57233. * @param propertyPath defines the path to the boolean property in the target object
  57234. * @param condition defines the trigger related conditions
  57235. */
  57236. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  57237. var _this = _super.call(this, triggerOptions, condition) || this;
  57238. _this.propertyPath = propertyPath;
  57239. _this._target = _this._effectiveTarget = target;
  57240. return _this;
  57241. }
  57242. /** @hidden */
  57243. SwitchBooleanAction.prototype._prepare = function () {
  57244. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57245. this._property = this._getProperty(this.propertyPath);
  57246. };
  57247. /**
  57248. * Execute the action toggle the boolean value.
  57249. */
  57250. SwitchBooleanAction.prototype.execute = function () {
  57251. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  57252. };
  57253. /**
  57254. * Serializes the actions and its related information.
  57255. * @param parent defines the object to serialize in
  57256. * @returns the serialized object
  57257. */
  57258. SwitchBooleanAction.prototype.serialize = function (parent) {
  57259. return _super.prototype._serialize.call(this, {
  57260. name: "SwitchBooleanAction",
  57261. properties: [
  57262. BABYLON.Action._GetTargetProperty(this._target),
  57263. { name: "propertyPath", value: this.propertyPath }
  57264. ]
  57265. }, parent);
  57266. };
  57267. return SwitchBooleanAction;
  57268. }(BABYLON.Action));
  57269. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  57270. /**
  57271. * This defines an action responsible to set a the state field of the target
  57272. * to a desired value once triggered.
  57273. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57274. */
  57275. var SetStateAction = /** @class */ (function (_super) {
  57276. __extends(SetStateAction, _super);
  57277. /**
  57278. * Instantiate the action
  57279. * @param triggerOptions defines the trigger options
  57280. * @param target defines the object containing the state property
  57281. * @param value defines the value to store in the state field
  57282. * @param condition defines the trigger related conditions
  57283. */
  57284. function SetStateAction(triggerOptions, target, value, condition) {
  57285. var _this = _super.call(this, triggerOptions, condition) || this;
  57286. _this.value = value;
  57287. _this._target = target;
  57288. return _this;
  57289. }
  57290. /**
  57291. * Execute the action and store the value on the target state property.
  57292. */
  57293. SetStateAction.prototype.execute = function () {
  57294. this._target.state = this.value;
  57295. };
  57296. /**
  57297. * Serializes the actions and its related information.
  57298. * @param parent defines the object to serialize in
  57299. * @returns the serialized object
  57300. */
  57301. SetStateAction.prototype.serialize = function (parent) {
  57302. return _super.prototype._serialize.call(this, {
  57303. name: "SetStateAction",
  57304. properties: [
  57305. BABYLON.Action._GetTargetProperty(this._target),
  57306. { name: "value", value: this.value }
  57307. ]
  57308. }, parent);
  57309. };
  57310. return SetStateAction;
  57311. }(BABYLON.Action));
  57312. BABYLON.SetStateAction = SetStateAction;
  57313. /**
  57314. * This defines an action responsible to set a property of the target
  57315. * to a desired value once triggered.
  57316. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57317. */
  57318. var SetValueAction = /** @class */ (function (_super) {
  57319. __extends(SetValueAction, _super);
  57320. /**
  57321. * Instantiate the action
  57322. * @param triggerOptions defines the trigger options
  57323. * @param target defines the object containing the property
  57324. * @param propertyPath defines the path of the property to set in the target
  57325. * @param value defines the value to set in the property
  57326. * @param condition defines the trigger related conditions
  57327. */
  57328. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  57329. var _this = _super.call(this, triggerOptions, condition) || this;
  57330. _this.propertyPath = propertyPath;
  57331. _this.value = value;
  57332. _this._target = _this._effectiveTarget = target;
  57333. return _this;
  57334. }
  57335. /** @hidden */
  57336. SetValueAction.prototype._prepare = function () {
  57337. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57338. this._property = this._getProperty(this.propertyPath);
  57339. };
  57340. /**
  57341. * Execute the action and set the targetted property to the desired value.
  57342. */
  57343. SetValueAction.prototype.execute = function () {
  57344. this._effectiveTarget[this._property] = this.value;
  57345. if (this._target.markAsDirty) {
  57346. this._target.markAsDirty(this._property);
  57347. }
  57348. };
  57349. /**
  57350. * Serializes the actions and its related information.
  57351. * @param parent defines the object to serialize in
  57352. * @returns the serialized object
  57353. */
  57354. SetValueAction.prototype.serialize = function (parent) {
  57355. return _super.prototype._serialize.call(this, {
  57356. name: "SetValueAction",
  57357. properties: [
  57358. BABYLON.Action._GetTargetProperty(this._target),
  57359. { name: "propertyPath", value: this.propertyPath },
  57360. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57361. ]
  57362. }, parent);
  57363. };
  57364. return SetValueAction;
  57365. }(BABYLON.Action));
  57366. BABYLON.SetValueAction = SetValueAction;
  57367. /**
  57368. * This defines an action responsible to increment the target value
  57369. * to a desired value once triggered.
  57370. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57371. */
  57372. var IncrementValueAction = /** @class */ (function (_super) {
  57373. __extends(IncrementValueAction, _super);
  57374. /**
  57375. * Instantiate the action
  57376. * @param triggerOptions defines the trigger options
  57377. * @param target defines the object containing the property
  57378. * @param propertyPath defines the path of the property to increment in the target
  57379. * @param value defines the value value we should increment the property by
  57380. * @param condition defines the trigger related conditions
  57381. */
  57382. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  57383. var _this = _super.call(this, triggerOptions, condition) || this;
  57384. _this.propertyPath = propertyPath;
  57385. _this.value = value;
  57386. _this._target = _this._effectiveTarget = target;
  57387. return _this;
  57388. }
  57389. /** @hidden */
  57390. IncrementValueAction.prototype._prepare = function () {
  57391. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57392. this._property = this._getProperty(this.propertyPath);
  57393. if (typeof this._effectiveTarget[this._property] !== "number") {
  57394. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  57395. }
  57396. };
  57397. /**
  57398. * Execute the action and increment the target of the value amount.
  57399. */
  57400. IncrementValueAction.prototype.execute = function () {
  57401. this._effectiveTarget[this._property] += this.value;
  57402. if (this._target.markAsDirty) {
  57403. this._target.markAsDirty(this._property);
  57404. }
  57405. };
  57406. /**
  57407. * Serializes the actions and its related information.
  57408. * @param parent defines the object to serialize in
  57409. * @returns the serialized object
  57410. */
  57411. IncrementValueAction.prototype.serialize = function (parent) {
  57412. return _super.prototype._serialize.call(this, {
  57413. name: "IncrementValueAction",
  57414. properties: [
  57415. BABYLON.Action._GetTargetProperty(this._target),
  57416. { name: "propertyPath", value: this.propertyPath },
  57417. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57418. ]
  57419. }, parent);
  57420. };
  57421. return IncrementValueAction;
  57422. }(BABYLON.Action));
  57423. BABYLON.IncrementValueAction = IncrementValueAction;
  57424. /**
  57425. * This defines an action responsible to start an animation once triggered.
  57426. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57427. */
  57428. var PlayAnimationAction = /** @class */ (function (_super) {
  57429. __extends(PlayAnimationAction, _super);
  57430. /**
  57431. * Instantiate the action
  57432. * @param triggerOptions defines the trigger options
  57433. * @param target defines the target animation or animation name
  57434. * @param from defines from where the animation should start (animation frame)
  57435. * @param end defines where the animation should stop (animation frame)
  57436. * @param loop defines if the animation should loop or stop after the first play
  57437. * @param condition defines the trigger related conditions
  57438. */
  57439. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  57440. var _this = _super.call(this, triggerOptions, condition) || this;
  57441. _this.from = from;
  57442. _this.to = to;
  57443. _this.loop = loop;
  57444. _this._target = target;
  57445. return _this;
  57446. }
  57447. /** @hidden */
  57448. PlayAnimationAction.prototype._prepare = function () {
  57449. };
  57450. /**
  57451. * Execute the action and play the animation.
  57452. */
  57453. PlayAnimationAction.prototype.execute = function () {
  57454. var scene = this._actionManager.getScene();
  57455. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  57456. };
  57457. /**
  57458. * Serializes the actions and its related information.
  57459. * @param parent defines the object to serialize in
  57460. * @returns the serialized object
  57461. */
  57462. PlayAnimationAction.prototype.serialize = function (parent) {
  57463. return _super.prototype._serialize.call(this, {
  57464. name: "PlayAnimationAction",
  57465. properties: [
  57466. BABYLON.Action._GetTargetProperty(this._target),
  57467. { name: "from", value: String(this.from) },
  57468. { name: "to", value: String(this.to) },
  57469. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  57470. ]
  57471. }, parent);
  57472. };
  57473. return PlayAnimationAction;
  57474. }(BABYLON.Action));
  57475. BABYLON.PlayAnimationAction = PlayAnimationAction;
  57476. /**
  57477. * This defines an action responsible to stop an animation once triggered.
  57478. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57479. */
  57480. var StopAnimationAction = /** @class */ (function (_super) {
  57481. __extends(StopAnimationAction, _super);
  57482. /**
  57483. * Instantiate the action
  57484. * @param triggerOptions defines the trigger options
  57485. * @param target defines the target animation or animation name
  57486. * @param condition defines the trigger related conditions
  57487. */
  57488. function StopAnimationAction(triggerOptions, target, condition) {
  57489. var _this = _super.call(this, triggerOptions, condition) || this;
  57490. _this._target = target;
  57491. return _this;
  57492. }
  57493. /** @hidden */
  57494. StopAnimationAction.prototype._prepare = function () {
  57495. };
  57496. /**
  57497. * Execute the action and stop the animation.
  57498. */
  57499. StopAnimationAction.prototype.execute = function () {
  57500. var scene = this._actionManager.getScene();
  57501. scene.stopAnimation(this._target);
  57502. };
  57503. /**
  57504. * Serializes the actions and its related information.
  57505. * @param parent defines the object to serialize in
  57506. * @returns the serialized object
  57507. */
  57508. StopAnimationAction.prototype.serialize = function (parent) {
  57509. return _super.prototype._serialize.call(this, {
  57510. name: "StopAnimationAction",
  57511. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  57512. }, parent);
  57513. };
  57514. return StopAnimationAction;
  57515. }(BABYLON.Action));
  57516. BABYLON.StopAnimationAction = StopAnimationAction;
  57517. /**
  57518. * This defines an action responsible that does nothing once triggered.
  57519. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57520. */
  57521. var DoNothingAction = /** @class */ (function (_super) {
  57522. __extends(DoNothingAction, _super);
  57523. /**
  57524. * Instantiate the action
  57525. * @param triggerOptions defines the trigger options
  57526. * @param condition defines the trigger related conditions
  57527. */
  57528. function DoNothingAction(triggerOptions, condition) {
  57529. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  57530. return _super.call(this, triggerOptions, condition) || this;
  57531. }
  57532. /**
  57533. * Execute the action and do nothing.
  57534. */
  57535. DoNothingAction.prototype.execute = function () {
  57536. };
  57537. /**
  57538. * Serializes the actions and its related information.
  57539. * @param parent defines the object to serialize in
  57540. * @returns the serialized object
  57541. */
  57542. DoNothingAction.prototype.serialize = function (parent) {
  57543. return _super.prototype._serialize.call(this, {
  57544. name: "DoNothingAction",
  57545. properties: []
  57546. }, parent);
  57547. };
  57548. return DoNothingAction;
  57549. }(BABYLON.Action));
  57550. BABYLON.DoNothingAction = DoNothingAction;
  57551. /**
  57552. * This defines an action responsible to trigger several actions once triggered.
  57553. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57554. */
  57555. var CombineAction = /** @class */ (function (_super) {
  57556. __extends(CombineAction, _super);
  57557. /**
  57558. * Instantiate the action
  57559. * @param triggerOptions defines the trigger options
  57560. * @param children defines the list of aggregated animations to run
  57561. * @param condition defines the trigger related conditions
  57562. */
  57563. function CombineAction(triggerOptions, children, condition) {
  57564. var _this = _super.call(this, triggerOptions, condition) || this;
  57565. _this.children = children;
  57566. return _this;
  57567. }
  57568. /** @hidden */
  57569. CombineAction.prototype._prepare = function () {
  57570. for (var index = 0; index < this.children.length; index++) {
  57571. this.children[index]._actionManager = this._actionManager;
  57572. this.children[index]._prepare();
  57573. }
  57574. };
  57575. /**
  57576. * Execute the action and executes all the aggregated actions.
  57577. */
  57578. CombineAction.prototype.execute = function (evt) {
  57579. for (var index = 0; index < this.children.length; index++) {
  57580. this.children[index].execute(evt);
  57581. }
  57582. };
  57583. /**
  57584. * Serializes the actions and its related information.
  57585. * @param parent defines the object to serialize in
  57586. * @returns the serialized object
  57587. */
  57588. CombineAction.prototype.serialize = function (parent) {
  57589. var serializationObject = _super.prototype._serialize.call(this, {
  57590. name: "CombineAction",
  57591. properties: [],
  57592. combine: []
  57593. }, parent);
  57594. for (var i = 0; i < this.children.length; i++) {
  57595. serializationObject.combine.push(this.children[i].serialize(null));
  57596. }
  57597. return serializationObject;
  57598. };
  57599. return CombineAction;
  57600. }(BABYLON.Action));
  57601. BABYLON.CombineAction = CombineAction;
  57602. /**
  57603. * This defines an action responsible to run code (external event) once triggered.
  57604. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57605. */
  57606. var ExecuteCodeAction = /** @class */ (function (_super) {
  57607. __extends(ExecuteCodeAction, _super);
  57608. /**
  57609. * Instantiate the action
  57610. * @param triggerOptions defines the trigger options
  57611. * @param func defines the callback function to run
  57612. * @param condition defines the trigger related conditions
  57613. */
  57614. function ExecuteCodeAction(triggerOptions, func, condition) {
  57615. var _this = _super.call(this, triggerOptions, condition) || this;
  57616. _this.func = func;
  57617. return _this;
  57618. }
  57619. /**
  57620. * Execute the action and run the attached code.
  57621. */
  57622. ExecuteCodeAction.prototype.execute = function (evt) {
  57623. this.func(evt);
  57624. };
  57625. return ExecuteCodeAction;
  57626. }(BABYLON.Action));
  57627. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  57628. /**
  57629. * This defines an action responsible to set the parent property of the target once triggered.
  57630. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57631. */
  57632. var SetParentAction = /** @class */ (function (_super) {
  57633. __extends(SetParentAction, _super);
  57634. /**
  57635. * Instantiate the action
  57636. * @param triggerOptions defines the trigger options
  57637. * @param target defines the target containing the parent property
  57638. * @param parent defines from where the animation should start (animation frame)
  57639. * @param condition defines the trigger related conditions
  57640. */
  57641. function SetParentAction(triggerOptions, target, parent, condition) {
  57642. var _this = _super.call(this, triggerOptions, condition) || this;
  57643. _this._target = target;
  57644. _this._parent = parent;
  57645. return _this;
  57646. }
  57647. /** @hidden */
  57648. SetParentAction.prototype._prepare = function () {
  57649. };
  57650. /**
  57651. * Execute the action and set the parent property.
  57652. */
  57653. SetParentAction.prototype.execute = function () {
  57654. if (this._target.parent === this._parent) {
  57655. return;
  57656. }
  57657. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  57658. invertParentWorldMatrix.invert();
  57659. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  57660. this._target.parent = this._parent;
  57661. };
  57662. /**
  57663. * Serializes the actions and its related information.
  57664. * @param parent defines the object to serialize in
  57665. * @returns the serialized object
  57666. */
  57667. SetParentAction.prototype.serialize = function (parent) {
  57668. return _super.prototype._serialize.call(this, {
  57669. name: "SetParentAction",
  57670. properties: [
  57671. BABYLON.Action._GetTargetProperty(this._target),
  57672. BABYLON.Action._GetTargetProperty(this._parent),
  57673. ]
  57674. }, parent);
  57675. };
  57676. return SetParentAction;
  57677. }(BABYLON.Action));
  57678. BABYLON.SetParentAction = SetParentAction;
  57679. })(BABYLON || (BABYLON = {}));
  57680. //# sourceMappingURL=babylon.directActions.js.map
  57681. var BABYLON;
  57682. (function (BABYLON) {
  57683. /**
  57684. * Class used to manage multiple sprites on the same spritesheet
  57685. * @see http://doc.babylonjs.com/babylon101/sprites
  57686. */
  57687. var SpriteManager = /** @class */ (function () {
  57688. /**
  57689. * Creates a new sprite manager
  57690. * @param name defines the manager's name
  57691. * @param imgUrl defines the sprite sheet url
  57692. * @param capacity defines the maximum allowed number of sprites
  57693. * @param cellSize defines the size of a sprite cell
  57694. * @param scene defines the hosting scene
  57695. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  57696. * @param samplingMode defines the smapling mode to use with spritesheet
  57697. */
  57698. function SpriteManager(
  57699. /** defines the manager's name */
  57700. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  57701. if (epsilon === void 0) { epsilon = 0.01; }
  57702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57703. this.name = name;
  57704. /** Gets the list of sprites */
  57705. this.sprites = new Array();
  57706. /** Gets or sets the rendering group id (0 by default) */
  57707. this.renderingGroupId = 0;
  57708. /** Gets or sets camera layer mask */
  57709. this.layerMask = 0x0FFFFFFF;
  57710. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  57711. this.fogEnabled = true;
  57712. /** Gets or sets a boolean indicating if the sprites are pickable */
  57713. this.isPickable = false;
  57714. /**
  57715. * An event triggered when the manager is disposed.
  57716. */
  57717. this.onDisposeObservable = new BABYLON.Observable();
  57718. this._vertexBuffers = {};
  57719. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  57720. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  57721. }
  57722. this._capacity = capacity;
  57723. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  57724. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57725. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57726. if (cellSize.width && cellSize.height) {
  57727. this.cellWidth = cellSize.width;
  57728. this.cellHeight = cellSize.height;
  57729. }
  57730. else if (cellSize !== undefined) {
  57731. this.cellWidth = cellSize;
  57732. this.cellHeight = cellSize;
  57733. }
  57734. else {
  57735. return;
  57736. }
  57737. this._epsilon = epsilon;
  57738. this._scene = scene;
  57739. this._scene.spriteManagers.push(this);
  57740. var indices = [];
  57741. var index = 0;
  57742. for (var count = 0; count < capacity; count++) {
  57743. indices.push(index);
  57744. indices.push(index + 1);
  57745. indices.push(index + 2);
  57746. indices.push(index);
  57747. indices.push(index + 2);
  57748. indices.push(index + 3);
  57749. index += 4;
  57750. }
  57751. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  57752. // VBO
  57753. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  57754. this._vertexData = new Float32Array(capacity * 16 * 4);
  57755. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  57756. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  57757. var options = this._buffer.createVertexBuffer("options", 4, 4);
  57758. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  57759. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  57760. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57761. this._vertexBuffers["options"] = options;
  57762. this._vertexBuffers["cellInfo"] = cellInfo;
  57763. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57764. // Effects
  57765. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  57766. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  57767. }
  57768. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  57769. /**
  57770. * Callback called when the manager is disposed
  57771. */
  57772. set: function (callback) {
  57773. if (this._onDisposeObserver) {
  57774. this.onDisposeObservable.remove(this._onDisposeObserver);
  57775. }
  57776. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57777. },
  57778. enumerable: true,
  57779. configurable: true
  57780. });
  57781. Object.defineProperty(SpriteManager.prototype, "texture", {
  57782. /**
  57783. * Gets or sets the spritesheet texture
  57784. */
  57785. get: function () {
  57786. return this._spriteTexture;
  57787. },
  57788. set: function (value) {
  57789. this._spriteTexture = value;
  57790. },
  57791. enumerable: true,
  57792. configurable: true
  57793. });
  57794. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  57795. var arrayOffset = index * 16;
  57796. if (offsetX === 0) {
  57797. offsetX = this._epsilon;
  57798. }
  57799. else if (offsetX === 1) {
  57800. offsetX = 1 - this._epsilon;
  57801. }
  57802. if (offsetY === 0) {
  57803. offsetY = this._epsilon;
  57804. }
  57805. else if (offsetY === 1) {
  57806. offsetY = 1 - this._epsilon;
  57807. }
  57808. this._vertexData[arrayOffset] = sprite.position.x;
  57809. this._vertexData[arrayOffset + 1] = sprite.position.y;
  57810. this._vertexData[arrayOffset + 2] = sprite.position.z;
  57811. this._vertexData[arrayOffset + 3] = sprite.angle;
  57812. this._vertexData[arrayOffset + 4] = sprite.width;
  57813. this._vertexData[arrayOffset + 5] = sprite.height;
  57814. this._vertexData[arrayOffset + 6] = offsetX;
  57815. this._vertexData[arrayOffset + 7] = offsetY;
  57816. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  57817. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  57818. var offset = (sprite.cellIndex / rowSize) >> 0;
  57819. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  57820. this._vertexData[arrayOffset + 11] = offset;
  57821. // Color
  57822. this._vertexData[arrayOffset + 12] = sprite.color.r;
  57823. this._vertexData[arrayOffset + 13] = sprite.color.g;
  57824. this._vertexData[arrayOffset + 14] = sprite.color.b;
  57825. this._vertexData[arrayOffset + 15] = sprite.color.a;
  57826. };
  57827. /**
  57828. * Intersects the sprites with a ray
  57829. * @param ray defines the ray to intersect with
  57830. * @param camera defines the current active camera
  57831. * @param predicate defines a predicate used to select candidate sprites
  57832. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  57833. * @returns null if no hit or a PickingInfo
  57834. */
  57835. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  57836. var count = Math.min(this._capacity, this.sprites.length);
  57837. var min = BABYLON.Vector3.Zero();
  57838. var max = BABYLON.Vector3.Zero();
  57839. var distance = Number.MAX_VALUE;
  57840. var currentSprite = null;
  57841. var cameraSpacePosition = BABYLON.Vector3.Zero();
  57842. var cameraView = camera.getViewMatrix();
  57843. for (var index = 0; index < count; index++) {
  57844. var sprite = this.sprites[index];
  57845. if (!sprite) {
  57846. continue;
  57847. }
  57848. if (predicate) {
  57849. if (!predicate(sprite)) {
  57850. continue;
  57851. }
  57852. }
  57853. else if (!sprite.isPickable) {
  57854. continue;
  57855. }
  57856. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  57857. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  57858. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  57859. if (ray.intersectsBoxMinMax(min, max)) {
  57860. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  57861. if (distance > currentDistance) {
  57862. distance = currentDistance;
  57863. currentSprite = sprite;
  57864. if (fastCheck) {
  57865. break;
  57866. }
  57867. }
  57868. }
  57869. }
  57870. if (currentSprite) {
  57871. var result = new BABYLON.PickingInfo();
  57872. result.hit = true;
  57873. result.pickedSprite = currentSprite;
  57874. result.distance = distance;
  57875. return result;
  57876. }
  57877. return null;
  57878. };
  57879. /**
  57880. * Render all child sprites
  57881. */
  57882. SpriteManager.prototype.render = function () {
  57883. // Check
  57884. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  57885. return;
  57886. }
  57887. var engine = this._scene.getEngine();
  57888. var baseSize = this._spriteTexture.getBaseSize();
  57889. // Sprites
  57890. var deltaTime = engine.getDeltaTime();
  57891. var max = Math.min(this._capacity, this.sprites.length);
  57892. var rowSize = baseSize.width / this.cellWidth;
  57893. var offset = 0;
  57894. for (var index = 0; index < max; index++) {
  57895. var sprite = this.sprites[index];
  57896. if (!sprite || !sprite.isVisible) {
  57897. continue;
  57898. }
  57899. sprite._animate(deltaTime);
  57900. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  57901. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  57902. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  57903. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  57904. }
  57905. this._buffer.update(this._vertexData);
  57906. // Render
  57907. var effect = this._effectBase;
  57908. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57909. effect = this._effectFog;
  57910. }
  57911. engine.enableEffect(effect);
  57912. var viewMatrix = this._scene.getViewMatrix();
  57913. effect.setTexture("diffuseSampler", this._spriteTexture);
  57914. effect.setMatrix("view", viewMatrix);
  57915. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57916. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  57917. // Fog
  57918. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57919. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  57920. effect.setColor3("vFogColor", this._scene.fogColor);
  57921. }
  57922. // VBOs
  57923. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57924. // Draw order
  57925. engine.setDepthFunctionToLessOrEqual();
  57926. effect.setBool("alphaTest", true);
  57927. engine.setColorWrite(false);
  57928. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57929. engine.setColorWrite(true);
  57930. effect.setBool("alphaTest", false);
  57931. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57932. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57933. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57934. };
  57935. /**
  57936. * Release associated resources
  57937. */
  57938. SpriteManager.prototype.dispose = function () {
  57939. if (this._buffer) {
  57940. this._buffer.dispose();
  57941. this._buffer = null;
  57942. }
  57943. if (this._indexBuffer) {
  57944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57945. this._indexBuffer = null;
  57946. }
  57947. if (this._spriteTexture) {
  57948. this._spriteTexture.dispose();
  57949. this._spriteTexture = null;
  57950. }
  57951. // Remove from scene
  57952. var index = this._scene.spriteManagers.indexOf(this);
  57953. this._scene.spriteManagers.splice(index, 1);
  57954. // Callback
  57955. this.onDisposeObservable.notifyObservers(this);
  57956. this.onDisposeObservable.clear();
  57957. };
  57958. return SpriteManager;
  57959. }());
  57960. BABYLON.SpriteManager = SpriteManager;
  57961. })(BABYLON || (BABYLON = {}));
  57962. //# sourceMappingURL=babylon.spriteManager.js.map
  57963. var BABYLON;
  57964. (function (BABYLON) {
  57965. /**
  57966. * Class used to represent a sprite
  57967. * @see http://doc.babylonjs.com/babylon101/sprites
  57968. */
  57969. var Sprite = /** @class */ (function () {
  57970. /**
  57971. * Creates a new Sprite
  57972. * @param name defines the name
  57973. * @param manager defines the manager
  57974. */
  57975. function Sprite(
  57976. /** defines the name */
  57977. name, manager) {
  57978. this.name = name;
  57979. /** Gets or sets the main color */
  57980. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57981. /** Gets or sets the width */
  57982. this.width = 1.0;
  57983. /** Gets or sets the height */
  57984. this.height = 1.0;
  57985. /** Gets or sets rotation angle */
  57986. this.angle = 0;
  57987. /** Gets or sets the cell index in the sprite sheet */
  57988. this.cellIndex = 0;
  57989. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  57990. this.invertU = 0;
  57991. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  57992. this.invertV = 0;
  57993. /** Gets the list of attached animations */
  57994. this.animations = new Array();
  57995. /** Gets or sets a boolean indicating if the sprite can be picked */
  57996. this.isPickable = false;
  57997. this._animationStarted = false;
  57998. this._loopAnimation = false;
  57999. this._fromIndex = 0;
  58000. this._toIndex = 0;
  58001. this._delay = 0;
  58002. this._direction = 1;
  58003. this._time = 0;
  58004. /**
  58005. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  58006. */
  58007. this.isVisible = true;
  58008. this._manager = manager;
  58009. this._manager.sprites.push(this);
  58010. this.position = BABYLON.Vector3.Zero();
  58011. }
  58012. Object.defineProperty(Sprite.prototype, "size", {
  58013. /**
  58014. * Gets or sets the sprite size
  58015. */
  58016. get: function () {
  58017. return this.width;
  58018. },
  58019. set: function (value) {
  58020. this.width = value;
  58021. this.height = value;
  58022. },
  58023. enumerable: true,
  58024. configurable: true
  58025. });
  58026. /**
  58027. * Starts an animation
  58028. * @param from defines the initial key
  58029. * @param to defines the end key
  58030. * @param loop defines if the animation must loop
  58031. * @param delay defines the start delay (in ms)
  58032. * @param onAnimationEnd defines a callback to call when animation ends
  58033. */
  58034. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  58035. this._fromIndex = from;
  58036. this._toIndex = to;
  58037. this._loopAnimation = loop;
  58038. this._delay = delay;
  58039. this._animationStarted = true;
  58040. this._direction = from < to ? 1 : -1;
  58041. this.cellIndex = from;
  58042. this._time = 0;
  58043. this._onAnimationEnd = onAnimationEnd;
  58044. };
  58045. /** Stops current animation (if any) */
  58046. Sprite.prototype.stopAnimation = function () {
  58047. this._animationStarted = false;
  58048. };
  58049. /** @hidden */
  58050. Sprite.prototype._animate = function (deltaTime) {
  58051. if (!this._animationStarted) {
  58052. return;
  58053. }
  58054. this._time += deltaTime;
  58055. if (this._time > this._delay) {
  58056. this._time = this._time % this._delay;
  58057. this.cellIndex += this._direction;
  58058. if (this.cellIndex > this._toIndex) {
  58059. if (this._loopAnimation) {
  58060. this.cellIndex = this._fromIndex;
  58061. }
  58062. else {
  58063. this.cellIndex = this._toIndex;
  58064. this._animationStarted = false;
  58065. if (this._onAnimationEnd) {
  58066. this._onAnimationEnd();
  58067. }
  58068. if (this.disposeWhenFinishedAnimating) {
  58069. this.dispose();
  58070. }
  58071. }
  58072. }
  58073. }
  58074. };
  58075. /** Release associated resources */
  58076. Sprite.prototype.dispose = function () {
  58077. for (var i = 0; i < this._manager.sprites.length; i++) {
  58078. if (this._manager.sprites[i] == this) {
  58079. this._manager.sprites.splice(i, 1);
  58080. }
  58081. }
  58082. };
  58083. return Sprite;
  58084. }());
  58085. BABYLON.Sprite = Sprite;
  58086. })(BABYLON || (BABYLON = {}));
  58087. //# sourceMappingURL=babylon.sprite.js.map
  58088. var BABYLON;
  58089. (function (BABYLON) {
  58090. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58091. if (!BABYLON.PickingInfo) {
  58092. return null;
  58093. }
  58094. var pickingInfo = null;
  58095. if (!camera) {
  58096. if (!this.activeCamera) {
  58097. return null;
  58098. }
  58099. camera = this.activeCamera;
  58100. }
  58101. if (this.spriteManagers.length > 0) {
  58102. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58103. var spriteManager = this.spriteManagers[spriteIndex];
  58104. if (!spriteManager.isPickable) {
  58105. continue;
  58106. }
  58107. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58108. if (!result || !result.hit) {
  58109. continue;
  58110. }
  58111. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58112. continue;
  58113. }
  58114. pickingInfo = result;
  58115. if (fastCheck) {
  58116. break;
  58117. }
  58118. }
  58119. }
  58120. return pickingInfo || new BABYLON.PickingInfo();
  58121. };
  58122. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58123. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58124. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58125. };
  58126. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58127. if (!this._tempSpritePickingRay) {
  58128. return null;
  58129. }
  58130. if (!camera) {
  58131. if (!this.activeCamera) {
  58132. return null;
  58133. }
  58134. camera = this.activeCamera;
  58135. }
  58136. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58137. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58138. };
  58139. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58140. if (this._pointerOverSprite === sprite) {
  58141. return;
  58142. }
  58143. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58144. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58145. }
  58146. this._pointerOverSprite = sprite;
  58147. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58148. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58149. }
  58150. };
  58151. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58152. return this._pointerOverSprite;
  58153. };
  58154. /**
  58155. * Defines the sprite scene component responsible to manage sprites
  58156. * in a given scene.
  58157. */
  58158. var SpriteSceneComponent = /** @class */ (function () {
  58159. /**
  58160. * Creates a new instance of the component for the given scene
  58161. * @param scene Defines the scene to register the component in
  58162. */
  58163. function SpriteSceneComponent(scene) {
  58164. /**
  58165. * The component name helpfull to identify the component in the list of scene components.
  58166. */
  58167. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58168. this.scene = scene;
  58169. this.scene.spriteManagers = new Array();
  58170. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58171. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58172. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58173. this._spritePredicate = function (sprite) {
  58174. if (!sprite.actionManager) {
  58175. return false;
  58176. }
  58177. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58178. };
  58179. }
  58180. /**
  58181. * Registers the component in a given scene
  58182. */
  58183. SpriteSceneComponent.prototype.register = function () {
  58184. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58185. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58186. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58187. };
  58188. /**
  58189. * Rebuilds the elements related to this component in case of
  58190. * context lost for instance.
  58191. */
  58192. SpriteSceneComponent.prototype.rebuild = function () {
  58193. /** Nothing to do for sprites */
  58194. };
  58195. /**
  58196. * Disposes the component and the associated ressources.
  58197. */
  58198. SpriteSceneComponent.prototype.dispose = function () {
  58199. this.scene.onBeforeSpritesRenderingObservable.clear();
  58200. this.scene.onAfterSpritesRenderingObservable.clear();
  58201. var spriteManagers = this.scene.spriteManagers;
  58202. while (spriteManagers.length) {
  58203. spriteManagers[0].dispose();
  58204. }
  58205. };
  58206. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  58207. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  58208. if (result) {
  58209. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  58210. }
  58211. return result;
  58212. };
  58213. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  58214. var scene = this.scene;
  58215. if (isMeshPicked) {
  58216. scene.setPointerOverSprite(null);
  58217. }
  58218. else {
  58219. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  58220. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58221. scene.setPointerOverSprite(pickResult.pickedSprite);
  58222. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  58223. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  58224. }
  58225. else {
  58226. canvas.style.cursor = scene.hoverCursor;
  58227. }
  58228. }
  58229. else {
  58230. scene.setPointerOverSprite(null);
  58231. }
  58232. }
  58233. return pickResult;
  58234. };
  58235. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58236. var scene = this.scene;
  58237. scene._pickedDownSprite = null;
  58238. if (scene.spriteManagers.length > 0) {
  58239. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58240. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58241. if (pickResult.pickedSprite.actionManager) {
  58242. scene._pickedDownSprite = pickResult.pickedSprite;
  58243. switch (evt.button) {
  58244. case 0:
  58245. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58246. break;
  58247. case 1:
  58248. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58249. break;
  58250. case 2:
  58251. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58252. break;
  58253. }
  58254. if (pickResult.pickedSprite.actionManager) {
  58255. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58256. }
  58257. }
  58258. }
  58259. }
  58260. return pickResult;
  58261. };
  58262. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58263. var scene = this.scene;
  58264. if (scene.spriteManagers.length > 0) {
  58265. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58266. if (spritePickResult) {
  58267. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  58268. if (spritePickResult.pickedSprite.actionManager) {
  58269. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58270. if (spritePickResult.pickedSprite.actionManager) {
  58271. if (!this.scene._isPointerSwiping()) {
  58272. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58273. }
  58274. }
  58275. }
  58276. }
  58277. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  58278. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  58279. }
  58280. }
  58281. }
  58282. return pickResult;
  58283. };
  58284. return SpriteSceneComponent;
  58285. }());
  58286. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  58287. })(BABYLON || (BABYLON = {}));
  58288. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  58289. var BABYLON;
  58290. (function (BABYLON) {
  58291. /**
  58292. * @hidden
  58293. */
  58294. var IntersectionInfo = /** @class */ (function () {
  58295. function IntersectionInfo(bu, bv, distance) {
  58296. this.bu = bu;
  58297. this.bv = bv;
  58298. this.distance = distance;
  58299. this.faceId = 0;
  58300. this.subMeshId = 0;
  58301. }
  58302. return IntersectionInfo;
  58303. }());
  58304. BABYLON.IntersectionInfo = IntersectionInfo;
  58305. /**
  58306. * Information about the result of picking within a scene
  58307. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  58308. */
  58309. var PickingInfo = /** @class */ (function () {
  58310. function PickingInfo() {
  58311. /**
  58312. * If the pick collided with an object
  58313. */
  58314. this.hit = false;
  58315. /**
  58316. * Distance away where the pick collided
  58317. */
  58318. this.distance = 0;
  58319. /**
  58320. * The location of pick collision
  58321. */
  58322. this.pickedPoint = null;
  58323. /**
  58324. * The mesh corresponding the the pick collision
  58325. */
  58326. this.pickedMesh = null;
  58327. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  58328. this.bu = 0;
  58329. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  58330. this.bv = 0;
  58331. /** The id of the face on the mesh that was picked */
  58332. this.faceId = -1;
  58333. /** Id of the the submesh that was picked */
  58334. this.subMeshId = 0;
  58335. /** If a sprite was picked, this will be the sprite the pick collided with */
  58336. this.pickedSprite = null;
  58337. /**
  58338. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  58339. */
  58340. this.originMesh = null;
  58341. /**
  58342. * The ray that was used to perform the picking.
  58343. */
  58344. this.ray = null;
  58345. }
  58346. /**
  58347. * Gets the normal correspodning to the face the pick collided with
  58348. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  58349. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  58350. * @returns The normal correspodning to the face the pick collided with
  58351. */
  58352. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  58353. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  58354. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  58355. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58356. return null;
  58357. }
  58358. var indices = this.pickedMesh.getIndices();
  58359. if (!indices) {
  58360. return null;
  58361. }
  58362. var result;
  58363. if (useVerticesNormals) {
  58364. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58365. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  58366. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  58367. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  58368. normal0 = normal0.scale(this.bu);
  58369. normal1 = normal1.scale(this.bv);
  58370. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  58371. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  58372. }
  58373. else {
  58374. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58375. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  58376. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  58377. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  58378. var p1p2 = vertex1.subtract(vertex2);
  58379. var p3p2 = vertex3.subtract(vertex2);
  58380. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  58381. }
  58382. if (useWorldCoordinates) {
  58383. var wm = this.pickedMesh.getWorldMatrix();
  58384. if (this.pickedMesh.nonUniformScaling) {
  58385. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  58386. wm = BABYLON.Tmp.Matrix[0];
  58387. wm.setTranslationFromFloats(0, 0, 0);
  58388. wm.invert();
  58389. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  58390. wm = BABYLON.Tmp.Matrix[1];
  58391. }
  58392. result = BABYLON.Vector3.TransformNormal(result, wm);
  58393. }
  58394. result.normalize();
  58395. return result;
  58396. };
  58397. /**
  58398. * Gets the texture coordinates of where the pick occured
  58399. * @returns the vector containing the coordnates of the texture
  58400. */
  58401. PickingInfo.prototype.getTextureCoordinates = function () {
  58402. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58403. return null;
  58404. }
  58405. var indices = this.pickedMesh.getIndices();
  58406. if (!indices) {
  58407. return null;
  58408. }
  58409. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58410. if (!uvs) {
  58411. return null;
  58412. }
  58413. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  58414. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  58415. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  58416. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  58417. uv1 = uv1.scale(this.bu);
  58418. uv2 = uv2.scale(this.bv);
  58419. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  58420. };
  58421. return PickingInfo;
  58422. }());
  58423. BABYLON.PickingInfo = PickingInfo;
  58424. })(BABYLON || (BABYLON = {}));
  58425. //# sourceMappingURL=babylon.pickingInfo.js.map
  58426. var BABYLON;
  58427. (function (BABYLON) {
  58428. /**
  58429. * Class representing a ray with position and direction
  58430. */
  58431. var Ray = /** @class */ (function () {
  58432. /**
  58433. * Creates a new ray
  58434. * @param origin origin point
  58435. * @param direction direction
  58436. * @param length length of the ray
  58437. */
  58438. function Ray(
  58439. /** origin point */
  58440. origin,
  58441. /** direction */
  58442. direction,
  58443. /** length of the ray */
  58444. length) {
  58445. if (length === void 0) { length = Number.MAX_VALUE; }
  58446. this.origin = origin;
  58447. this.direction = direction;
  58448. this.length = length;
  58449. }
  58450. // Methods
  58451. /**
  58452. * Checks if the ray intersects a box
  58453. * @param minimum bound of the box
  58454. * @param maximum bound of the box
  58455. * @param intersectionTreshold extra extend to be added to the box in all direction
  58456. * @returns if the box was hit
  58457. */
  58458. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) {
  58459. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58460. var newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  58461. var newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  58462. var d = 0.0;
  58463. var maxValue = Number.MAX_VALUE;
  58464. var inv;
  58465. var min;
  58466. var max;
  58467. var temp;
  58468. if (Math.abs(this.direction.x) < 0.0000001) {
  58469. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  58470. return false;
  58471. }
  58472. }
  58473. else {
  58474. inv = 1.0 / this.direction.x;
  58475. min = (newMinimum.x - this.origin.x) * inv;
  58476. max = (newMaximum.x - this.origin.x) * inv;
  58477. if (max === -Infinity) {
  58478. max = Infinity;
  58479. }
  58480. if (min > max) {
  58481. temp = min;
  58482. min = max;
  58483. max = temp;
  58484. }
  58485. d = Math.max(min, d);
  58486. maxValue = Math.min(max, maxValue);
  58487. if (d > maxValue) {
  58488. return false;
  58489. }
  58490. }
  58491. if (Math.abs(this.direction.y) < 0.0000001) {
  58492. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  58493. return false;
  58494. }
  58495. }
  58496. else {
  58497. inv = 1.0 / this.direction.y;
  58498. min = (newMinimum.y - this.origin.y) * inv;
  58499. max = (newMaximum.y - this.origin.y) * inv;
  58500. if (max === -Infinity) {
  58501. max = Infinity;
  58502. }
  58503. if (min > max) {
  58504. temp = min;
  58505. min = max;
  58506. max = temp;
  58507. }
  58508. d = Math.max(min, d);
  58509. maxValue = Math.min(max, maxValue);
  58510. if (d > maxValue) {
  58511. return false;
  58512. }
  58513. }
  58514. if (Math.abs(this.direction.z) < 0.0000001) {
  58515. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  58516. return false;
  58517. }
  58518. }
  58519. else {
  58520. inv = 1.0 / this.direction.z;
  58521. min = (newMinimum.z - this.origin.z) * inv;
  58522. max = (newMaximum.z - this.origin.z) * inv;
  58523. if (max === -Infinity) {
  58524. max = Infinity;
  58525. }
  58526. if (min > max) {
  58527. temp = min;
  58528. min = max;
  58529. max = temp;
  58530. }
  58531. d = Math.max(min, d);
  58532. maxValue = Math.min(max, maxValue);
  58533. if (d > maxValue) {
  58534. return false;
  58535. }
  58536. }
  58537. return true;
  58538. };
  58539. /**
  58540. * Checks if the ray intersects a box
  58541. * @param box the bounding box to check
  58542. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  58543. * @returns if the box was hit
  58544. */
  58545. Ray.prototype.intersectsBox = function (box, intersectionTreshold) {
  58546. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58547. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  58548. };
  58549. /**
  58550. * If the ray hits a sphere
  58551. * @param sphere the bounding sphere to check
  58552. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  58553. * @returns true if it hits the sphere
  58554. */
  58555. Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) {
  58556. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58557. var x = sphere.center.x - this.origin.x;
  58558. var y = sphere.center.y - this.origin.y;
  58559. var z = sphere.center.z - this.origin.z;
  58560. var pyth = (x * x) + (y * y) + (z * z);
  58561. var radius = sphere.radius + intersectionTreshold;
  58562. var rr = radius * radius;
  58563. if (pyth <= rr) {
  58564. return true;
  58565. }
  58566. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  58567. if (dot < 0.0) {
  58568. return false;
  58569. }
  58570. var temp = pyth - (dot * dot);
  58571. return temp <= rr;
  58572. };
  58573. /**
  58574. * If the ray hits a triange
  58575. * @param vertex0 triangle vertex
  58576. * @param vertex1 triangle vertex
  58577. * @param vertex2 triangle vertex
  58578. * @returns intersection information if hit
  58579. */
  58580. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  58581. var edge1 = Ray.TmpVector3[0];
  58582. var edge2 = Ray.TmpVector3[1];
  58583. var pvec = Ray.TmpVector3[2];
  58584. var tvec = Ray.TmpVector3[3];
  58585. var qvec = Ray.TmpVector3[4];
  58586. vertex1.subtractToRef(vertex0, edge1);
  58587. vertex2.subtractToRef(vertex0, edge2);
  58588. BABYLON.Vector3.CrossToRef(this.direction, edge2, pvec);
  58589. var det = BABYLON.Vector3.Dot(edge1, pvec);
  58590. if (det === 0) {
  58591. return null;
  58592. }
  58593. var invdet = 1 / det;
  58594. this.origin.subtractToRef(vertex0, tvec);
  58595. var bu = BABYLON.Vector3.Dot(tvec, pvec) * invdet;
  58596. if (bu < 0 || bu > 1.0) {
  58597. return null;
  58598. }
  58599. BABYLON.Vector3.CrossToRef(tvec, edge1, qvec);
  58600. var bv = BABYLON.Vector3.Dot(this.direction, qvec) * invdet;
  58601. if (bv < 0 || bu + bv > 1.0) {
  58602. return null;
  58603. }
  58604. //check if the distance is longer than the predefined length.
  58605. var distance = BABYLON.Vector3.Dot(edge2, qvec) * invdet;
  58606. if (distance > this.length) {
  58607. return null;
  58608. }
  58609. return new BABYLON.IntersectionInfo(bu, bv, distance);
  58610. };
  58611. /**
  58612. * Checks if ray intersects a plane
  58613. * @param plane the plane to check
  58614. * @returns the distance away it was hit
  58615. */
  58616. Ray.prototype.intersectsPlane = function (plane) {
  58617. var distance;
  58618. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  58619. if (Math.abs(result1) < 9.99999997475243E-07) {
  58620. return null;
  58621. }
  58622. else {
  58623. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  58624. distance = (-plane.d - result2) / result1;
  58625. if (distance < 0.0) {
  58626. if (distance < -9.99999997475243E-07) {
  58627. return null;
  58628. }
  58629. else {
  58630. return 0;
  58631. }
  58632. }
  58633. return distance;
  58634. }
  58635. };
  58636. /**
  58637. * Checks if ray intersects a mesh
  58638. * @param mesh the mesh to check
  58639. * @param fastCheck if only the bounding box should checked
  58640. * @returns picking info of the intersecton
  58641. */
  58642. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  58643. var tm = BABYLON.Tmp.Matrix[0];
  58644. mesh.getWorldMatrix().invertToRef(tm);
  58645. if (this._tmpRay) {
  58646. Ray.TransformToRef(this, tm, this._tmpRay);
  58647. }
  58648. else {
  58649. this._tmpRay = Ray.Transform(this, tm);
  58650. }
  58651. return mesh.intersects(this._tmpRay, fastCheck);
  58652. };
  58653. /**
  58654. * Checks if ray intersects a mesh
  58655. * @param meshes the meshes to check
  58656. * @param fastCheck if only the bounding box should checked
  58657. * @param results array to store result in
  58658. * @returns Array of picking infos
  58659. */
  58660. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  58661. if (results) {
  58662. results.length = 0;
  58663. }
  58664. else {
  58665. results = [];
  58666. }
  58667. for (var i = 0; i < meshes.length; i++) {
  58668. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  58669. if (pickInfo.hit) {
  58670. results.push(pickInfo);
  58671. }
  58672. }
  58673. results.sort(this._comparePickingInfo);
  58674. return results;
  58675. };
  58676. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  58677. if (pickingInfoA.distance < pickingInfoB.distance) {
  58678. return -1;
  58679. }
  58680. else if (pickingInfoA.distance > pickingInfoB.distance) {
  58681. return 1;
  58682. }
  58683. else {
  58684. return 0;
  58685. }
  58686. };
  58687. /**
  58688. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  58689. * @param sega the first point of the segment to test the intersection against
  58690. * @param segb the second point of the segment to test the intersection against
  58691. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  58692. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  58693. */
  58694. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  58695. var o = this.origin;
  58696. var u = BABYLON.Tmp.Vector3[0];
  58697. var rsegb = BABYLON.Tmp.Vector3[1];
  58698. var v = BABYLON.Tmp.Vector3[2];
  58699. var w = BABYLON.Tmp.Vector3[3];
  58700. segb.subtractToRef(sega, u);
  58701. this.direction.scaleToRef(Ray.rayl, v);
  58702. o.addToRef(v, rsegb);
  58703. sega.subtractToRef(o, w);
  58704. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  58705. var b = BABYLON.Vector3.Dot(u, v);
  58706. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  58707. var d = BABYLON.Vector3.Dot(u, w);
  58708. var e = BABYLON.Vector3.Dot(v, w);
  58709. var D = a * c - b * b; // always >= 0
  58710. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  58711. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  58712. // compute the line parameters of the two closest points
  58713. if (D < Ray.smallnum) { // the lines are almost parallel
  58714. sN = 0.0; // force using point P0 on segment S1
  58715. sD = 1.0; // to prevent possible division by 0.0 later
  58716. tN = e;
  58717. tD = c;
  58718. }
  58719. else { // get the closest points on the infinite lines
  58720. sN = (b * e - c * d);
  58721. tN = (a * e - b * d);
  58722. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  58723. sN = 0.0;
  58724. tN = e;
  58725. tD = c;
  58726. }
  58727. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  58728. sN = sD;
  58729. tN = e + b;
  58730. tD = c;
  58731. }
  58732. }
  58733. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  58734. tN = 0.0;
  58735. // recompute sc for this edge
  58736. if (-d < 0.0) {
  58737. sN = 0.0;
  58738. }
  58739. else if (-d > a) {
  58740. sN = sD;
  58741. }
  58742. else {
  58743. sN = -d;
  58744. sD = a;
  58745. }
  58746. }
  58747. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  58748. tN = tD;
  58749. // recompute sc for this edge
  58750. if ((-d + b) < 0.0) {
  58751. sN = 0;
  58752. }
  58753. else if ((-d + b) > a) {
  58754. sN = sD;
  58755. }
  58756. else {
  58757. sN = (-d + b);
  58758. sD = a;
  58759. }
  58760. }
  58761. // finally do the division to get sc and tc
  58762. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  58763. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  58764. // get the difference of the two closest points
  58765. var qtc = BABYLON.Tmp.Vector3[4];
  58766. v.scaleToRef(tc, qtc);
  58767. var dP = BABYLON.Tmp.Vector3[5];
  58768. u.scaleToRef(sc, dP);
  58769. dP.addInPlace(w).subtractInPlace(qtc); // = S1(sc) - S2(tc)
  58770. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  58771. if (isIntersected) {
  58772. return qtc.length();
  58773. }
  58774. return -1;
  58775. };
  58776. /**
  58777. * Update the ray from viewport position
  58778. * @param x position
  58779. * @param y y position
  58780. * @param viewportWidth viewport width
  58781. * @param viewportHeight viewport height
  58782. * @param world world matrix
  58783. * @param view view matrix
  58784. * @param projection projection matrix
  58785. * @returns this ray updated
  58786. */
  58787. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58788. BABYLON.Vector3.UnprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection, this);
  58789. return this;
  58790. };
  58791. // Statics
  58792. /**
  58793. * Creates a ray with origin and direction of 0,0,0
  58794. * @returns the new ray
  58795. */
  58796. Ray.Zero = function () {
  58797. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  58798. };
  58799. /**
  58800. * Creates a new ray from screen space and viewport
  58801. * @param x position
  58802. * @param y y position
  58803. * @param viewportWidth viewport width
  58804. * @param viewportHeight viewport height
  58805. * @param world world matrix
  58806. * @param view view matrix
  58807. * @param projection projection matrix
  58808. * @returns new ray
  58809. */
  58810. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58811. var result = Ray.Zero();
  58812. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  58813. };
  58814. /**
  58815. * 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
  58816. * transformed to the given world matrix.
  58817. * @param origin The origin point
  58818. * @param end The end point
  58819. * @param world a matrix to transform the ray to. Default is the identity matrix.
  58820. * @returns the new ray
  58821. */
  58822. Ray.CreateNewFromTo = function (origin, end, world) {
  58823. if (world === void 0) { world = BABYLON.Matrix.IdentityReadOnly; }
  58824. var direction = end.subtract(origin);
  58825. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  58826. direction.normalize();
  58827. return Ray.Transform(new Ray(origin, direction, length), world);
  58828. };
  58829. /**
  58830. * Transforms a ray by a matrix
  58831. * @param ray ray to transform
  58832. * @param matrix matrix to apply
  58833. * @returns the resulting new ray
  58834. */
  58835. Ray.Transform = function (ray, matrix) {
  58836. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  58837. Ray.TransformToRef(ray, matrix, result);
  58838. return result;
  58839. };
  58840. /**
  58841. * Transforms a ray by a matrix
  58842. * @param ray ray to transform
  58843. * @param matrix matrix to apply
  58844. * @param result ray to store result in
  58845. */
  58846. Ray.TransformToRef = function (ray, matrix, result) {
  58847. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  58848. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  58849. result.length = ray.length;
  58850. var dir = result.direction;
  58851. var len = dir.length();
  58852. if (!(len === 0 || len === 1)) {
  58853. var num = 1.0 / len;
  58854. dir.x *= num;
  58855. dir.y *= num;
  58856. dir.z *= num;
  58857. result.length *= len;
  58858. }
  58859. };
  58860. Ray.TmpVector3 = BABYLON.Tools.BuildArray(6, BABYLON.Vector3.Zero);
  58861. Ray.smallnum = 0.00000001;
  58862. Ray.rayl = 10e8;
  58863. return Ray;
  58864. }());
  58865. BABYLON.Ray = Ray;
  58866. })(BABYLON || (BABYLON = {}));
  58867. //# sourceMappingURL=babylon.ray.js.map
  58868. var BABYLON;
  58869. (function (BABYLON) {
  58870. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  58871. if (boxMin.x > sphereCenter.x + sphereRadius) {
  58872. return false;
  58873. }
  58874. if (sphereCenter.x - sphereRadius > boxMax.x) {
  58875. return false;
  58876. }
  58877. if (boxMin.y > sphereCenter.y + sphereRadius) {
  58878. return false;
  58879. }
  58880. if (sphereCenter.y - sphereRadius > boxMax.y) {
  58881. return false;
  58882. }
  58883. if (boxMin.z > sphereCenter.z + sphereRadius) {
  58884. return false;
  58885. }
  58886. if (sphereCenter.z - sphereRadius > boxMax.z) {
  58887. return false;
  58888. }
  58889. return true;
  58890. };
  58891. var getLowestRoot = (function () {
  58892. var result = { root: 0, found: false };
  58893. return function (a, b, c, maxR) {
  58894. result.root = 0;
  58895. result.found = false;
  58896. var determinant = b * b - 4.0 * a * c;
  58897. if (determinant < 0) {
  58898. return result;
  58899. }
  58900. var sqrtD = Math.sqrt(determinant);
  58901. var r1 = (-b - sqrtD) / (2.0 * a);
  58902. var r2 = (-b + sqrtD) / (2.0 * a);
  58903. if (r1 > r2) {
  58904. var temp = r2;
  58905. r2 = r1;
  58906. r1 = temp;
  58907. }
  58908. if (r1 > 0 && r1 < maxR) {
  58909. result.root = r1;
  58910. result.found = true;
  58911. return result;
  58912. }
  58913. if (r2 > 0 && r2 < maxR) {
  58914. result.root = r2;
  58915. result.found = true;
  58916. return result;
  58917. }
  58918. return result;
  58919. };
  58920. })();
  58921. /** @hidden */
  58922. var Collider = /** @class */ (function () {
  58923. function Collider() {
  58924. this._collisionPoint = BABYLON.Vector3.Zero();
  58925. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  58926. this._tempVector = BABYLON.Vector3.Zero();
  58927. this._tempVector2 = BABYLON.Vector3.Zero();
  58928. this._tempVector3 = BABYLON.Vector3.Zero();
  58929. this._tempVector4 = BABYLON.Vector3.Zero();
  58930. this._edge = BABYLON.Vector3.Zero();
  58931. this._baseToVertex = BABYLON.Vector3.Zero();
  58932. this._destinationPoint = BABYLON.Vector3.Zero();
  58933. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  58934. this._displacementVector = BABYLON.Vector3.Zero();
  58935. /** @hidden */
  58936. this._radius = BABYLON.Vector3.One();
  58937. /** @hidden */
  58938. this._retry = 0;
  58939. /** @hidden */
  58940. this._basePointWorld = BABYLON.Vector3.Zero();
  58941. this._velocityWorld = BABYLON.Vector3.Zero();
  58942. this._normalizedVelocity = BABYLON.Vector3.Zero();
  58943. this._collisionMask = -1;
  58944. }
  58945. Object.defineProperty(Collider.prototype, "collisionMask", {
  58946. get: function () {
  58947. return this._collisionMask;
  58948. },
  58949. set: function (mask) {
  58950. this._collisionMask = !isNaN(mask) ? mask : -1;
  58951. },
  58952. enumerable: true,
  58953. configurable: true
  58954. });
  58955. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  58956. /**
  58957. * Gets the plane normal used to compute the sliding response (in local space)
  58958. */
  58959. get: function () {
  58960. return this._slidePlaneNormal;
  58961. },
  58962. enumerable: true,
  58963. configurable: true
  58964. });
  58965. // Methods
  58966. /** @hidden */
  58967. Collider.prototype._initialize = function (source, dir, e) {
  58968. this._velocity = dir;
  58969. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  58970. this._basePoint = source;
  58971. source.multiplyToRef(this._radius, this._basePointWorld);
  58972. dir.multiplyToRef(this._radius, this._velocityWorld);
  58973. this._velocityWorldLength = this._velocityWorld.length();
  58974. this._epsilon = e;
  58975. this.collisionFound = false;
  58976. };
  58977. /** @hidden */
  58978. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  58979. pa.subtractToRef(point, this._tempVector);
  58980. pb.subtractToRef(point, this._tempVector2);
  58981. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  58982. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58983. if (d < 0) {
  58984. return false;
  58985. }
  58986. pc.subtractToRef(point, this._tempVector3);
  58987. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  58988. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58989. if (d < 0) {
  58990. return false;
  58991. }
  58992. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  58993. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  58994. return d >= 0;
  58995. };
  58996. /** @hidden */
  58997. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  58998. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  58999. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  59000. if (distance > this._velocityWorldLength + max + sphereRadius) {
  59001. return false;
  59002. }
  59003. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  59004. return false;
  59005. }
  59006. return true;
  59007. };
  59008. /** @hidden */
  59009. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  59010. var t0;
  59011. var embeddedInPlane = false;
  59012. //defensive programming, actually not needed.
  59013. if (!trianglePlaneArray) {
  59014. trianglePlaneArray = [];
  59015. }
  59016. if (!trianglePlaneArray[faceIndex]) {
  59017. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  59018. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  59019. }
  59020. var trianglePlane = trianglePlaneArray[faceIndex];
  59021. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  59022. return;
  59023. }
  59024. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  59025. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  59026. if (normalDotVelocity == 0) {
  59027. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  59028. return;
  59029. }
  59030. embeddedInPlane = true;
  59031. t0 = 0;
  59032. }
  59033. else {
  59034. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59035. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59036. if (t0 > t1) {
  59037. var temp = t1;
  59038. t1 = t0;
  59039. t0 = temp;
  59040. }
  59041. if (t0 > 1.0 || t1 < 0.0) {
  59042. return;
  59043. }
  59044. if (t0 < 0) {
  59045. t0 = 0;
  59046. }
  59047. if (t0 > 1.0) {
  59048. t0 = 1.0;
  59049. }
  59050. }
  59051. this._collisionPoint.copyFromFloats(0, 0, 0);
  59052. var found = false;
  59053. var t = 1.0;
  59054. if (!embeddedInPlane) {
  59055. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59056. this._velocity.scaleToRef(t0, this._tempVector);
  59057. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59058. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59059. found = true;
  59060. t = t0;
  59061. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59062. }
  59063. }
  59064. if (!found) {
  59065. var velocitySquaredLength = this._velocity.lengthSquared();
  59066. var a = velocitySquaredLength;
  59067. this._basePoint.subtractToRef(p1, this._tempVector);
  59068. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59069. var c = this._tempVector.lengthSquared() - 1.0;
  59070. var lowestRoot = getLowestRoot(a, b, c, t);
  59071. if (lowestRoot.found) {
  59072. t = lowestRoot.root;
  59073. found = true;
  59074. this._collisionPoint.copyFrom(p1);
  59075. }
  59076. this._basePoint.subtractToRef(p2, this._tempVector);
  59077. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59078. c = this._tempVector.lengthSquared() - 1.0;
  59079. lowestRoot = getLowestRoot(a, b, c, t);
  59080. if (lowestRoot.found) {
  59081. t = lowestRoot.root;
  59082. found = true;
  59083. this._collisionPoint.copyFrom(p2);
  59084. }
  59085. this._basePoint.subtractToRef(p3, this._tempVector);
  59086. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59087. c = this._tempVector.lengthSquared() - 1.0;
  59088. lowestRoot = getLowestRoot(a, b, c, t);
  59089. if (lowestRoot.found) {
  59090. t = lowestRoot.root;
  59091. found = true;
  59092. this._collisionPoint.copyFrom(p3);
  59093. }
  59094. p2.subtractToRef(p1, this._edge);
  59095. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59096. var edgeSquaredLength = this._edge.lengthSquared();
  59097. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59098. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59099. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59100. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59101. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59102. lowestRoot = getLowestRoot(a, b, c, t);
  59103. if (lowestRoot.found) {
  59104. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59105. if (f >= 0.0 && f <= 1.0) {
  59106. t = lowestRoot.root;
  59107. found = true;
  59108. this._edge.scaleInPlace(f);
  59109. p1.addToRef(this._edge, this._collisionPoint);
  59110. }
  59111. }
  59112. p3.subtractToRef(p2, this._edge);
  59113. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59114. edgeSquaredLength = this._edge.lengthSquared();
  59115. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59116. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59117. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59118. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59119. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59120. lowestRoot = getLowestRoot(a, b, c, t);
  59121. if (lowestRoot.found) {
  59122. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59123. if (f >= 0.0 && f <= 1.0) {
  59124. t = lowestRoot.root;
  59125. found = true;
  59126. this._edge.scaleInPlace(f);
  59127. p2.addToRef(this._edge, this._collisionPoint);
  59128. }
  59129. }
  59130. p1.subtractToRef(p3, this._edge);
  59131. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59132. edgeSquaredLength = this._edge.lengthSquared();
  59133. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59134. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59135. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59136. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59137. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59138. lowestRoot = getLowestRoot(a, b, c, t);
  59139. if (lowestRoot.found) {
  59140. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59141. if (f >= 0.0 && f <= 1.0) {
  59142. t = lowestRoot.root;
  59143. found = true;
  59144. this._edge.scaleInPlace(f);
  59145. p3.addToRef(this._edge, this._collisionPoint);
  59146. }
  59147. }
  59148. }
  59149. if (found) {
  59150. var distToCollision = t * this._velocity.length();
  59151. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59152. if (!this.intersectionPoint) {
  59153. this.intersectionPoint = this._collisionPoint.clone();
  59154. }
  59155. else {
  59156. this.intersectionPoint.copyFrom(this._collisionPoint);
  59157. }
  59158. this._nearestDistance = distToCollision;
  59159. this.collisionFound = true;
  59160. }
  59161. }
  59162. };
  59163. /** @hidden */
  59164. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59165. for (var i = indexStart; i < indexEnd; i += 3) {
  59166. var p1 = pts[indices[i] - decal];
  59167. var p2 = pts[indices[i + 1] - decal];
  59168. var p3 = pts[indices[i + 2] - decal];
  59169. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59170. }
  59171. };
  59172. /** @hidden */
  59173. Collider.prototype._getResponse = function (pos, vel) {
  59174. pos.addToRef(vel, this._destinationPoint);
  59175. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59176. this._basePoint.addToRef(vel, pos);
  59177. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59178. this._slidePlaneNormal.normalize();
  59179. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59180. pos.addInPlace(this._displacementVector);
  59181. this.intersectionPoint.addInPlace(this._displacementVector);
  59182. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59183. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59184. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59185. };
  59186. return Collider;
  59187. }());
  59188. BABYLON.Collider = Collider;
  59189. })(BABYLON || (BABYLON = {}));
  59190. //# sourceMappingURL=babylon.collider.js.map
  59191. var BABYLON;
  59192. (function (BABYLON) {
  59193. //WebWorker code will be inserted to this variable.
  59194. /** @hidden */
  59195. BABYLON.CollisionWorker = "";
  59196. /** Defines supported task for worker process */
  59197. var WorkerTaskType;
  59198. (function (WorkerTaskType) {
  59199. /** Initialization */
  59200. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  59201. /** Update of geometry */
  59202. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  59203. /** Evaluate collision */
  59204. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  59205. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  59206. /** Defines kind of replies returned by worker */
  59207. var WorkerReplyType;
  59208. (function (WorkerReplyType) {
  59209. /** Success */
  59210. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  59211. /** Unkown error */
  59212. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  59213. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  59214. /** @hidden */
  59215. var CollisionCoordinatorWorker = /** @class */ (function () {
  59216. function CollisionCoordinatorWorker() {
  59217. var _this = this;
  59218. this._scaledPosition = BABYLON.Vector3.Zero();
  59219. this._scaledVelocity = BABYLON.Vector3.Zero();
  59220. this.onMeshUpdated = function (transformNode) {
  59221. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  59222. };
  59223. this.onGeometryUpdated = function (geometry) {
  59224. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  59225. };
  59226. this._afterRender = function () {
  59227. if (!_this._init) {
  59228. return;
  59229. }
  59230. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  59231. return;
  59232. }
  59233. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  59234. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  59235. if (_this._runningUpdated > 4) {
  59236. return;
  59237. }
  59238. ++_this._runningUpdated;
  59239. var payload = {
  59240. updatedMeshes: _this._addUpdateMeshesList,
  59241. updatedGeometries: _this._addUpdateGeometriesList,
  59242. removedGeometries: _this._toRemoveGeometryArray,
  59243. removedMeshes: _this._toRemoveMeshesArray
  59244. };
  59245. var message = {
  59246. payload: payload,
  59247. taskType: WorkerTaskType.UPDATE
  59248. };
  59249. var serializable = [];
  59250. for (var id in payload.updatedGeometries) {
  59251. if (payload.updatedGeometries.hasOwnProperty(id)) {
  59252. //prepare transferables
  59253. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  59254. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  59255. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  59256. }
  59257. }
  59258. _this._worker.postMessage(message, serializable);
  59259. _this._addUpdateMeshesList = {};
  59260. _this._addUpdateGeometriesList = {};
  59261. _this._toRemoveGeometryArray = [];
  59262. _this._toRemoveMeshesArray = [];
  59263. };
  59264. this._onMessageFromWorker = function (e) {
  59265. var returnData = e.data;
  59266. if (returnData.error != WorkerReplyType.SUCCESS) {
  59267. //TODO what errors can be returned from the worker?
  59268. BABYLON.Tools.Warn("error returned from worker!");
  59269. return;
  59270. }
  59271. switch (returnData.taskType) {
  59272. case WorkerTaskType.INIT:
  59273. _this._init = true;
  59274. //Update the worked with ALL of the scene's current state
  59275. _this._scene.meshes.forEach(function (mesh) {
  59276. _this.onMeshAdded(mesh);
  59277. });
  59278. _this._scene.getGeometries().forEach(function (geometry) {
  59279. _this.onGeometryAdded(geometry);
  59280. });
  59281. break;
  59282. case WorkerTaskType.UPDATE:
  59283. _this._runningUpdated--;
  59284. break;
  59285. case WorkerTaskType.COLLIDE:
  59286. var returnPayload = returnData.payload;
  59287. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  59288. return;
  59289. }
  59290. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  59291. if (callback) {
  59292. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  59293. if (mesh) {
  59294. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  59295. }
  59296. }
  59297. //cleanup
  59298. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  59299. break;
  59300. }
  59301. };
  59302. this._collisionsCallbackArray = [];
  59303. this._init = false;
  59304. this._runningUpdated = 0;
  59305. this._addUpdateMeshesList = {};
  59306. this._addUpdateGeometriesList = {};
  59307. this._toRemoveGeometryArray = [];
  59308. this._toRemoveMeshesArray = [];
  59309. }
  59310. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59311. if (!this._init) {
  59312. return;
  59313. }
  59314. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  59315. return;
  59316. }
  59317. position.divideToRef(collider._radius, this._scaledPosition);
  59318. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59319. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  59320. var payload = {
  59321. collider: {
  59322. position: this._scaledPosition.asArray(),
  59323. velocity: this._scaledVelocity.asArray(),
  59324. radius: collider._radius.asArray()
  59325. },
  59326. collisionId: collisionIndex,
  59327. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  59328. maximumRetry: maximumRetry
  59329. };
  59330. var message = {
  59331. payload: payload,
  59332. taskType: WorkerTaskType.COLLIDE
  59333. };
  59334. this._worker.postMessage(message);
  59335. };
  59336. CollisionCoordinatorWorker.prototype.init = function (scene) {
  59337. this._scene = scene;
  59338. this._scene.registerAfterRender(this._afterRender);
  59339. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  59340. this._worker = new Worker(workerUrl);
  59341. this._worker.onmessage = this._onMessageFromWorker;
  59342. var message = {
  59343. payload: {},
  59344. taskType: WorkerTaskType.INIT
  59345. };
  59346. this._worker.postMessage(message);
  59347. };
  59348. CollisionCoordinatorWorker.prototype.destroy = function () {
  59349. this._scene.unregisterAfterRender(this._afterRender);
  59350. this._worker.terminate();
  59351. };
  59352. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  59353. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  59354. this.onMeshUpdated(mesh);
  59355. };
  59356. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  59357. this._toRemoveMeshesArray.push(mesh.uniqueId);
  59358. };
  59359. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  59360. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  59361. geometry.onGeometryUpdated = this.onGeometryUpdated;
  59362. this.onGeometryUpdated(geometry);
  59363. };
  59364. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  59365. this._toRemoveGeometryArray.push(geometry.id);
  59366. };
  59367. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  59368. var submeshes = [];
  59369. if (mesh.subMeshes) {
  59370. submeshes = mesh.subMeshes.map(function (sm, idx) {
  59371. var boundingInfo = sm.getBoundingInfo();
  59372. return {
  59373. position: idx,
  59374. verticesStart: sm.verticesStart,
  59375. verticesCount: sm.verticesCount,
  59376. indexStart: sm.indexStart,
  59377. indexCount: sm.indexCount,
  59378. hasMaterial: !!sm.getMaterial(),
  59379. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59380. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59381. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59382. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  59383. };
  59384. });
  59385. }
  59386. var geometryId = null;
  59387. if (mesh instanceof BABYLON.Mesh) {
  59388. var geometry = mesh.geometry;
  59389. geometryId = geometry ? geometry.id : null;
  59390. }
  59391. else if (mesh instanceof BABYLON.InstancedMesh) {
  59392. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  59393. geometryId = geometry ? geometry.id : null;
  59394. }
  59395. var boundingInfo = mesh.getBoundingInfo();
  59396. return {
  59397. uniqueId: mesh.uniqueId,
  59398. id: mesh.id,
  59399. name: mesh.name,
  59400. geometryId: geometryId,
  59401. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59402. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59403. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59404. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  59405. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  59406. subMeshes: submeshes,
  59407. checkCollisions: mesh.checkCollisions
  59408. };
  59409. };
  59410. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  59411. return {
  59412. id: geometry.id,
  59413. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  59414. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  59415. indices: new Uint32Array(geometry.getIndices() || []),
  59416. };
  59417. };
  59418. return CollisionCoordinatorWorker;
  59419. }());
  59420. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  59421. /** @hidden */
  59422. var CollisionCoordinatorLegacy = /** @class */ (function () {
  59423. function CollisionCoordinatorLegacy() {
  59424. this._scaledPosition = BABYLON.Vector3.Zero();
  59425. this._scaledVelocity = BABYLON.Vector3.Zero();
  59426. this._finalPosition = BABYLON.Vector3.Zero();
  59427. }
  59428. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59429. position.divideToRef(collider._radius, this._scaledPosition);
  59430. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59431. collider.collidedMesh = null;
  59432. collider._retry = 0;
  59433. collider._initialVelocity = this._scaledVelocity;
  59434. collider._initialPosition = this._scaledPosition;
  59435. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  59436. this._finalPosition.multiplyInPlace(collider._radius);
  59437. //run the callback
  59438. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  59439. };
  59440. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  59441. this._scene = scene;
  59442. };
  59443. CollisionCoordinatorLegacy.prototype.destroy = function () {
  59444. //Legacy need no destruction method.
  59445. };
  59446. //No update in legacy mode
  59447. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  59448. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  59449. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  59450. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  59451. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  59452. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  59453. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  59454. if (excludedMesh === void 0) { excludedMesh = null; }
  59455. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  59456. if (collider._retry >= maximumRetry) {
  59457. finalPosition.copyFrom(position);
  59458. return;
  59459. }
  59460. // Check if this is a mesh else camera or -1
  59461. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  59462. collider._initialize(position, velocity, closeDistance);
  59463. // Check all meshes
  59464. for (var index = 0; index < this._scene.meshes.length; index++) {
  59465. var mesh = this._scene.meshes[index];
  59466. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  59467. mesh._checkCollision(collider);
  59468. }
  59469. }
  59470. if (!collider.collisionFound) {
  59471. position.addToRef(velocity, finalPosition);
  59472. return;
  59473. }
  59474. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  59475. collider._getResponse(position, velocity);
  59476. }
  59477. if (velocity.length() <= closeDistance) {
  59478. finalPosition.copyFrom(position);
  59479. return;
  59480. }
  59481. collider._retry++;
  59482. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  59483. };
  59484. return CollisionCoordinatorLegacy;
  59485. }());
  59486. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  59487. })(BABYLON || (BABYLON = {}));
  59488. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  59489. var BABYLON;
  59490. (function (BABYLON) {
  59491. /**
  59492. * A particle represents one of the element emitted by a particle system.
  59493. * This is mainly define by its coordinates, direction, velocity and age.
  59494. */
  59495. var Particle = /** @class */ (function () {
  59496. /**
  59497. * Creates a new instance Particle
  59498. * @param particleSystem the particle system the particle belongs to
  59499. */
  59500. function Particle(
  59501. /**
  59502. * The particle system the particle belongs to.
  59503. */
  59504. particleSystem) {
  59505. this.particleSystem = particleSystem;
  59506. /**
  59507. * The world position of the particle in the scene.
  59508. */
  59509. this.position = BABYLON.Vector3.Zero();
  59510. /**
  59511. * The world direction of the particle in the scene.
  59512. */
  59513. this.direction = BABYLON.Vector3.Zero();
  59514. /**
  59515. * The color of the particle.
  59516. */
  59517. this.color = new BABYLON.Color4(0, 0, 0, 0);
  59518. /**
  59519. * The color change of the particle per step.
  59520. */
  59521. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  59522. /**
  59523. * Defines how long will the life of the particle be.
  59524. */
  59525. this.lifeTime = 1.0;
  59526. /**
  59527. * The current age of the particle.
  59528. */
  59529. this.age = 0;
  59530. /**
  59531. * The current size of the particle.
  59532. */
  59533. this.size = 0;
  59534. /**
  59535. * The current scale of the particle.
  59536. */
  59537. this.scale = new BABYLON.Vector2(1, 1);
  59538. /**
  59539. * The current angle of the particle.
  59540. */
  59541. this.angle = 0;
  59542. /**
  59543. * Defines how fast is the angle changing.
  59544. */
  59545. this.angularSpeed = 0;
  59546. /**
  59547. * Defines the cell index used by the particle to be rendered from a sprite.
  59548. */
  59549. this.cellIndex = 0;
  59550. /** @hidden */
  59551. this._attachedSubEmitters = null;
  59552. /** @hidden */
  59553. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  59554. /** @hidden */
  59555. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  59556. /** @hidden */
  59557. this._currentSize1 = 0;
  59558. /** @hidden */
  59559. this._currentSize2 = 0;
  59560. /** @hidden */
  59561. this._currentAngularSpeed1 = 0;
  59562. /** @hidden */
  59563. this._currentAngularSpeed2 = 0;
  59564. /** @hidden */
  59565. this._currentVelocity1 = 0;
  59566. /** @hidden */
  59567. this._currentVelocity2 = 0;
  59568. /** @hidden */
  59569. this._currentLimitVelocity1 = 0;
  59570. /** @hidden */
  59571. this._currentLimitVelocity2 = 0;
  59572. /** @hidden */
  59573. this._currentDrag1 = 0;
  59574. /** @hidden */
  59575. this._currentDrag2 = 0;
  59576. this.id = Particle._Count++;
  59577. if (!this.particleSystem.isAnimationSheetEnabled) {
  59578. return;
  59579. }
  59580. this.updateCellInfoFromSystem();
  59581. }
  59582. Particle.prototype.updateCellInfoFromSystem = function () {
  59583. this.cellIndex = this.particleSystem.startSpriteCellID;
  59584. };
  59585. /**
  59586. * Defines how the sprite cell index is updated for the particle
  59587. */
  59588. Particle.prototype.updateCellIndex = function () {
  59589. var offsetAge = this.age;
  59590. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  59591. if (this.particleSystem.spriteRandomStartCell) {
  59592. if (this._randomCellOffset === undefined) {
  59593. this._randomCellOffset = Math.random() * this.lifeTime;
  59594. }
  59595. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  59596. changeSpeed = 1;
  59597. offsetAge = this._randomCellOffset;
  59598. }
  59599. else {
  59600. offsetAge += this._randomCellOffset;
  59601. }
  59602. }
  59603. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  59604. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  59605. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  59606. };
  59607. /** @hidden */
  59608. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  59609. if (subEmitter.particleSystem.emitter.position) {
  59610. var emitterMesh = subEmitter.particleSystem.emitter;
  59611. emitterMesh.position.copyFrom(this.position);
  59612. if (subEmitter.inheritDirection) {
  59613. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  59614. // Look at using Y as forward
  59615. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  59616. }
  59617. }
  59618. else {
  59619. var emitterPosition = subEmitter.particleSystem.emitter;
  59620. emitterPosition.copyFrom(this.position);
  59621. }
  59622. // Set inheritedVelocityOffset to be used when new particles are created
  59623. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  59624. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  59625. };
  59626. /** @hidden */
  59627. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  59628. var _this = this;
  59629. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  59630. this._attachedSubEmitters.forEach(function (subEmitter) {
  59631. _this._inheritParticleInfoToSubEmitter(subEmitter);
  59632. });
  59633. }
  59634. };
  59635. /** @hidden */
  59636. Particle.prototype._reset = function () {
  59637. this.age = 0;
  59638. this._currentColorGradient = null;
  59639. this._currentSizeGradient = null;
  59640. this._currentAngularSpeedGradient = null;
  59641. this._currentVelocityGradient = null;
  59642. this._currentLimitVelocityGradient = null;
  59643. this._currentDragGradient = null;
  59644. this.cellIndex = this.particleSystem.startSpriteCellID;
  59645. this._randomCellOffset = undefined;
  59646. };
  59647. /**
  59648. * Copy the properties of particle to another one.
  59649. * @param other the particle to copy the information to.
  59650. */
  59651. Particle.prototype.copyTo = function (other) {
  59652. other.position.copyFrom(this.position);
  59653. if (this._initialDirection) {
  59654. if (other._initialDirection) {
  59655. other._initialDirection.copyFrom(this._initialDirection);
  59656. }
  59657. else {
  59658. other._initialDirection = this._initialDirection.clone();
  59659. }
  59660. }
  59661. else {
  59662. other._initialDirection = null;
  59663. }
  59664. other.direction.copyFrom(this.direction);
  59665. other.color.copyFrom(this.color);
  59666. other.colorStep.copyFrom(this.colorStep);
  59667. other.lifeTime = this.lifeTime;
  59668. other.age = this.age;
  59669. other._randomCellOffset = this._randomCellOffset;
  59670. other.size = this.size;
  59671. other.scale.copyFrom(this.scale);
  59672. other.angle = this.angle;
  59673. other.angularSpeed = this.angularSpeed;
  59674. other.particleSystem = this.particleSystem;
  59675. other.cellIndex = this.cellIndex;
  59676. other.id = this.id;
  59677. other._attachedSubEmitters = this._attachedSubEmitters;
  59678. if (this._currentColorGradient) {
  59679. other._currentColorGradient = this._currentColorGradient;
  59680. other._currentColor1.copyFrom(this._currentColor1);
  59681. other._currentColor2.copyFrom(this._currentColor2);
  59682. }
  59683. if (this._currentSizeGradient) {
  59684. other._currentSizeGradient = this._currentSizeGradient;
  59685. other._currentSize1 = this._currentSize1;
  59686. other._currentSize2 = this._currentSize2;
  59687. }
  59688. if (this._currentAngularSpeedGradient) {
  59689. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  59690. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  59691. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  59692. }
  59693. if (this._currentVelocityGradient) {
  59694. other._currentVelocityGradient = this._currentVelocityGradient;
  59695. other._currentVelocity1 = this._currentVelocity1;
  59696. other._currentVelocity2 = this._currentVelocity2;
  59697. }
  59698. if (this._currentLimitVelocityGradient) {
  59699. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  59700. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  59701. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  59702. }
  59703. if (this._currentDragGradient) {
  59704. other._currentDragGradient = this._currentDragGradient;
  59705. other._currentDrag1 = this._currentDrag1;
  59706. other._currentDrag2 = this._currentDrag2;
  59707. }
  59708. if (this.particleSystem.isAnimationSheetEnabled) {
  59709. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  59710. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  59711. }
  59712. if (this.particleSystem.useRampGradients) {
  59713. other.remapData.copyFrom(this.remapData);
  59714. }
  59715. if (this._randomNoiseCoordinates1) {
  59716. if (other._randomNoiseCoordinates1) {
  59717. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  59718. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  59719. }
  59720. else {
  59721. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  59722. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  59723. }
  59724. }
  59725. };
  59726. Particle._Count = 0;
  59727. return Particle;
  59728. }());
  59729. BABYLON.Particle = Particle;
  59730. })(BABYLON || (BABYLON = {}));
  59731. //# sourceMappingURL=babylon.particle.js.map
  59732. var BABYLON;
  59733. (function (BABYLON) {
  59734. /**
  59735. * This represents the base class for particle system in Babylon.
  59736. * 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.
  59737. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59738. * @example https://doc.babylonjs.com/babylon101/particles
  59739. */
  59740. var BaseParticleSystem = /** @class */ (function () {
  59741. /**
  59742. * Instantiates a particle system.
  59743. * 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.
  59744. * @param name The name of the particle system
  59745. */
  59746. function BaseParticleSystem(name) {
  59747. /**
  59748. * List of animations used by the particle system.
  59749. */
  59750. this.animations = [];
  59751. /**
  59752. * The rendering group used by the Particle system to chose when to render.
  59753. */
  59754. this.renderingGroupId = 0;
  59755. /**
  59756. * The emitter represents the Mesh or position we are attaching the particle system to.
  59757. */
  59758. this.emitter = null;
  59759. /**
  59760. * The maximum number of particles to emit per frame
  59761. */
  59762. this.emitRate = 10;
  59763. /**
  59764. * If you want to launch only a few particles at once, that can be done, as well.
  59765. */
  59766. this.manualEmitCount = -1;
  59767. /**
  59768. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59769. */
  59770. this.updateSpeed = 0.01;
  59771. /**
  59772. * The amount of time the particle system is running (depends of the overall update speed).
  59773. */
  59774. this.targetStopDuration = 0;
  59775. /**
  59776. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59777. */
  59778. this.disposeOnStop = false;
  59779. /**
  59780. * Minimum power of emitting particles.
  59781. */
  59782. this.minEmitPower = 1;
  59783. /**
  59784. * Maximum power of emitting particles.
  59785. */
  59786. this.maxEmitPower = 1;
  59787. /**
  59788. * Minimum life time of emitting particles.
  59789. */
  59790. this.minLifeTime = 1;
  59791. /**
  59792. * Maximum life time of emitting particles.
  59793. */
  59794. this.maxLifeTime = 1;
  59795. /**
  59796. * Minimum Size of emitting particles.
  59797. */
  59798. this.minSize = 1;
  59799. /**
  59800. * Maximum Size of emitting particles.
  59801. */
  59802. this.maxSize = 1;
  59803. /**
  59804. * Minimum scale of emitting particles on X axis.
  59805. */
  59806. this.minScaleX = 1;
  59807. /**
  59808. * Maximum scale of emitting particles on X axis.
  59809. */
  59810. this.maxScaleX = 1;
  59811. /**
  59812. * Minimum scale of emitting particles on Y axis.
  59813. */
  59814. this.minScaleY = 1;
  59815. /**
  59816. * Maximum scale of emitting particles on Y axis.
  59817. */
  59818. this.maxScaleY = 1;
  59819. /**
  59820. * Gets or sets the minimal initial rotation in radians.
  59821. */
  59822. this.minInitialRotation = 0;
  59823. /**
  59824. * Gets or sets the maximal initial rotation in radians.
  59825. */
  59826. this.maxInitialRotation = 0;
  59827. /**
  59828. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59829. */
  59830. this.minAngularSpeed = 0;
  59831. /**
  59832. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59833. */
  59834. this.maxAngularSpeed = 0;
  59835. /**
  59836. * The layer mask we are rendering the particles through.
  59837. */
  59838. this.layerMask = 0x0FFFFFFF;
  59839. /**
  59840. * This can help using your own shader to render the particle system.
  59841. * The according effect will be created
  59842. */
  59843. this.customShader = null;
  59844. /**
  59845. * By default particle system starts as soon as they are created. This prevents the
  59846. * automatic start to happen and let you decide when to start emitting particles.
  59847. */
  59848. this.preventAutoStart = false;
  59849. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59850. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59851. /**
  59852. * Callback triggered when the particle animation is ending.
  59853. */
  59854. this.onAnimationEnd = null;
  59855. /**
  59856. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59857. */
  59858. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59859. /**
  59860. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59861. * to override the particles.
  59862. */
  59863. this.forceDepthWrite = false;
  59864. /** 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 */
  59865. this.preWarmCycles = 0;
  59866. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59867. this.preWarmStepOffset = 1;
  59868. /**
  59869. * 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)
  59870. */
  59871. this.spriteCellChangeSpeed = 1;
  59872. /**
  59873. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59874. */
  59875. this.startSpriteCellID = 0;
  59876. /**
  59877. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59878. */
  59879. this.endSpriteCellID = 0;
  59880. /**
  59881. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59882. */
  59883. this.spriteCellWidth = 0;
  59884. /**
  59885. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59886. */
  59887. this.spriteCellHeight = 0;
  59888. /**
  59889. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  59890. */
  59891. this.spriteRandomStartCell = false;
  59892. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59893. this.translationPivot = new BABYLON.Vector2(0, 0);
  59894. /**
  59895. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  59896. */
  59897. this.beginAnimationOnStart = false;
  59898. /**
  59899. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  59900. */
  59901. this.beginAnimationFrom = 0;
  59902. /**
  59903. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  59904. */
  59905. this.beginAnimationTo = 60;
  59906. /**
  59907. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  59908. */
  59909. this.beginAnimationLoop = false;
  59910. /**
  59911. * You can use gravity if you want to give an orientation to your particles.
  59912. */
  59913. this.gravity = BABYLON.Vector3.Zero();
  59914. this._colorGradients = null;
  59915. this._sizeGradients = null;
  59916. this._lifeTimeGradients = null;
  59917. this._angularSpeedGradients = null;
  59918. this._velocityGradients = null;
  59919. this._limitVelocityGradients = null;
  59920. this._dragGradients = null;
  59921. this._emitRateGradients = null;
  59922. this._startSizeGradients = null;
  59923. this._rampGradients = null;
  59924. this._colorRemapGradients = null;
  59925. this._alphaRemapGradients = null;
  59926. /**
  59927. * Defines the delay in milliseconds before starting the system (0 by default)
  59928. */
  59929. this.startDelay = 0;
  59930. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  59931. this.limitVelocityDamping = 0.4;
  59932. /**
  59933. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59934. */
  59935. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59936. /**
  59937. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59938. */
  59939. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59940. /**
  59941. * Color the particle will have at the end of its lifetime
  59942. */
  59943. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  59944. /**
  59945. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  59946. */
  59947. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59948. /** @hidden */
  59949. this._isSubEmitter = false;
  59950. /**
  59951. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59952. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  59953. */
  59954. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  59955. this._isBillboardBased = true;
  59956. /**
  59957. * Local cache of defines for image processing.
  59958. */
  59959. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  59960. this.id = name;
  59961. this.name = name;
  59962. }
  59963. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  59964. /**
  59965. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  59966. */
  59967. get: function () {
  59968. return this._isAnimationSheetEnabled;
  59969. },
  59970. set: function (value) {
  59971. if (this._isAnimationSheetEnabled == value) {
  59972. return;
  59973. }
  59974. this._isAnimationSheetEnabled = value;
  59975. this._reset();
  59976. },
  59977. enumerable: true,
  59978. configurable: true
  59979. });
  59980. /**
  59981. * Get hosting scene
  59982. * @returns the scene
  59983. */
  59984. BaseParticleSystem.prototype.getScene = function () {
  59985. return this._scene;
  59986. };
  59987. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  59988. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  59989. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  59990. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  59991. };
  59992. /**
  59993. * Gets the current list of drag gradients.
  59994. * You must use addDragGradient and removeDragGradient to udpate this list
  59995. * @returns the list of drag gradients
  59996. */
  59997. BaseParticleSystem.prototype.getDragGradients = function () {
  59998. return this._dragGradients;
  59999. };
  60000. /**
  60001. * Gets the current list of limit velocity gradients.
  60002. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  60003. * @returns the list of limit velocity gradients
  60004. */
  60005. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  60006. return this._limitVelocityGradients;
  60007. };
  60008. /**
  60009. * Gets the current list of color gradients.
  60010. * You must use addColorGradient and removeColorGradient to udpate this list
  60011. * @returns the list of color gradients
  60012. */
  60013. BaseParticleSystem.prototype.getColorGradients = function () {
  60014. return this._colorGradients;
  60015. };
  60016. /**
  60017. * Gets the current list of size gradients.
  60018. * You must use addSizeGradient and removeSizeGradient to udpate this list
  60019. * @returns the list of size gradients
  60020. */
  60021. BaseParticleSystem.prototype.getSizeGradients = function () {
  60022. return this._sizeGradients;
  60023. };
  60024. /**
  60025. * Gets the current list of color remap gradients.
  60026. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  60027. * @returns the list of color remap gradients
  60028. */
  60029. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  60030. return this._colorRemapGradients;
  60031. };
  60032. /**
  60033. * Gets the current list of alpha remap gradients.
  60034. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  60035. * @returns the list of alpha remap gradients
  60036. */
  60037. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  60038. return this._alphaRemapGradients;
  60039. };
  60040. /**
  60041. * Gets the current list of life time gradients.
  60042. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  60043. * @returns the list of life time gradients
  60044. */
  60045. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  60046. return this._lifeTimeGradients;
  60047. };
  60048. /**
  60049. * Gets the current list of angular speed gradients.
  60050. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60051. * @returns the list of angular speed gradients
  60052. */
  60053. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60054. return this._angularSpeedGradients;
  60055. };
  60056. /**
  60057. * Gets the current list of velocity gradients.
  60058. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60059. * @returns the list of velocity gradients
  60060. */
  60061. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60062. return this._velocityGradients;
  60063. };
  60064. /**
  60065. * Gets the current list of start size gradients.
  60066. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60067. * @returns the list of start size gradients
  60068. */
  60069. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60070. return this._startSizeGradients;
  60071. };
  60072. /**
  60073. * Gets the current list of emit rate gradients.
  60074. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60075. * @returns the list of emit rate gradients
  60076. */
  60077. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60078. return this._emitRateGradients;
  60079. };
  60080. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60081. /**
  60082. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60083. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60084. */
  60085. get: function () {
  60086. if (this.particleEmitterType.direction1) {
  60087. return this.particleEmitterType.direction1;
  60088. }
  60089. return BABYLON.Vector3.Zero();
  60090. },
  60091. set: function (value) {
  60092. if (this.particleEmitterType.direction1) {
  60093. this.particleEmitterType.direction1 = value;
  60094. }
  60095. },
  60096. enumerable: true,
  60097. configurable: true
  60098. });
  60099. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60100. /**
  60101. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60102. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60103. */
  60104. get: function () {
  60105. if (this.particleEmitterType.direction2) {
  60106. return this.particleEmitterType.direction2;
  60107. }
  60108. return BABYLON.Vector3.Zero();
  60109. },
  60110. set: function (value) {
  60111. if (this.particleEmitterType.direction2) {
  60112. this.particleEmitterType.direction2 = value;
  60113. }
  60114. },
  60115. enumerable: true,
  60116. configurable: true
  60117. });
  60118. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60119. /**
  60120. * 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.
  60121. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60122. */
  60123. get: function () {
  60124. if (this.particleEmitterType.minEmitBox) {
  60125. return this.particleEmitterType.minEmitBox;
  60126. }
  60127. return BABYLON.Vector3.Zero();
  60128. },
  60129. set: function (value) {
  60130. if (this.particleEmitterType.minEmitBox) {
  60131. this.particleEmitterType.minEmitBox = value;
  60132. }
  60133. },
  60134. enumerable: true,
  60135. configurable: true
  60136. });
  60137. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60138. /**
  60139. * 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.
  60140. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60141. */
  60142. get: function () {
  60143. if (this.particleEmitterType.maxEmitBox) {
  60144. return this.particleEmitterType.maxEmitBox;
  60145. }
  60146. return BABYLON.Vector3.Zero();
  60147. },
  60148. set: function (value) {
  60149. if (this.particleEmitterType.maxEmitBox) {
  60150. this.particleEmitterType.maxEmitBox = value;
  60151. }
  60152. },
  60153. enumerable: true,
  60154. configurable: true
  60155. });
  60156. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60157. /**
  60158. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60159. */
  60160. get: function () {
  60161. return this._isBillboardBased;
  60162. },
  60163. set: function (value) {
  60164. if (this._isBillboardBased === value) {
  60165. return;
  60166. }
  60167. this._isBillboardBased = value;
  60168. this._reset();
  60169. },
  60170. enumerable: true,
  60171. configurable: true
  60172. });
  60173. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60174. /**
  60175. * Gets the image processing configuration used either in this material.
  60176. */
  60177. get: function () {
  60178. return this._imageProcessingConfiguration;
  60179. },
  60180. /**
  60181. * Sets the Default image processing configuration used either in the this material.
  60182. *
  60183. * If sets to null, the scene one is in use.
  60184. */
  60185. set: function (value) {
  60186. this._attachImageProcessingConfiguration(value);
  60187. },
  60188. enumerable: true,
  60189. configurable: true
  60190. });
  60191. /**
  60192. * Attaches a new image processing configuration to the Standard Material.
  60193. * @param configuration
  60194. */
  60195. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  60196. if (configuration === this._imageProcessingConfiguration) {
  60197. return;
  60198. }
  60199. // Pick the scene configuration if needed.
  60200. if (!configuration) {
  60201. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  60202. }
  60203. else {
  60204. this._imageProcessingConfiguration = configuration;
  60205. }
  60206. };
  60207. /** @hidden */
  60208. BaseParticleSystem.prototype._reset = function () {
  60209. };
  60210. /** @hidden */
  60211. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  60212. if (!gradients) {
  60213. return this;
  60214. }
  60215. var index = 0;
  60216. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60217. var valueGradient = gradients_1[_i];
  60218. if (valueGradient.gradient === gradient) {
  60219. gradients.splice(index, 1);
  60220. break;
  60221. }
  60222. index++;
  60223. }
  60224. if (texture) {
  60225. texture.dispose();
  60226. }
  60227. return this;
  60228. };
  60229. /**
  60230. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  60231. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60232. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60233. * @returns the emitter
  60234. */
  60235. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  60236. var particleEmitter = new BABYLON.PointParticleEmitter();
  60237. particleEmitter.direction1 = direction1;
  60238. particleEmitter.direction2 = direction2;
  60239. this.particleEmitterType = particleEmitter;
  60240. return particleEmitter;
  60241. };
  60242. /**
  60243. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  60244. * @param radius The radius of the hemisphere to emit from
  60245. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60246. * @returns the emitter
  60247. */
  60248. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  60249. if (radius === void 0) { radius = 1; }
  60250. if (radiusRange === void 0) { radiusRange = 1; }
  60251. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  60252. this.particleEmitterType = particleEmitter;
  60253. return particleEmitter;
  60254. };
  60255. /**
  60256. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  60257. * @param radius The radius of the sphere to emit from
  60258. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60259. * @returns the emitter
  60260. */
  60261. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  60262. if (radius === void 0) { radius = 1; }
  60263. if (radiusRange === void 0) { radiusRange = 1; }
  60264. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  60265. this.particleEmitterType = particleEmitter;
  60266. return particleEmitter;
  60267. };
  60268. /**
  60269. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  60270. * @param radius The radius of the sphere to emit from
  60271. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  60272. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  60273. * @returns the emitter
  60274. */
  60275. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  60276. if (radius === void 0) { radius = 1; }
  60277. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60278. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60279. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  60280. this.particleEmitterType = particleEmitter;
  60281. return particleEmitter;
  60282. };
  60283. /**
  60284. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  60285. * @param radius The radius of the emission cylinder
  60286. * @param height The height of the emission cylinder
  60287. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  60288. * @param directionRandomizer How much to randomize the particle direction [0-1]
  60289. * @returns the emitter
  60290. */
  60291. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  60292. if (radius === void 0) { radius = 1; }
  60293. if (height === void 0) { height = 1; }
  60294. if (radiusRange === void 0) { radiusRange = 1; }
  60295. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60296. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  60297. this.particleEmitterType = particleEmitter;
  60298. return particleEmitter;
  60299. };
  60300. /**
  60301. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  60302. * @param radius The radius of the cylinder to emit from
  60303. * @param height The height of the emission cylinder
  60304. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60305. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  60306. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  60307. * @returns the emitter
  60308. */
  60309. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  60310. if (radius === void 0) { radius = 1; }
  60311. if (height === void 0) { height = 1; }
  60312. if (radiusRange === void 0) { radiusRange = 1; }
  60313. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60314. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60315. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  60316. this.particleEmitterType = particleEmitter;
  60317. return particleEmitter;
  60318. };
  60319. /**
  60320. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  60321. * @param radius The radius of the cone to emit from
  60322. * @param angle The base angle of the cone
  60323. * @returns the emitter
  60324. */
  60325. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  60326. if (radius === void 0) { radius = 1; }
  60327. if (angle === void 0) { angle = Math.PI / 4; }
  60328. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  60329. this.particleEmitterType = particleEmitter;
  60330. return particleEmitter;
  60331. };
  60332. /**
  60333. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  60334. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60335. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60336. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60337. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60338. * @returns the emitter
  60339. */
  60340. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  60341. var particleEmitter = new BABYLON.BoxParticleEmitter();
  60342. this.particleEmitterType = particleEmitter;
  60343. this.direction1 = direction1;
  60344. this.direction2 = direction2;
  60345. this.minEmitBox = minEmitBox;
  60346. this.maxEmitBox = maxEmitBox;
  60347. return particleEmitter;
  60348. };
  60349. /**
  60350. * Source color is added to the destination color without alpha affecting the result
  60351. */
  60352. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  60353. /**
  60354. * Blend current color and particle color using particle’s alpha
  60355. */
  60356. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  60357. /**
  60358. * Add current color and particle color multiplied by particle’s alpha
  60359. */
  60360. BaseParticleSystem.BLENDMODE_ADD = 2;
  60361. /**
  60362. * Multiply current color with particle color
  60363. */
  60364. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  60365. /**
  60366. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  60367. */
  60368. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  60369. return BaseParticleSystem;
  60370. }());
  60371. BABYLON.BaseParticleSystem = BaseParticleSystem;
  60372. })(BABYLON || (BABYLON = {}));
  60373. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  60374. var BABYLON;
  60375. (function (BABYLON) {
  60376. /**
  60377. * This represents a particle system in Babylon.
  60378. * 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.
  60379. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60380. * @example https://doc.babylonjs.com/babylon101/particles
  60381. */
  60382. var ParticleSystem = /** @class */ (function (_super) {
  60383. __extends(ParticleSystem, _super);
  60384. /**
  60385. * Instantiates a particle system.
  60386. * 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.
  60387. * @param name The name of the particle system
  60388. * @param capacity The max number of particles alive at the same time
  60389. * @param scene The scene the particle system belongs to
  60390. * @param customEffect a custom effect used to change the way particles are rendered by default
  60391. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60392. * @param epsilon Offset used to render the particles
  60393. */
  60394. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  60395. if (customEffect === void 0) { customEffect = null; }
  60396. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60397. if (epsilon === void 0) { epsilon = 0.01; }
  60398. var _this = _super.call(this, name) || this;
  60399. /**
  60400. * @hidden
  60401. */
  60402. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  60403. /**
  60404. * An event triggered when the system is disposed
  60405. */
  60406. _this.onDisposeObservable = new BABYLON.Observable();
  60407. _this._particles = new Array();
  60408. _this._stockParticles = new Array();
  60409. _this._newPartsExcess = 0;
  60410. _this._vertexBuffers = {};
  60411. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  60412. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  60413. _this._scaledDirection = BABYLON.Vector3.Zero();
  60414. _this._scaledGravity = BABYLON.Vector3.Zero();
  60415. _this._currentRenderId = -1;
  60416. _this._useInstancing = false;
  60417. _this._started = false;
  60418. _this._stopped = false;
  60419. _this._actualFrame = 0;
  60420. /** @hidden */
  60421. _this._currentEmitRate1 = 0;
  60422. /** @hidden */
  60423. _this._currentEmitRate2 = 0;
  60424. /** @hidden */
  60425. _this._currentStartSize1 = 0;
  60426. /** @hidden */
  60427. _this._currentStartSize2 = 0;
  60428. _this._rawTextureWidth = 256;
  60429. _this._useRampGradients = false;
  60430. /**
  60431. * @hidden
  60432. * If the particle systems emitter should be disposed when the particle system is disposed
  60433. */
  60434. _this._disposeEmitterOnDispose = false;
  60435. // start of sub system methods
  60436. /**
  60437. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  60438. * Its lifetime will start back at 0.
  60439. */
  60440. _this.recycleParticle = function (particle) {
  60441. // move particle from activeParticle list to stock particles
  60442. var lastParticle = _this._particles.pop();
  60443. if (lastParticle !== particle) {
  60444. lastParticle.copyTo(particle);
  60445. }
  60446. _this._stockParticles.push(lastParticle);
  60447. };
  60448. _this._createParticle = function () {
  60449. var particle;
  60450. if (_this._stockParticles.length !== 0) {
  60451. particle = _this._stockParticles.pop();
  60452. particle._reset();
  60453. }
  60454. else {
  60455. particle = new BABYLON.Particle(_this);
  60456. }
  60457. // Attach emitters
  60458. if (_this._subEmitters && _this._subEmitters.length > 0) {
  60459. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  60460. particle._attachedSubEmitters = [];
  60461. subEmitters.forEach(function (subEmitter) {
  60462. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  60463. var newEmitter = subEmitter.clone();
  60464. particle._attachedSubEmitters.push(newEmitter);
  60465. newEmitter.particleSystem.start();
  60466. }
  60467. });
  60468. }
  60469. return particle;
  60470. };
  60471. _this._emitFromParticle = function (particle) {
  60472. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  60473. return;
  60474. }
  60475. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  60476. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  60477. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  60478. var subSystem = subEmitter.clone();
  60479. particle._inheritParticleInfoToSubEmitter(subSystem);
  60480. subSystem.particleSystem._rootParticleSystem = _this;
  60481. _this.activeSubSystems.push(subSystem.particleSystem);
  60482. subSystem.particleSystem.start();
  60483. }
  60484. });
  60485. };
  60486. _this._capacity = capacity;
  60487. _this._epsilon = epsilon;
  60488. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60489. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60490. // Setup the default processing configuration to the scene.
  60491. _this._attachImageProcessingConfiguration(null);
  60492. _this._customEffect = customEffect;
  60493. _this._scene.particleSystems.push(_this);
  60494. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  60495. _this._createIndexBuffer();
  60496. _this._createVertexBuffers();
  60497. // Default emitter type
  60498. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60499. // Update
  60500. _this.updateFunction = function (particles) {
  60501. var noiseTextureSize = null;
  60502. var noiseTextureData = null;
  60503. if (_this.noiseTexture) { // We need to get texture data back to CPU
  60504. noiseTextureSize = _this.noiseTexture.getSize();
  60505. noiseTextureData = (_this.noiseTexture.getContent());
  60506. }
  60507. var _loop_1 = function () {
  60508. particle = particles[index];
  60509. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  60510. var previousAge = particle.age;
  60511. particle.age += scaledUpdateSpeed;
  60512. // Evaluate step to death
  60513. if (particle.age > particle.lifeTime) {
  60514. var diff = particle.age - previousAge;
  60515. var oldDiff = particle.lifeTime - previousAge;
  60516. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  60517. particle.age = particle.lifeTime;
  60518. }
  60519. var ratio = particle.age / particle.lifeTime;
  60520. // Color
  60521. if (_this._colorGradients && _this._colorGradients.length > 0) {
  60522. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  60523. if (currentGradient !== particle._currentColorGradient) {
  60524. particle._currentColor1.copyFrom(particle._currentColor2);
  60525. nextGradient.getColorToRef(particle._currentColor2);
  60526. particle._currentColorGradient = currentGradient;
  60527. }
  60528. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  60529. });
  60530. }
  60531. else {
  60532. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  60533. particle.color.addInPlace(_this._scaledColorStep);
  60534. if (particle.color.a < 0) {
  60535. particle.color.a = 0;
  60536. }
  60537. }
  60538. // Angular speed
  60539. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  60540. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  60541. if (currentGradient !== particle._currentAngularSpeedGradient) {
  60542. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  60543. particle._currentAngularSpeed2 = nextGradient.getFactor();
  60544. particle._currentAngularSpeedGradient = currentGradient;
  60545. }
  60546. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  60547. });
  60548. }
  60549. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  60550. // Direction
  60551. var directionScale = scaledUpdateSpeed;
  60552. /// Velocity
  60553. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  60554. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  60555. if (currentGradient !== particle._currentVelocityGradient) {
  60556. particle._currentVelocity1 = particle._currentVelocity2;
  60557. particle._currentVelocity2 = nextGradient.getFactor();
  60558. particle._currentVelocityGradient = currentGradient;
  60559. }
  60560. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  60561. });
  60562. }
  60563. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  60564. /// Limit velocity
  60565. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  60566. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  60567. if (currentGradient !== particle._currentLimitVelocityGradient) {
  60568. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  60569. particle._currentLimitVelocity2 = nextGradient.getFactor();
  60570. particle._currentLimitVelocityGradient = currentGradient;
  60571. }
  60572. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  60573. var currentVelocity = particle.direction.length();
  60574. if (currentVelocity > limitVelocity) {
  60575. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  60576. }
  60577. });
  60578. }
  60579. /// Drag
  60580. if (_this._dragGradients && _this._dragGradients.length > 0) {
  60581. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  60582. if (currentGradient !== particle._currentDragGradient) {
  60583. particle._currentDrag1 = particle._currentDrag2;
  60584. particle._currentDrag2 = nextGradient.getFactor();
  60585. particle._currentDragGradient = currentGradient;
  60586. }
  60587. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  60588. _this._scaledDirection.scaleInPlace(1.0 - drag);
  60589. });
  60590. }
  60591. particle.position.addInPlace(_this._scaledDirection);
  60592. // Noise
  60593. if (noiseTextureData && noiseTextureSize) {
  60594. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60595. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60596. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60597. var force = BABYLON.Tmp.Vector3[0];
  60598. var scaledForce = BABYLON.Tmp.Vector3[1];
  60599. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  60600. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  60601. particle.direction.addInPlace(scaledForce);
  60602. }
  60603. // Gravity
  60604. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  60605. particle.direction.addInPlace(_this._scaledGravity);
  60606. // Size
  60607. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  60608. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  60609. if (currentGradient !== particle._currentSizeGradient) {
  60610. particle._currentSize1 = particle._currentSize2;
  60611. particle._currentSize2 = nextGradient.getFactor();
  60612. particle._currentSizeGradient = currentGradient;
  60613. }
  60614. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  60615. });
  60616. }
  60617. // Remap data
  60618. if (_this._useRampGradients) {
  60619. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  60620. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  60621. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60622. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60623. particle.remapData.x = min;
  60624. particle.remapData.y = max - min;
  60625. });
  60626. }
  60627. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  60628. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  60629. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60630. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60631. particle.remapData.z = min;
  60632. particle.remapData.w = max - min;
  60633. });
  60634. }
  60635. }
  60636. if (_this._isAnimationSheetEnabled) {
  60637. particle.updateCellIndex();
  60638. }
  60639. // Update the position of the attached sub-emitters to match their attached particle
  60640. particle._inheritParticleInfoToSubEmitters();
  60641. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  60642. _this._emitFromParticle(particle);
  60643. if (particle._attachedSubEmitters) {
  60644. particle._attachedSubEmitters.forEach(function (subEmitter) {
  60645. subEmitter.particleSystem.disposeOnStop = true;
  60646. subEmitter.particleSystem.stop();
  60647. });
  60648. particle._attachedSubEmitters = null;
  60649. }
  60650. _this.recycleParticle(particle);
  60651. index--;
  60652. return "continue";
  60653. }
  60654. };
  60655. var particle;
  60656. for (var index = 0; index < particles.length; index++) {
  60657. _loop_1();
  60658. }
  60659. };
  60660. return _this;
  60661. }
  60662. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  60663. /**
  60664. * Sets a callback that will be triggered when the system is disposed
  60665. */
  60666. set: function (callback) {
  60667. if (this._onDisposeObserver) {
  60668. this.onDisposeObservable.remove(this._onDisposeObserver);
  60669. }
  60670. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  60671. },
  60672. enumerable: true,
  60673. configurable: true
  60674. });
  60675. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  60676. /** Gets or sets a boolean indicating that ramp gradients must be used
  60677. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  60678. */
  60679. get: function () {
  60680. return this._useRampGradients;
  60681. },
  60682. set: function (value) {
  60683. if (this._useRampGradients === value) {
  60684. return;
  60685. }
  60686. this._useRampGradients = value;
  60687. this._resetEffect();
  60688. },
  60689. enumerable: true,
  60690. configurable: true
  60691. });
  60692. Object.defineProperty(ParticleSystem.prototype, "particles", {
  60693. //end of Sub-emitter
  60694. /**
  60695. * Gets the current list of active particles
  60696. */
  60697. get: function () {
  60698. return this._particles;
  60699. },
  60700. enumerable: true,
  60701. configurable: true
  60702. });
  60703. /**
  60704. * Returns the string "ParticleSystem"
  60705. * @returns a string containing the class name
  60706. */
  60707. ParticleSystem.prototype.getClassName = function () {
  60708. return "ParticleSystem";
  60709. };
  60710. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  60711. var newGradient = new BABYLON.FactorGradient();
  60712. newGradient.gradient = gradient;
  60713. newGradient.factor1 = factor;
  60714. newGradient.factor2 = factor2;
  60715. factorGradients.push(newGradient);
  60716. factorGradients.sort(function (a, b) {
  60717. if (a.gradient < b.gradient) {
  60718. return -1;
  60719. }
  60720. else if (a.gradient > b.gradient) {
  60721. return 1;
  60722. }
  60723. return 0;
  60724. });
  60725. };
  60726. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  60727. if (!factorGradients) {
  60728. return;
  60729. }
  60730. var index = 0;
  60731. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  60732. var factorGradient = factorGradients_1[_i];
  60733. if (factorGradient.gradient === gradient) {
  60734. factorGradients.splice(index, 1);
  60735. break;
  60736. }
  60737. index++;
  60738. }
  60739. };
  60740. /**
  60741. * Adds a new life time gradient
  60742. * @param gradient defines the gradient to use (between 0 and 1)
  60743. * @param factor defines the life time factor to affect to the specified gradient
  60744. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60745. * @returns the current particle system
  60746. */
  60747. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  60748. if (!this._lifeTimeGradients) {
  60749. this._lifeTimeGradients = [];
  60750. }
  60751. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  60752. return this;
  60753. };
  60754. /**
  60755. * Remove a specific life time gradient
  60756. * @param gradient defines the gradient to remove
  60757. * @returns the current particle system
  60758. */
  60759. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  60760. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  60761. return this;
  60762. };
  60763. /**
  60764. * Adds a new size gradient
  60765. * @param gradient defines the gradient to use (between 0 and 1)
  60766. * @param factor defines the size factor to affect to the specified gradient
  60767. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60768. * @returns the current particle system
  60769. */
  60770. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  60771. if (!this._sizeGradients) {
  60772. this._sizeGradients = [];
  60773. }
  60774. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  60775. return this;
  60776. };
  60777. /**
  60778. * Remove a specific size gradient
  60779. * @param gradient defines the gradient to remove
  60780. * @returns the current particle system
  60781. */
  60782. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60783. this._removeFactorGradient(this._sizeGradients, gradient);
  60784. return this;
  60785. };
  60786. /**
  60787. * Adds a new color remap gradient
  60788. * @param gradient defines the gradient to use (between 0 and 1)
  60789. * @param min defines the color remap minimal range
  60790. * @param max defines the color remap maximal range
  60791. * @returns the current particle system
  60792. */
  60793. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  60794. if (!this._colorRemapGradients) {
  60795. this._colorRemapGradients = [];
  60796. }
  60797. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  60798. return this;
  60799. };
  60800. /**
  60801. * Remove a specific color remap gradient
  60802. * @param gradient defines the gradient to remove
  60803. * @returns the current particle system
  60804. */
  60805. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  60806. this._removeFactorGradient(this._colorRemapGradients, gradient);
  60807. return this;
  60808. };
  60809. /**
  60810. * Adds a new alpha remap gradient
  60811. * @param gradient defines the gradient to use (between 0 and 1)
  60812. * @param min defines the alpha remap minimal range
  60813. * @param max defines the alpha remap maximal range
  60814. * @returns the current particle system
  60815. */
  60816. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  60817. if (!this._alphaRemapGradients) {
  60818. this._alphaRemapGradients = [];
  60819. }
  60820. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  60821. return this;
  60822. };
  60823. /**
  60824. * Remove a specific alpha remap gradient
  60825. * @param gradient defines the gradient to remove
  60826. * @returns the current particle system
  60827. */
  60828. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  60829. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  60830. return this;
  60831. };
  60832. /**
  60833. * Adds a new angular speed gradient
  60834. * @param gradient defines the gradient to use (between 0 and 1)
  60835. * @param factor defines the angular speed to affect to the specified gradient
  60836. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60837. * @returns the current particle system
  60838. */
  60839. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  60840. if (!this._angularSpeedGradients) {
  60841. this._angularSpeedGradients = [];
  60842. }
  60843. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  60844. return this;
  60845. };
  60846. /**
  60847. * Remove a specific angular speed gradient
  60848. * @param gradient defines the gradient to remove
  60849. * @returns the current particle system
  60850. */
  60851. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60852. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  60853. return this;
  60854. };
  60855. /**
  60856. * Adds a new velocity gradient
  60857. * @param gradient defines the gradient to use (between 0 and 1)
  60858. * @param factor defines the velocity to affect to the specified gradient
  60859. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60860. * @returns the current particle system
  60861. */
  60862. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  60863. if (!this._velocityGradients) {
  60864. this._velocityGradients = [];
  60865. }
  60866. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  60867. return this;
  60868. };
  60869. /**
  60870. * Remove a specific velocity gradient
  60871. * @param gradient defines the gradient to remove
  60872. * @returns the current particle system
  60873. */
  60874. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60875. this._removeFactorGradient(this._velocityGradients, gradient);
  60876. return this;
  60877. };
  60878. /**
  60879. * Adds a new limit velocity gradient
  60880. * @param gradient defines the gradient to use (between 0 and 1)
  60881. * @param factor defines the limit velocity value to affect to the specified gradient
  60882. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60883. * @returns the current particle system
  60884. */
  60885. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  60886. if (!this._limitVelocityGradients) {
  60887. this._limitVelocityGradients = [];
  60888. }
  60889. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  60890. return this;
  60891. };
  60892. /**
  60893. * Remove a specific limit velocity gradient
  60894. * @param gradient defines the gradient to remove
  60895. * @returns the current particle system
  60896. */
  60897. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60898. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  60899. return this;
  60900. };
  60901. /**
  60902. * Adds a new drag gradient
  60903. * @param gradient defines the gradient to use (between 0 and 1)
  60904. * @param factor defines the drag value to affect to the specified gradient
  60905. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60906. * @returns the current particle system
  60907. */
  60908. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  60909. if (!this._dragGradients) {
  60910. this._dragGradients = [];
  60911. }
  60912. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  60913. return this;
  60914. };
  60915. /**
  60916. * Remove a specific drag gradient
  60917. * @param gradient defines the gradient to remove
  60918. * @returns the current particle system
  60919. */
  60920. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  60921. this._removeFactorGradient(this._dragGradients, gradient);
  60922. return this;
  60923. };
  60924. /**
  60925. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  60926. * @param gradient defines the gradient to use (between 0 and 1)
  60927. * @param factor defines the emit rate value to affect to the specified gradient
  60928. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60929. * @returns the current particle system
  60930. */
  60931. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  60932. if (!this._emitRateGradients) {
  60933. this._emitRateGradients = [];
  60934. }
  60935. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  60936. return this;
  60937. };
  60938. /**
  60939. * Remove a specific emit rate gradient
  60940. * @param gradient defines the gradient to remove
  60941. * @returns the current particle system
  60942. */
  60943. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  60944. this._removeFactorGradient(this._emitRateGradients, gradient);
  60945. return this;
  60946. };
  60947. /**
  60948. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  60949. * @param gradient defines the gradient to use (between 0 and 1)
  60950. * @param factor defines the start size value to affect to the specified gradient
  60951. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60952. * @returns the current particle system
  60953. */
  60954. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  60955. if (!this._startSizeGradients) {
  60956. this._startSizeGradients = [];
  60957. }
  60958. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  60959. return this;
  60960. };
  60961. /**
  60962. * Remove a specific start size gradient
  60963. * @param gradient defines the gradient to remove
  60964. * @returns the current particle system
  60965. */
  60966. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  60967. this._removeFactorGradient(this._emitRateGradients, gradient);
  60968. return this;
  60969. };
  60970. ParticleSystem.prototype._createRampGradientTexture = function () {
  60971. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  60972. return;
  60973. }
  60974. var data = new Uint8Array(this._rawTextureWidth * 4);
  60975. var tmpColor = BABYLON.Tmp.Color3[0];
  60976. for (var x = 0; x < this._rawTextureWidth; x++) {
  60977. var ratio = x / this._rawTextureWidth;
  60978. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  60979. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  60980. data[x * 4] = tmpColor.r * 255;
  60981. data[x * 4 + 1] = tmpColor.g * 255;
  60982. data[x * 4 + 2] = tmpColor.b * 255;
  60983. data[x * 4 + 3] = 255;
  60984. });
  60985. }
  60986. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60987. };
  60988. /**
  60989. * Gets the current list of ramp gradients.
  60990. * You must use addRampGradient and removeRampGradient to udpate this list
  60991. * @returns the list of ramp gradients
  60992. */
  60993. ParticleSystem.prototype.getRampGradients = function () {
  60994. return this._rampGradients;
  60995. };
  60996. /**
  60997. * Adds a new ramp gradient used to remap particle colors
  60998. * @param gradient defines the gradient to use (between 0 and 1)
  60999. * @param color defines the color to affect to the specified gradient
  61000. * @returns the current particle system
  61001. */
  61002. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61003. if (!this._rampGradients) {
  61004. this._rampGradients = [];
  61005. }
  61006. var rampGradient = new BABYLON.Color3Gradient();
  61007. rampGradient.gradient = gradient;
  61008. rampGradient.color = color;
  61009. this._rampGradients.push(rampGradient);
  61010. this._rampGradients.sort(function (a, b) {
  61011. if (a.gradient < b.gradient) {
  61012. return -1;
  61013. }
  61014. else if (a.gradient > b.gradient) {
  61015. return 1;
  61016. }
  61017. return 0;
  61018. });
  61019. if (this._rampGradientsTexture) {
  61020. this._rampGradientsTexture.dispose();
  61021. this._rampGradientsTexture = null;
  61022. }
  61023. this._createRampGradientTexture();
  61024. return this;
  61025. };
  61026. /**
  61027. * Remove a specific ramp gradient
  61028. * @param gradient defines the gradient to remove
  61029. * @returns the current particle system
  61030. */
  61031. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  61032. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  61033. this._rampGradientsTexture = null;
  61034. if (this._rampGradients && this._rampGradients.length > 0) {
  61035. this._createRampGradientTexture();
  61036. }
  61037. return this;
  61038. };
  61039. /**
  61040. * Adds a new color gradient
  61041. * @param gradient defines the gradient to use (between 0 and 1)
  61042. * @param color1 defines the color to affect to the specified gradient
  61043. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61044. * @returns this particle system
  61045. */
  61046. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61047. if (!this._colorGradients) {
  61048. this._colorGradients = [];
  61049. }
  61050. var colorGradient = new BABYLON.ColorGradient();
  61051. colorGradient.gradient = gradient;
  61052. colorGradient.color1 = color1;
  61053. colorGradient.color2 = color2;
  61054. this._colorGradients.push(colorGradient);
  61055. this._colorGradients.sort(function (a, b) {
  61056. if (a.gradient < b.gradient) {
  61057. return -1;
  61058. }
  61059. else if (a.gradient > b.gradient) {
  61060. return 1;
  61061. }
  61062. return 0;
  61063. });
  61064. return this;
  61065. };
  61066. /**
  61067. * Remove a specific color gradient
  61068. * @param gradient defines the gradient to remove
  61069. * @returns this particle system
  61070. */
  61071. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61072. if (!this._colorGradients) {
  61073. return this;
  61074. }
  61075. var index = 0;
  61076. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61077. var colorGradient = _a[_i];
  61078. if (colorGradient.gradient === gradient) {
  61079. this._colorGradients.splice(index, 1);
  61080. break;
  61081. }
  61082. index++;
  61083. }
  61084. return this;
  61085. };
  61086. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61087. u = Math.abs(u) * 0.5 + 0.5;
  61088. v = Math.abs(v) * 0.5 + 0.5;
  61089. var wrappedU = ((u * width) % width) | 0;
  61090. var wrappedV = ((v * height) % height) | 0;
  61091. var position = (wrappedU + wrappedV * width) * 4;
  61092. return pixels[position] / 255;
  61093. };
  61094. ParticleSystem.prototype._reset = function () {
  61095. this._resetEffect();
  61096. };
  61097. ParticleSystem.prototype._resetEffect = function () {
  61098. if (this._vertexBuffer) {
  61099. this._vertexBuffer.dispose();
  61100. this._vertexBuffer = null;
  61101. }
  61102. if (this._spriteBuffer) {
  61103. this._spriteBuffer.dispose();
  61104. this._spriteBuffer = null;
  61105. }
  61106. this._createVertexBuffers();
  61107. };
  61108. ParticleSystem.prototype._createVertexBuffers = function () {
  61109. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61110. if (this._isAnimationSheetEnabled) {
  61111. this._vertexBufferSize += 1;
  61112. }
  61113. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61114. this._vertexBufferSize += 3;
  61115. }
  61116. if (this._useRampGradients) {
  61117. this._vertexBufferSize += 4;
  61118. }
  61119. var engine = this._scene.getEngine();
  61120. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61121. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61122. var dataOffset = 0;
  61123. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61125. dataOffset += 3;
  61126. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61127. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61128. dataOffset += 4;
  61129. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61130. this._vertexBuffers["angle"] = options;
  61131. dataOffset += 1;
  61132. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61133. this._vertexBuffers["size"] = size;
  61134. dataOffset += 2;
  61135. if (this._isAnimationSheetEnabled) {
  61136. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61137. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61138. dataOffset += 1;
  61139. }
  61140. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61141. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61142. this._vertexBuffers["direction"] = directionBuffer;
  61143. dataOffset += 3;
  61144. }
  61145. if (this._useRampGradients) {
  61146. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61147. this._vertexBuffers["remapData"] = rampDataBuffer;
  61148. dataOffset += 4;
  61149. }
  61150. var offsets;
  61151. if (this._useInstancing) {
  61152. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61153. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61154. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61155. }
  61156. else {
  61157. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61158. dataOffset += 2;
  61159. }
  61160. this._vertexBuffers["offset"] = offsets;
  61161. };
  61162. ParticleSystem.prototype._createIndexBuffer = function () {
  61163. if (this._useInstancing) {
  61164. return;
  61165. }
  61166. var indices = [];
  61167. var index = 0;
  61168. for (var count = 0; count < this._capacity; count++) {
  61169. indices.push(index);
  61170. indices.push(index + 1);
  61171. indices.push(index + 2);
  61172. indices.push(index);
  61173. indices.push(index + 2);
  61174. indices.push(index + 3);
  61175. index += 4;
  61176. }
  61177. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61178. };
  61179. /**
  61180. * Gets the maximum number of particles active at the same time.
  61181. * @returns The max number of active particles.
  61182. */
  61183. ParticleSystem.prototype.getCapacity = function () {
  61184. return this._capacity;
  61185. };
  61186. /**
  61187. * Gets whether there are still active particles in the system.
  61188. * @returns True if it is alive, otherwise false.
  61189. */
  61190. ParticleSystem.prototype.isAlive = function () {
  61191. return this._alive;
  61192. };
  61193. /**
  61194. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61195. * @returns True if it has been started, otherwise false.
  61196. */
  61197. ParticleSystem.prototype.isStarted = function () {
  61198. return this._started;
  61199. };
  61200. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  61201. var _this = this;
  61202. this._subEmitters = new Array();
  61203. if (this.subEmitters) {
  61204. this.subEmitters.forEach(function (subEmitter) {
  61205. if (subEmitter instanceof ParticleSystem) {
  61206. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  61207. }
  61208. else if (subEmitter instanceof BABYLON.SubEmitter) {
  61209. _this._subEmitters.push([subEmitter]);
  61210. }
  61211. else if (subEmitter instanceof Array) {
  61212. _this._subEmitters.push(subEmitter);
  61213. }
  61214. });
  61215. }
  61216. };
  61217. /**
  61218. * Starts the particle system and begins to emit
  61219. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61220. */
  61221. ParticleSystem.prototype.start = function (delay) {
  61222. var _this = this;
  61223. if (delay === void 0) { delay = this.startDelay; }
  61224. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61225. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61226. }
  61227. if (delay) {
  61228. setTimeout(function () {
  61229. _this.start(0);
  61230. }, delay);
  61231. return;
  61232. }
  61233. // Convert the subEmitters field to the constant type field _subEmitters
  61234. this._prepareSubEmitterInternalArray();
  61235. this._started = true;
  61236. this._stopped = false;
  61237. this._actualFrame = 0;
  61238. if (this._subEmitters && this._subEmitters.length != 0) {
  61239. this.activeSubSystems = new Array();
  61240. }
  61241. // Reset emit gradient so it acts the same on every start
  61242. if (this._emitRateGradients) {
  61243. if (this._emitRateGradients.length > 0) {
  61244. this._currentEmitRateGradient = this._emitRateGradients[0];
  61245. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  61246. this._currentEmitRate2 = this._currentEmitRate1;
  61247. }
  61248. if (this._emitRateGradients.length > 1) {
  61249. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  61250. }
  61251. }
  61252. // Reset start size gradient so it acts the same on every start
  61253. if (this._startSizeGradients) {
  61254. if (this._startSizeGradients.length > 0) {
  61255. this._currentStartSizeGradient = this._startSizeGradients[0];
  61256. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  61257. this._currentStartSize2 = this._currentStartSize1;
  61258. }
  61259. if (this._startSizeGradients.length > 1) {
  61260. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  61261. }
  61262. }
  61263. if (this.preWarmCycles) {
  61264. if (this.emitter instanceof BABYLON.AbstractMesh) {
  61265. this.emitter.computeWorldMatrix(true);
  61266. }
  61267. var noiseTextureAsProcedural_1 = this.noiseTexture;
  61268. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  61269. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  61270. setTimeout(function () {
  61271. for (var index = 0; index < _this.preWarmCycles; index++) {
  61272. _this.animate(true);
  61273. noiseTextureAsProcedural_1.render();
  61274. }
  61275. });
  61276. });
  61277. }
  61278. else {
  61279. for (var index = 0; index < this.preWarmCycles; index++) {
  61280. this.animate(true);
  61281. }
  61282. }
  61283. }
  61284. // Animations
  61285. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  61286. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  61287. }
  61288. };
  61289. /**
  61290. * Stops the particle system.
  61291. * @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.
  61292. */
  61293. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  61294. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  61295. this._stopped = true;
  61296. if (stopSubEmitters) {
  61297. this._stopSubEmitters();
  61298. }
  61299. };
  61300. // animation sheet
  61301. /**
  61302. * Remove all active particles
  61303. */
  61304. ParticleSystem.prototype.reset = function () {
  61305. this._stockParticles = [];
  61306. this._particles = [];
  61307. };
  61308. /**
  61309. * @hidden (for internal use only)
  61310. */
  61311. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  61312. var offset = index * this._vertexBufferSize;
  61313. this._vertexData[offset++] = particle.position.x;
  61314. this._vertexData[offset++] = particle.position.y;
  61315. this._vertexData[offset++] = particle.position.z;
  61316. this._vertexData[offset++] = particle.color.r;
  61317. this._vertexData[offset++] = particle.color.g;
  61318. this._vertexData[offset++] = particle.color.b;
  61319. this._vertexData[offset++] = particle.color.a;
  61320. this._vertexData[offset++] = particle.angle;
  61321. this._vertexData[offset++] = particle.scale.x * particle.size;
  61322. this._vertexData[offset++] = particle.scale.y * particle.size;
  61323. if (this._isAnimationSheetEnabled) {
  61324. this._vertexData[offset++] = particle.cellIndex;
  61325. }
  61326. if (!this._isBillboardBased) {
  61327. if (particle._initialDirection) {
  61328. this._vertexData[offset++] = particle._initialDirection.x;
  61329. this._vertexData[offset++] = particle._initialDirection.y;
  61330. this._vertexData[offset++] = particle._initialDirection.z;
  61331. }
  61332. else {
  61333. this._vertexData[offset++] = particle.direction.x;
  61334. this._vertexData[offset++] = particle.direction.y;
  61335. this._vertexData[offset++] = particle.direction.z;
  61336. }
  61337. }
  61338. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61339. this._vertexData[offset++] = particle.direction.x;
  61340. this._vertexData[offset++] = particle.direction.y;
  61341. this._vertexData[offset++] = particle.direction.z;
  61342. }
  61343. if (this._useRampGradients) {
  61344. this._vertexData[offset++] = particle.remapData.x;
  61345. this._vertexData[offset++] = particle.remapData.y;
  61346. this._vertexData[offset++] = particle.remapData.z;
  61347. this._vertexData[offset++] = particle.remapData.w;
  61348. }
  61349. if (!this._useInstancing) {
  61350. if (this._isAnimationSheetEnabled) {
  61351. if (offsetX === 0) {
  61352. offsetX = this._epsilon;
  61353. }
  61354. else if (offsetX === 1) {
  61355. offsetX = 1 - this._epsilon;
  61356. }
  61357. if (offsetY === 0) {
  61358. offsetY = this._epsilon;
  61359. }
  61360. else if (offsetY === 1) {
  61361. offsetY = 1 - this._epsilon;
  61362. }
  61363. }
  61364. this._vertexData[offset++] = offsetX;
  61365. this._vertexData[offset++] = offsetY;
  61366. }
  61367. };
  61368. ParticleSystem.prototype._stopSubEmitters = function () {
  61369. if (!this.activeSubSystems) {
  61370. return;
  61371. }
  61372. this.activeSubSystems.forEach(function (subSystem) {
  61373. subSystem.stop(true);
  61374. });
  61375. this.activeSubSystems = new Array();
  61376. };
  61377. ParticleSystem.prototype._removeFromRoot = function () {
  61378. if (!this._rootParticleSystem) {
  61379. return;
  61380. }
  61381. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  61382. if (index !== -1) {
  61383. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  61384. }
  61385. this._rootParticleSystem = null;
  61386. };
  61387. // End of sub system methods
  61388. ParticleSystem.prototype._update = function (newParticles) {
  61389. var _this = this;
  61390. // Update current
  61391. this._alive = this._particles.length > 0;
  61392. if (this.emitter.position) {
  61393. var emitterMesh = this.emitter;
  61394. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  61395. }
  61396. else {
  61397. var emitterPosition = this.emitter;
  61398. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61399. }
  61400. this.updateFunction(this._particles);
  61401. // Add new ones
  61402. var particle;
  61403. var _loop_2 = function () {
  61404. if (this_1._particles.length === this_1._capacity) {
  61405. return "break";
  61406. }
  61407. particle = this_1._createParticle();
  61408. this_1._particles.push(particle);
  61409. // Emitter
  61410. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  61411. if (this_1.startPositionFunction) {
  61412. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61413. }
  61414. else {
  61415. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61416. }
  61417. if (this_1.startDirectionFunction) {
  61418. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61419. }
  61420. else {
  61421. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61422. }
  61423. if (emitPower === 0) {
  61424. if (!particle._initialDirection) {
  61425. particle._initialDirection = particle.direction.clone();
  61426. }
  61427. else {
  61428. particle._initialDirection.copyFrom(particle.direction);
  61429. }
  61430. }
  61431. else {
  61432. particle._initialDirection = null;
  61433. }
  61434. particle.direction.scaleInPlace(emitPower);
  61435. // Life time
  61436. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  61437. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  61438. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  61439. var factorGradient1 = currentGradient;
  61440. var factorGradient2 = nextGradient;
  61441. var lifeTime1 = factorGradient1.getFactor();
  61442. var lifeTime2 = factorGradient2.getFactor();
  61443. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  61444. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  61445. });
  61446. }
  61447. else {
  61448. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  61449. }
  61450. // Size
  61451. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  61452. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  61453. }
  61454. else {
  61455. particle._currentSizeGradient = this_1._sizeGradients[0];
  61456. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  61457. particle.size = particle._currentSize1;
  61458. if (this_1._sizeGradients.length > 1) {
  61459. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  61460. }
  61461. else {
  61462. particle._currentSize2 = particle._currentSize1;
  61463. }
  61464. }
  61465. // Size and scale
  61466. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  61467. // Adjust scale by start size
  61468. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  61469. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  61470. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  61471. if (currentGradient !== _this._currentStartSizeGradient) {
  61472. _this._currentStartSize1 = _this._currentStartSize2;
  61473. _this._currentStartSize2 = nextGradient.getFactor();
  61474. _this._currentStartSizeGradient = currentGradient;
  61475. }
  61476. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  61477. particle.scale.scaleInPlace(value);
  61478. });
  61479. }
  61480. // Angle
  61481. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  61482. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  61483. }
  61484. else {
  61485. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  61486. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  61487. particle._currentAngularSpeed1 = particle.angularSpeed;
  61488. if (this_1._angularSpeedGradients.length > 1) {
  61489. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  61490. }
  61491. else {
  61492. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  61493. }
  61494. }
  61495. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  61496. // Velocity
  61497. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  61498. particle._currentVelocityGradient = this_1._velocityGradients[0];
  61499. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  61500. if (this_1._velocityGradients.length > 1) {
  61501. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  61502. }
  61503. else {
  61504. particle._currentVelocity2 = particle._currentVelocity1;
  61505. }
  61506. }
  61507. // Limit velocity
  61508. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  61509. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  61510. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  61511. if (this_1._limitVelocityGradients.length > 1) {
  61512. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  61513. }
  61514. else {
  61515. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  61516. }
  61517. }
  61518. // Drag
  61519. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  61520. particle._currentDragGradient = this_1._dragGradients[0];
  61521. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  61522. if (this_1._dragGradients.length > 1) {
  61523. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  61524. }
  61525. else {
  61526. particle._currentDrag2 = particle._currentDrag1;
  61527. }
  61528. }
  61529. // Color
  61530. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  61531. step = BABYLON.Scalar.RandomRange(0, 1.0);
  61532. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  61533. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  61534. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  61535. }
  61536. else {
  61537. particle._currentColorGradient = this_1._colorGradients[0];
  61538. particle._currentColorGradient.getColorToRef(particle.color);
  61539. particle._currentColor1.copyFrom(particle.color);
  61540. if (this_1._colorGradients.length > 1) {
  61541. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  61542. }
  61543. else {
  61544. particle._currentColor2.copyFrom(particle.color);
  61545. }
  61546. }
  61547. // Sheet
  61548. if (this_1._isAnimationSheetEnabled) {
  61549. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  61550. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  61551. }
  61552. // Inherited Velocity
  61553. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  61554. // Ramp
  61555. if (this_1._useRampGradients) {
  61556. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  61557. }
  61558. // Noise texture coordinates
  61559. if (this_1.noiseTexture) {
  61560. if (particle._randomNoiseCoordinates1) {
  61561. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  61562. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  61563. }
  61564. else {
  61565. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61566. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61567. }
  61568. }
  61569. // Update the position of the attached sub-emitters to match their attached particle
  61570. particle._inheritParticleInfoToSubEmitters();
  61571. };
  61572. var this_1 = this, step;
  61573. for (var index = 0; index < newParticles; index++) {
  61574. var state_1 = _loop_2();
  61575. if (state_1 === "break")
  61576. break;
  61577. }
  61578. };
  61579. /** @hidden */
  61580. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  61581. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61582. if (isBillboardBased === void 0) { isBillboardBased = false; }
  61583. if (useRampGradients === void 0) { useRampGradients = false; }
  61584. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  61585. if (isAnimationSheetEnabled) {
  61586. attributeNamesOrOptions.push("cellIndex");
  61587. }
  61588. if (!isBillboardBased) {
  61589. attributeNamesOrOptions.push("direction");
  61590. }
  61591. if (useRampGradients) {
  61592. attributeNamesOrOptions.push("remapData");
  61593. }
  61594. return attributeNamesOrOptions;
  61595. };
  61596. /** @hidden */
  61597. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  61598. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61599. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  61600. if (isAnimationSheetEnabled) {
  61601. effectCreationOption.push("particlesInfos");
  61602. }
  61603. return effectCreationOption;
  61604. };
  61605. /** @hidden */
  61606. ParticleSystem.prototype._getEffect = function (blendMode) {
  61607. if (this._customEffect) {
  61608. return this._customEffect;
  61609. }
  61610. var defines = [];
  61611. if (this._scene.clipPlane) {
  61612. defines.push("#define CLIPPLANE");
  61613. }
  61614. if (this._scene.clipPlane2) {
  61615. defines.push("#define CLIPPLANE2");
  61616. }
  61617. if (this._scene.clipPlane3) {
  61618. defines.push("#define CLIPPLANE3");
  61619. }
  61620. if (this._scene.clipPlane4) {
  61621. defines.push("#define CLIPPLANE4");
  61622. }
  61623. if (this._isAnimationSheetEnabled) {
  61624. defines.push("#define ANIMATESHEET");
  61625. }
  61626. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  61627. defines.push("#define BLENDMULTIPLYMODE");
  61628. }
  61629. if (this._useRampGradients) {
  61630. defines.push("#define RAMPGRADIENT");
  61631. }
  61632. if (this._isBillboardBased) {
  61633. defines.push("#define BILLBOARD");
  61634. switch (this.billboardMode) {
  61635. case ParticleSystem.BILLBOARDMODE_Y:
  61636. defines.push("#define BILLBOARDY");
  61637. break;
  61638. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  61639. defines.push("#define BILLBOARDSTRETCHED");
  61640. break;
  61641. case ParticleSystem.BILLBOARDMODE_ALL:
  61642. default:
  61643. break;
  61644. }
  61645. }
  61646. if (this._imageProcessingConfiguration) {
  61647. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61648. defines.push(this._imageProcessingConfigurationDefines.toString());
  61649. }
  61650. // Effect
  61651. var join = defines.join("\n");
  61652. if (this._cachedDefines !== join) {
  61653. this._cachedDefines = join;
  61654. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  61655. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  61656. var samplers = ["diffuseSampler", "rampSampler"];
  61657. if (BABYLON.ImageProcessingConfiguration) {
  61658. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  61659. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61660. }
  61661. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  61662. }
  61663. return this._effect;
  61664. };
  61665. /**
  61666. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61667. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  61668. */
  61669. ParticleSystem.prototype.animate = function (preWarmOnly) {
  61670. var _this = this;
  61671. if (preWarmOnly === void 0) { preWarmOnly = false; }
  61672. if (!this._started) {
  61673. return;
  61674. }
  61675. if (!preWarmOnly) {
  61676. // Check
  61677. if (!this.isReady()) {
  61678. return;
  61679. }
  61680. if (this._currentRenderId === this._scene.getFrameId()) {
  61681. return;
  61682. }
  61683. this._currentRenderId = this._scene.getFrameId();
  61684. }
  61685. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61686. // Determine the number of particles we need to create
  61687. var newParticles;
  61688. if (this.manualEmitCount > -1) {
  61689. newParticles = this.manualEmitCount;
  61690. this._newPartsExcess = 0;
  61691. this.manualEmitCount = 0;
  61692. }
  61693. else {
  61694. var rate_1 = this.emitRate;
  61695. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  61696. var ratio = this._actualFrame / this.targetStopDuration;
  61697. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  61698. if (currentGradient !== _this._currentEmitRateGradient) {
  61699. _this._currentEmitRate1 = _this._currentEmitRate2;
  61700. _this._currentEmitRate2 = nextGradient.getFactor();
  61701. _this._currentEmitRateGradient = currentGradient;
  61702. }
  61703. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  61704. });
  61705. }
  61706. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  61707. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  61708. }
  61709. if (this._newPartsExcess > 1.0) {
  61710. newParticles += this._newPartsExcess >> 0;
  61711. this._newPartsExcess -= this._newPartsExcess >> 0;
  61712. }
  61713. this._alive = false;
  61714. if (!this._stopped) {
  61715. this._actualFrame += this._scaledUpdateSpeed;
  61716. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61717. this.stop();
  61718. }
  61719. }
  61720. else {
  61721. newParticles = 0;
  61722. }
  61723. this._update(newParticles);
  61724. // Stopped?
  61725. if (this._stopped) {
  61726. if (!this._alive) {
  61727. this._started = false;
  61728. if (this.onAnimationEnd) {
  61729. this.onAnimationEnd();
  61730. }
  61731. if (this.disposeOnStop) {
  61732. this._scene._toBeDisposed.push(this);
  61733. }
  61734. }
  61735. }
  61736. if (!preWarmOnly) {
  61737. // Update VBO
  61738. var offset = 0;
  61739. for (var index = 0; index < this._particles.length; index++) {
  61740. var particle = this._particles[index];
  61741. this._appendParticleVertices(offset, particle);
  61742. offset += this._useInstancing ? 1 : 4;
  61743. }
  61744. if (this._vertexBuffer) {
  61745. this._vertexBuffer.update(this._vertexData);
  61746. }
  61747. }
  61748. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  61749. this.stop();
  61750. }
  61751. };
  61752. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  61753. this._appendParticleVertex(offset++, particle, 0, 0);
  61754. if (!this._useInstancing) {
  61755. this._appendParticleVertex(offset++, particle, 1, 0);
  61756. this._appendParticleVertex(offset++, particle, 1, 1);
  61757. this._appendParticleVertex(offset++, particle, 0, 1);
  61758. }
  61759. };
  61760. /**
  61761. * Rebuilds the particle system.
  61762. */
  61763. ParticleSystem.prototype.rebuild = function () {
  61764. this._createIndexBuffer();
  61765. if (this._vertexBuffer) {
  61766. this._vertexBuffer._rebuild();
  61767. }
  61768. };
  61769. /**
  61770. * Is this system ready to be used/rendered
  61771. * @return true if the system is ready
  61772. */
  61773. ParticleSystem.prototype.isReady = function () {
  61774. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61775. return false;
  61776. }
  61777. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61778. if (!this._getEffect(this.blendMode).isReady()) {
  61779. return false;
  61780. }
  61781. }
  61782. else {
  61783. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  61784. return false;
  61785. }
  61786. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  61787. return false;
  61788. }
  61789. }
  61790. return true;
  61791. };
  61792. ParticleSystem.prototype._render = function (blendMode) {
  61793. var effect = this._getEffect(blendMode);
  61794. var engine = this._scene.getEngine();
  61795. // Render
  61796. engine.enableEffect(effect);
  61797. var viewMatrix = this._scene.getViewMatrix();
  61798. effect.setTexture("diffuseSampler", this.particleTexture);
  61799. effect.setMatrix("view", viewMatrix);
  61800. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  61801. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61802. var baseSize = this.particleTexture.getBaseSize();
  61803. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61804. }
  61805. effect.setVector2("translationPivot", this.translationPivot);
  61806. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  61807. if (this._isBillboardBased) {
  61808. var camera = this._scene.activeCamera;
  61809. effect.setVector3("eyePosition", camera.globalPosition);
  61810. }
  61811. if (this._rampGradientsTexture) {
  61812. effect.setTexture("rampSampler", this._rampGradientsTexture);
  61813. }
  61814. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61815. var invView = viewMatrix.clone();
  61816. invView.invert();
  61817. effect.setMatrix("invView", invView);
  61818. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  61819. }
  61820. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  61821. // image processing
  61822. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61823. this._imageProcessingConfiguration.bind(effect);
  61824. }
  61825. // Draw order
  61826. switch (blendMode) {
  61827. case ParticleSystem.BLENDMODE_ADD:
  61828. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61829. break;
  61830. case ParticleSystem.BLENDMODE_ONEONE:
  61831. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61832. break;
  61833. case ParticleSystem.BLENDMODE_STANDARD:
  61834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61835. break;
  61836. case ParticleSystem.BLENDMODE_MULTIPLY:
  61837. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61838. break;
  61839. }
  61840. if (this._useInstancing) {
  61841. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  61842. }
  61843. else {
  61844. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  61845. }
  61846. return this._particles.length;
  61847. };
  61848. /**
  61849. * Renders the particle system in its current state.
  61850. * @returns the current number of particles
  61851. */
  61852. ParticleSystem.prototype.render = function () {
  61853. // Check
  61854. if (!this.isReady() || !this._particles.length) {
  61855. return 0;
  61856. }
  61857. var engine = this._scene.getEngine();
  61858. engine.setState(false);
  61859. if (this.forceDepthWrite) {
  61860. engine.setDepthWrite(true);
  61861. }
  61862. var outparticles = 0;
  61863. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61864. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  61865. }
  61866. outparticles = this._render(this.blendMode);
  61867. engine.unbindInstanceAttributes();
  61868. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61869. return outparticles;
  61870. };
  61871. /**
  61872. * Disposes the particle system and free the associated resources
  61873. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61874. */
  61875. ParticleSystem.prototype.dispose = function (disposeTexture) {
  61876. if (disposeTexture === void 0) { disposeTexture = true; }
  61877. if (this._vertexBuffer) {
  61878. this._vertexBuffer.dispose();
  61879. this._vertexBuffer = null;
  61880. }
  61881. if (this._spriteBuffer) {
  61882. this._spriteBuffer.dispose();
  61883. this._spriteBuffer = null;
  61884. }
  61885. if (this._indexBuffer) {
  61886. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61887. this._indexBuffer = null;
  61888. }
  61889. if (disposeTexture && this.particleTexture) {
  61890. this.particleTexture.dispose();
  61891. this.particleTexture = null;
  61892. }
  61893. if (disposeTexture && this.noiseTexture) {
  61894. this.noiseTexture.dispose();
  61895. this.noiseTexture = null;
  61896. }
  61897. if (this._rampGradientsTexture) {
  61898. this._rampGradientsTexture.dispose();
  61899. this._rampGradientsTexture = null;
  61900. }
  61901. this._removeFromRoot();
  61902. if (this._subEmitters && this._subEmitters.length) {
  61903. for (var index = 0; index < this._subEmitters.length; index++) {
  61904. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  61905. var subEmitter = _a[_i];
  61906. subEmitter.dispose();
  61907. }
  61908. }
  61909. this._subEmitters = [];
  61910. this.subEmitters = [];
  61911. }
  61912. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  61913. this.emitter.dispose(true);
  61914. }
  61915. // Remove from scene
  61916. var index = this._scene.particleSystems.indexOf(this);
  61917. if (index > -1) {
  61918. this._scene.particleSystems.splice(index, 1);
  61919. }
  61920. this._scene._activeParticleSystems.dispose();
  61921. // Callback
  61922. this.onDisposeObservable.notifyObservers(this);
  61923. this.onDisposeObservable.clear();
  61924. this.reset();
  61925. };
  61926. // Clone
  61927. /**
  61928. * Clones the particle system.
  61929. * @param name The name of the cloned object
  61930. * @param newEmitter The new emitter to use
  61931. * @returns the cloned particle system
  61932. */
  61933. ParticleSystem.prototype.clone = function (name, newEmitter) {
  61934. var custom = null;
  61935. var program = null;
  61936. if (this.customShader != null) {
  61937. program = this.customShader;
  61938. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61939. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61940. }
  61941. else if (this._customEffect) {
  61942. custom = this._customEffect;
  61943. }
  61944. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  61945. result.customShader = program;
  61946. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  61947. if (newEmitter === undefined) {
  61948. newEmitter = this.emitter;
  61949. }
  61950. result.noiseTexture = this.noiseTexture;
  61951. result.emitter = newEmitter;
  61952. if (this.particleTexture) {
  61953. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61954. }
  61955. // Clone gradients
  61956. if (this._colorGradients) {
  61957. this._colorGradients.forEach(function (v) {
  61958. result.addColorGradient(v.gradient, v.color1, v.color2);
  61959. });
  61960. }
  61961. if (this._dragGradients) {
  61962. this._dragGradients.forEach(function (v) {
  61963. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  61964. });
  61965. }
  61966. if (this._angularSpeedGradients) {
  61967. this._angularSpeedGradients.forEach(function (v) {
  61968. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  61969. });
  61970. }
  61971. if (this._emitRateGradients) {
  61972. this._emitRateGradients.forEach(function (v) {
  61973. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  61974. });
  61975. }
  61976. if (this._lifeTimeGradients) {
  61977. this._lifeTimeGradients.forEach(function (v) {
  61978. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  61979. });
  61980. }
  61981. if (this._limitVelocityGradients) {
  61982. this._limitVelocityGradients.forEach(function (v) {
  61983. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  61984. });
  61985. }
  61986. if (this._sizeGradients) {
  61987. this._sizeGradients.forEach(function (v) {
  61988. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  61989. });
  61990. }
  61991. if (this._startSizeGradients) {
  61992. this._startSizeGradients.forEach(function (v) {
  61993. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  61994. });
  61995. }
  61996. if (this._velocityGradients) {
  61997. this._velocityGradients.forEach(function (v) {
  61998. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  61999. });
  62000. }
  62001. if (this._rampGradients) {
  62002. this._rampGradients.forEach(function (v) {
  62003. result.addRampGradient(v.gradient, v.color);
  62004. });
  62005. }
  62006. if (this._colorRemapGradients) {
  62007. this._colorRemapGradients.forEach(function (v) {
  62008. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  62009. });
  62010. }
  62011. if (this._alphaRemapGradients) {
  62012. this._alphaRemapGradients.forEach(function (v) {
  62013. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  62014. });
  62015. }
  62016. if (!this.preventAutoStart) {
  62017. result.start();
  62018. }
  62019. return result;
  62020. };
  62021. /**
  62022. * Serializes the particle system to a JSON object.
  62023. * @returns the JSON object
  62024. */
  62025. ParticleSystem.prototype.serialize = function () {
  62026. var serializationObject = {};
  62027. ParticleSystem._Serialize(serializationObject, this);
  62028. serializationObject.textureMask = this.textureMask.asArray();
  62029. serializationObject.customShader = this.customShader;
  62030. serializationObject.preventAutoStart = this.preventAutoStart;
  62031. // SubEmitters
  62032. if (this.subEmitters) {
  62033. serializationObject.subEmitters = [];
  62034. if (!this._subEmitters) {
  62035. this._prepareSubEmitterInternalArray();
  62036. }
  62037. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  62038. var subs = _a[_i];
  62039. var cell = [];
  62040. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  62041. var sub = subs_1[_b];
  62042. cell.push(sub.serialize());
  62043. }
  62044. serializationObject.subEmitters.push(cell);
  62045. }
  62046. }
  62047. return serializationObject;
  62048. };
  62049. /** @hidden */
  62050. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  62051. serializationObject.name = particleSystem.name;
  62052. serializationObject.id = particleSystem.id;
  62053. serializationObject.capacity = particleSystem.getCapacity();
  62054. // Emitter
  62055. if (particleSystem.emitter.position) {
  62056. var emitterMesh = particleSystem.emitter;
  62057. serializationObject.emitterId = emitterMesh.id;
  62058. }
  62059. else {
  62060. var emitterPosition = particleSystem.emitter;
  62061. serializationObject.emitter = emitterPosition.asArray();
  62062. }
  62063. // Emitter
  62064. if (particleSystem.particleEmitterType) {
  62065. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62066. }
  62067. if (particleSystem.particleTexture) {
  62068. serializationObject.textureName = particleSystem.particleTexture.name;
  62069. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62070. }
  62071. // Animations
  62072. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62073. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62074. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62075. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62076. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62077. // Particle system
  62078. serializationObject.startDelay = particleSystem.startDelay;
  62079. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62080. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62081. serializationObject.billboardMode = particleSystem.billboardMode;
  62082. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62083. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62084. serializationObject.minSize = particleSystem.minSize;
  62085. serializationObject.maxSize = particleSystem.maxSize;
  62086. serializationObject.minScaleX = particleSystem.minScaleX;
  62087. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62088. serializationObject.minScaleY = particleSystem.minScaleY;
  62089. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62090. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62091. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62092. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62093. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62094. serializationObject.emitRate = particleSystem.emitRate;
  62095. serializationObject.gravity = particleSystem.gravity.asArray();
  62096. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62097. serializationObject.color1 = particleSystem.color1.asArray();
  62098. serializationObject.color2 = particleSystem.color2.asArray();
  62099. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62100. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62101. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62102. serializationObject.blendMode = particleSystem.blendMode;
  62103. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62104. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62105. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62106. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62107. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62108. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62109. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62110. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62111. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62112. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62113. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62114. var colorGradients = particleSystem.getColorGradients();
  62115. if (colorGradients) {
  62116. serializationObject.colorGradients = [];
  62117. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62118. var colorGradient = colorGradients_1[_i];
  62119. var serializedGradient = {
  62120. gradient: colorGradient.gradient,
  62121. color1: colorGradient.color1.asArray()
  62122. };
  62123. if (colorGradient.color2) {
  62124. serializedGradient.color2 = colorGradient.color2.asArray();
  62125. }
  62126. serializationObject.colorGradients.push(serializedGradient);
  62127. }
  62128. }
  62129. var rampGradients = particleSystem.getRampGradients();
  62130. if (rampGradients) {
  62131. serializationObject.rampGradients = [];
  62132. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62133. var rampGradient = rampGradients_1[_a];
  62134. var serializedGradient = {
  62135. gradient: rampGradient.gradient,
  62136. color: rampGradient.color.asArray()
  62137. };
  62138. serializationObject.rampGradients.push(serializedGradient);
  62139. }
  62140. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62141. }
  62142. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62143. if (colorRemapGradients) {
  62144. serializationObject.colorRemapGradients = [];
  62145. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62146. var colorRemapGradient = colorRemapGradients_1[_b];
  62147. var serializedGradient = {
  62148. gradient: colorRemapGradient.gradient,
  62149. factor1: colorRemapGradient.factor1
  62150. };
  62151. if (colorRemapGradient.factor2 !== undefined) {
  62152. serializedGradient.factor2 = colorRemapGradient.factor2;
  62153. }
  62154. serializationObject.colorRemapGradients.push(serializedGradient);
  62155. }
  62156. }
  62157. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62158. if (alphaRemapGradients) {
  62159. serializationObject.alphaRemapGradients = [];
  62160. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62161. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62162. var serializedGradient = {
  62163. gradient: alphaRemapGradient.gradient,
  62164. factor1: alphaRemapGradient.factor1
  62165. };
  62166. if (alphaRemapGradient.factor2 !== undefined) {
  62167. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62168. }
  62169. serializationObject.alphaRemapGradients.push(serializedGradient);
  62170. }
  62171. }
  62172. var sizeGradients = particleSystem.getSizeGradients();
  62173. if (sizeGradients) {
  62174. serializationObject.sizeGradients = [];
  62175. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62176. var sizeGradient = sizeGradients_1[_d];
  62177. var serializedGradient = {
  62178. gradient: sizeGradient.gradient,
  62179. factor1: sizeGradient.factor1
  62180. };
  62181. if (sizeGradient.factor2 !== undefined) {
  62182. serializedGradient.factor2 = sizeGradient.factor2;
  62183. }
  62184. serializationObject.sizeGradients.push(serializedGradient);
  62185. }
  62186. }
  62187. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  62188. if (angularSpeedGradients) {
  62189. serializationObject.angularSpeedGradients = [];
  62190. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  62191. var angularSpeedGradient = angularSpeedGradients_1[_e];
  62192. var serializedGradient = {
  62193. gradient: angularSpeedGradient.gradient,
  62194. factor1: angularSpeedGradient.factor1
  62195. };
  62196. if (angularSpeedGradient.factor2 !== undefined) {
  62197. serializedGradient.factor2 = angularSpeedGradient.factor2;
  62198. }
  62199. serializationObject.angularSpeedGradients.push(serializedGradient);
  62200. }
  62201. }
  62202. var velocityGradients = particleSystem.getVelocityGradients();
  62203. if (velocityGradients) {
  62204. serializationObject.velocityGradients = [];
  62205. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  62206. var velocityGradient = velocityGradients_1[_f];
  62207. var serializedGradient = {
  62208. gradient: velocityGradient.gradient,
  62209. factor1: velocityGradient.factor1
  62210. };
  62211. if (velocityGradient.factor2 !== undefined) {
  62212. serializedGradient.factor2 = velocityGradient.factor2;
  62213. }
  62214. serializationObject.velocityGradients.push(serializedGradient);
  62215. }
  62216. }
  62217. var dragGradients = particleSystem.getDragGradients();
  62218. if (dragGradients) {
  62219. serializationObject.dragyGradients = [];
  62220. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  62221. var dragGradient = dragGradients_1[_g];
  62222. var serializedGradient = {
  62223. gradient: dragGradient.gradient,
  62224. factor1: dragGradient.factor1
  62225. };
  62226. if (dragGradient.factor2 !== undefined) {
  62227. serializedGradient.factor2 = dragGradient.factor2;
  62228. }
  62229. serializationObject.dragGradients.push(serializedGradient);
  62230. }
  62231. }
  62232. var emitRateGradients = particleSystem.getEmitRateGradients();
  62233. if (emitRateGradients) {
  62234. serializationObject.emitRateGradients = [];
  62235. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  62236. var emitRateGradient = emitRateGradients_1[_h];
  62237. var serializedGradient = {
  62238. gradient: emitRateGradient.gradient,
  62239. factor1: emitRateGradient.factor1
  62240. };
  62241. if (emitRateGradient.factor2 !== undefined) {
  62242. serializedGradient.factor2 = emitRateGradient.factor2;
  62243. }
  62244. serializationObject.emitRateGradients.push(serializedGradient);
  62245. }
  62246. }
  62247. var startSizeGradients = particleSystem.getStartSizeGradients();
  62248. if (startSizeGradients) {
  62249. serializationObject.startSizeGradients = [];
  62250. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  62251. var startSizeGradient = startSizeGradients_1[_j];
  62252. var serializedGradient = {
  62253. gradient: startSizeGradient.gradient,
  62254. factor1: startSizeGradient.factor1
  62255. };
  62256. if (startSizeGradient.factor2 !== undefined) {
  62257. serializedGradient.factor2 = startSizeGradient.factor2;
  62258. }
  62259. serializationObject.startSizeGradients.push(serializedGradient);
  62260. }
  62261. }
  62262. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  62263. if (lifeTimeGradients) {
  62264. serializationObject.lifeTimeGradients = [];
  62265. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  62266. var lifeTimeGradient = lifeTimeGradients_1[_k];
  62267. var serializedGradient = {
  62268. gradient: lifeTimeGradient.gradient,
  62269. factor1: lifeTimeGradient.factor1
  62270. };
  62271. if (lifeTimeGradient.factor2 !== undefined) {
  62272. serializedGradient.factor2 = lifeTimeGradient.factor2;
  62273. }
  62274. serializationObject.lifeTimeGradients.push(serializedGradient);
  62275. }
  62276. }
  62277. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  62278. if (limitVelocityGradients) {
  62279. serializationObject.limitVelocityGradients = [];
  62280. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  62281. var limitVelocityGradient = limitVelocityGradients_1[_l];
  62282. var serializedGradient = {
  62283. gradient: limitVelocityGradient.gradient,
  62284. factor1: limitVelocityGradient.factor1
  62285. };
  62286. if (limitVelocityGradient.factor2 !== undefined) {
  62287. serializedGradient.factor2 = limitVelocityGradient.factor2;
  62288. }
  62289. serializationObject.limitVelocityGradients.push(serializedGradient);
  62290. }
  62291. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  62292. }
  62293. if (particleSystem.noiseTexture) {
  62294. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  62295. }
  62296. };
  62297. /** @hidden */
  62298. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  62299. // Texture
  62300. if (parsedParticleSystem.textureName) {
  62301. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  62302. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  62303. }
  62304. // Emitter
  62305. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  62306. particleSystem.emitter = BABYLON.Vector3.Zero();
  62307. }
  62308. else if (parsedParticleSystem.emitterId) {
  62309. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  62310. }
  62311. else {
  62312. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  62313. }
  62314. // Misc.
  62315. if (parsedParticleSystem.renderingGroupId !== undefined) {
  62316. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  62317. }
  62318. if (parsedParticleSystem.isBillboardBased !== undefined) {
  62319. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  62320. }
  62321. if (parsedParticleSystem.billboardMode !== undefined) {
  62322. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  62323. }
  62324. // Animations
  62325. if (parsedParticleSystem.animations) {
  62326. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  62327. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  62328. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62329. }
  62330. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  62331. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  62332. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  62333. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  62334. }
  62335. if (parsedParticleSystem.autoAnimate) {
  62336. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  62337. }
  62338. // Particle system
  62339. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  62340. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  62341. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  62342. particleSystem.minSize = parsedParticleSystem.minSize;
  62343. particleSystem.maxSize = parsedParticleSystem.maxSize;
  62344. if (parsedParticleSystem.minScaleX) {
  62345. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  62346. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  62347. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  62348. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  62349. }
  62350. if (parsedParticleSystem.preWarmCycles !== undefined) {
  62351. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  62352. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  62353. }
  62354. if (parsedParticleSystem.minInitialRotation !== undefined) {
  62355. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  62356. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  62357. }
  62358. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  62359. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  62360. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  62361. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  62362. particleSystem.emitRate = parsedParticleSystem.emitRate;
  62363. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  62364. if (parsedParticleSystem.noiseStrength) {
  62365. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  62366. }
  62367. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  62368. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  62369. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  62370. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  62371. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  62372. particleSystem.blendMode = parsedParticleSystem.blendMode;
  62373. if (parsedParticleSystem.colorGradients) {
  62374. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  62375. var colorGradient = _a[_i];
  62376. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  62377. }
  62378. }
  62379. if (parsedParticleSystem.rampGradients) {
  62380. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  62381. var rampGradient = _c[_b];
  62382. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  62383. }
  62384. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  62385. }
  62386. if (parsedParticleSystem.colorRemapGradients) {
  62387. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  62388. var colorRemapGradient = _e[_d];
  62389. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  62390. }
  62391. }
  62392. if (parsedParticleSystem.alphaRemapGradients) {
  62393. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  62394. var alphaRemapGradient = _g[_f];
  62395. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  62396. }
  62397. }
  62398. if (parsedParticleSystem.sizeGradients) {
  62399. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  62400. var sizeGradient = _j[_h];
  62401. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62402. }
  62403. }
  62404. if (parsedParticleSystem.sizeGradients) {
  62405. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  62406. var sizeGradient = _l[_k];
  62407. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62408. }
  62409. }
  62410. if (parsedParticleSystem.angularSpeedGradients) {
  62411. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  62412. var angularSpeedGradient = _o[_m];
  62413. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  62414. }
  62415. }
  62416. if (parsedParticleSystem.velocityGradients) {
  62417. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  62418. var velocityGradient = _q[_p];
  62419. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  62420. }
  62421. }
  62422. if (parsedParticleSystem.dragGradients) {
  62423. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  62424. var dragGradient = _s[_r];
  62425. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  62426. }
  62427. }
  62428. if (parsedParticleSystem.emitRateGradients) {
  62429. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  62430. var emitRateGradient = _u[_t];
  62431. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  62432. }
  62433. }
  62434. if (parsedParticleSystem.startSizeGradients) {
  62435. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  62436. var startSizeGradient = _w[_v];
  62437. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  62438. }
  62439. }
  62440. if (parsedParticleSystem.lifeTimeGradients) {
  62441. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  62442. var lifeTimeGradient = _y[_x];
  62443. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  62444. }
  62445. }
  62446. if (parsedParticleSystem.limitVelocityGradients) {
  62447. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  62448. var limitVelocityGradient = _0[_z];
  62449. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  62450. }
  62451. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  62452. }
  62453. if (parsedParticleSystem.noiseTexture) {
  62454. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  62455. }
  62456. // Emitter
  62457. var emitterType;
  62458. if (parsedParticleSystem.particleEmitterType) {
  62459. switch (parsedParticleSystem.particleEmitterType.type) {
  62460. case "SphereParticleEmitter":
  62461. emitterType = new BABYLON.SphereParticleEmitter();
  62462. break;
  62463. case "SphereDirectedParticleEmitter":
  62464. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  62465. break;
  62466. case "ConeEmitter":
  62467. case "ConeParticleEmitter":
  62468. emitterType = new BABYLON.ConeParticleEmitter();
  62469. break;
  62470. case "CylinderParticleEmitter":
  62471. emitterType = new BABYLON.CylinderParticleEmitter();
  62472. break;
  62473. case "HemisphericParticleEmitter":
  62474. emitterType = new BABYLON.HemisphericParticleEmitter();
  62475. break;
  62476. case "BoxEmitter":
  62477. case "BoxParticleEmitter":
  62478. default:
  62479. emitterType = new BABYLON.BoxParticleEmitter();
  62480. break;
  62481. }
  62482. emitterType.parse(parsedParticleSystem.particleEmitterType);
  62483. }
  62484. else {
  62485. emitterType = new BABYLON.BoxParticleEmitter();
  62486. emitterType.parse(parsedParticleSystem);
  62487. }
  62488. particleSystem.particleEmitterType = emitterType;
  62489. // Animation sheet
  62490. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  62491. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  62492. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  62493. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  62494. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  62495. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  62496. };
  62497. /**
  62498. * Parses a JSON object to create a particle system.
  62499. * @param parsedParticleSystem The JSON object to parse
  62500. * @param scene The scene to create the particle system in
  62501. * @param rootUrl The root url to use to load external dependencies like texture
  62502. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  62503. * @returns the Parsed particle system
  62504. */
  62505. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  62506. if (doNotStart === void 0) { doNotStart = false; }
  62507. var name = parsedParticleSystem.name;
  62508. var custom = null;
  62509. var program = null;
  62510. if (parsedParticleSystem.customShader) {
  62511. program = parsedParticleSystem.customShader;
  62512. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62513. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62514. }
  62515. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  62516. particleSystem.customShader = program;
  62517. if (parsedParticleSystem.id) {
  62518. particleSystem.id = parsedParticleSystem.id;
  62519. }
  62520. // SubEmitters
  62521. if (parsedParticleSystem.subEmitters) {
  62522. particleSystem.subEmitters = [];
  62523. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  62524. var cell = _a[_i];
  62525. var cellArray = [];
  62526. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  62527. var sub = cell_1[_b];
  62528. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  62529. }
  62530. particleSystem.subEmitters.push(cellArray);
  62531. }
  62532. }
  62533. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62534. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  62535. // Auto start
  62536. if (parsedParticleSystem.preventAutoStart) {
  62537. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  62538. }
  62539. if (!doNotStart && !particleSystem.preventAutoStart) {
  62540. particleSystem.start();
  62541. }
  62542. return particleSystem;
  62543. };
  62544. /**
  62545. * Billboard mode will only apply to Y axis
  62546. */
  62547. ParticleSystem.BILLBOARDMODE_Y = 2;
  62548. /**
  62549. * Billboard mode will apply to all axes
  62550. */
  62551. ParticleSystem.BILLBOARDMODE_ALL = 7;
  62552. /**
  62553. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  62554. */
  62555. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  62556. return ParticleSystem;
  62557. }(BABYLON.BaseParticleSystem));
  62558. BABYLON.ParticleSystem = ParticleSystem;
  62559. })(BABYLON || (BABYLON = {}));
  62560. //# sourceMappingURL=babylon.particleSystem.js.map
  62561. var BABYLON;
  62562. (function (BABYLON) {
  62563. /**
  62564. * Particle emitter emitting particles from the inside of a box.
  62565. * It emits the particles randomly between 2 given directions.
  62566. */
  62567. var BoxParticleEmitter = /** @class */ (function () {
  62568. /**
  62569. * Creates a new instance BoxParticleEmitter
  62570. */
  62571. function BoxParticleEmitter() {
  62572. /**
  62573. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62574. */
  62575. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62576. /**
  62577. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62578. */
  62579. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62580. /**
  62581. * 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.
  62582. */
  62583. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  62584. /**
  62585. * 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.
  62586. */
  62587. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  62588. }
  62589. /**
  62590. * Called by the particle System when the direction is computed for the created particle.
  62591. * @param worldMatrix is the world matrix of the particle system
  62592. * @param directionToUpdate is the direction vector to update with the result
  62593. * @param particle is the particle we are computed the direction for
  62594. */
  62595. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62596. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62597. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62598. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62599. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62600. };
  62601. /**
  62602. * Called by the particle System when the position is computed for the created particle.
  62603. * @param worldMatrix is the world matrix of the particle system
  62604. * @param positionToUpdate is the position vector to update with the result
  62605. * @param particle is the particle we are computed the position for
  62606. */
  62607. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62608. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  62609. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  62610. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  62611. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62612. };
  62613. /**
  62614. * Clones the current emitter and returns a copy of it
  62615. * @returns the new emitter
  62616. */
  62617. BoxParticleEmitter.prototype.clone = function () {
  62618. var newOne = new BoxParticleEmitter();
  62619. BABYLON.Tools.DeepCopy(this, newOne);
  62620. return newOne;
  62621. };
  62622. /**
  62623. * Called by the GPUParticleSystem to setup the update shader
  62624. * @param effect defines the update shader
  62625. */
  62626. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  62627. effect.setVector3("direction1", this.direction1);
  62628. effect.setVector3("direction2", this.direction2);
  62629. effect.setVector3("minEmitBox", this.minEmitBox);
  62630. effect.setVector3("maxEmitBox", this.maxEmitBox);
  62631. };
  62632. /**
  62633. * Returns a string to use to update the GPU particles update shader
  62634. * @returns a string containng the defines string
  62635. */
  62636. BoxParticleEmitter.prototype.getEffectDefines = function () {
  62637. return "#define BOXEMITTER";
  62638. };
  62639. /**
  62640. * Returns the string "BoxParticleEmitter"
  62641. * @returns a string containing the class name
  62642. */
  62643. BoxParticleEmitter.prototype.getClassName = function () {
  62644. return "BoxParticleEmitter";
  62645. };
  62646. /**
  62647. * Serializes the particle system to a JSON object.
  62648. * @returns the JSON object
  62649. */
  62650. BoxParticleEmitter.prototype.serialize = function () {
  62651. var serializationObject = {};
  62652. serializationObject.type = this.getClassName();
  62653. serializationObject.direction1 = this.direction1.asArray();
  62654. serializationObject.direction2 = this.direction2.asArray();
  62655. serializationObject.minEmitBox = this.minEmitBox.asArray();
  62656. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  62657. return serializationObject;
  62658. };
  62659. /**
  62660. * Parse properties from a JSON object
  62661. * @param serializationObject defines the JSON object
  62662. */
  62663. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  62664. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62665. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62666. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  62667. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  62668. };
  62669. return BoxParticleEmitter;
  62670. }());
  62671. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  62672. })(BABYLON || (BABYLON = {}));
  62673. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  62674. var BABYLON;
  62675. (function (BABYLON) {
  62676. /**
  62677. * Particle emitter emitting particles from the inside of a cylinder.
  62678. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  62679. */
  62680. var CylinderParticleEmitter = /** @class */ (function () {
  62681. /**
  62682. * Creates a new instance CylinderParticleEmitter
  62683. * @param radius the radius of the emission cylinder (1 by default)
  62684. * @param height the height of the emission cylinder (1 by default)
  62685. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62686. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62687. */
  62688. function CylinderParticleEmitter(
  62689. /**
  62690. * The radius of the emission cylinder.
  62691. */
  62692. radius,
  62693. /**
  62694. * The height of the emission cylinder.
  62695. */
  62696. height,
  62697. /**
  62698. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62699. */
  62700. radiusRange,
  62701. /**
  62702. * How much to randomize the particle direction [0-1].
  62703. */
  62704. directionRandomizer) {
  62705. if (radius === void 0) { radius = 1; }
  62706. if (height === void 0) { height = 1; }
  62707. if (radiusRange === void 0) { radiusRange = 1; }
  62708. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62709. this.radius = radius;
  62710. this.height = height;
  62711. this.radiusRange = radiusRange;
  62712. this.directionRandomizer = directionRandomizer;
  62713. }
  62714. /**
  62715. * Called by the particle System when the direction is computed for the created particle.
  62716. * @param worldMatrix is the world matrix of the particle system
  62717. * @param directionToUpdate is the direction vector to update with the result
  62718. * @param particle is the particle we are computed the direction for
  62719. */
  62720. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62721. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62722. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  62723. var angle = Math.atan2(direction.x, direction.z);
  62724. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  62725. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  62726. direction.x = Math.sin(angle);
  62727. direction.z = Math.cos(angle);
  62728. direction.normalize();
  62729. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62730. };
  62731. /**
  62732. * Called by the particle System when the position is computed for the created particle.
  62733. * @param worldMatrix is the world matrix of the particle system
  62734. * @param positionToUpdate is the position vector to update with the result
  62735. * @param particle is the particle we are computed the position for
  62736. */
  62737. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62738. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  62739. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62740. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  62741. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  62742. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  62743. var xPos = positionRadius * Math.cos(angle);
  62744. var zPos = positionRadius * Math.sin(angle);
  62745. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  62746. };
  62747. /**
  62748. * Clones the current emitter and returns a copy of it
  62749. * @returns the new emitter
  62750. */
  62751. CylinderParticleEmitter.prototype.clone = function () {
  62752. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  62753. BABYLON.Tools.DeepCopy(this, newOne);
  62754. return newOne;
  62755. };
  62756. /**
  62757. * Called by the GPUParticleSystem to setup the update shader
  62758. * @param effect defines the update shader
  62759. */
  62760. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  62761. effect.setFloat("radius", this.radius);
  62762. effect.setFloat("height", this.height);
  62763. effect.setFloat("radiusRange", this.radiusRange);
  62764. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62765. };
  62766. /**
  62767. * Returns a string to use to update the GPU particles update shader
  62768. * @returns a string containng the defines string
  62769. */
  62770. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  62771. return "#define CYLINDEREMITTER";
  62772. };
  62773. /**
  62774. * Returns the string "CylinderParticleEmitter"
  62775. * @returns a string containing the class name
  62776. */
  62777. CylinderParticleEmitter.prototype.getClassName = function () {
  62778. return "CylinderParticleEmitter";
  62779. };
  62780. /**
  62781. * Serializes the particle system to a JSON object.
  62782. * @returns the JSON object
  62783. */
  62784. CylinderParticleEmitter.prototype.serialize = function () {
  62785. var serializationObject = {};
  62786. serializationObject.type = this.getClassName();
  62787. serializationObject.radius = this.radius;
  62788. serializationObject.height = this.height;
  62789. serializationObject.radiusRange = this.radiusRange;
  62790. serializationObject.directionRandomizer = this.directionRandomizer;
  62791. return serializationObject;
  62792. };
  62793. /**
  62794. * Parse properties from a JSON object
  62795. * @param serializationObject defines the JSON object
  62796. */
  62797. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  62798. this.radius = serializationObject.radius;
  62799. this.height = serializationObject.height;
  62800. this.radiusRange = serializationObject.radiusRange;
  62801. this.directionRandomizer = serializationObject.directionRandomizer;
  62802. };
  62803. return CylinderParticleEmitter;
  62804. }());
  62805. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  62806. /**
  62807. * Particle emitter emitting particles from the inside of a cylinder.
  62808. * It emits the particles randomly between two vectors.
  62809. */
  62810. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  62811. __extends(CylinderDirectedParticleEmitter, _super);
  62812. /**
  62813. * Creates a new instance CylinderDirectedParticleEmitter
  62814. * @param radius the radius of the emission cylinder (1 by default)
  62815. * @param height the height of the emission cylinder (1 by default)
  62816. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62817. * @param direction1 the min limit of the emission direction (up vector by default)
  62818. * @param direction2 the max limit of the emission direction (up vector by default)
  62819. */
  62820. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  62821. /**
  62822. * The min limit of the emission direction.
  62823. */
  62824. direction1,
  62825. /**
  62826. * The max limit of the emission direction.
  62827. */
  62828. direction2) {
  62829. if (radius === void 0) { radius = 1; }
  62830. if (height === void 0) { height = 1; }
  62831. if (radiusRange === void 0) { radiusRange = 1; }
  62832. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62833. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62834. var _this = _super.call(this, radius, height, radiusRange) || this;
  62835. _this.direction1 = direction1;
  62836. _this.direction2 = direction2;
  62837. return _this;
  62838. }
  62839. /**
  62840. * Called by the particle System when the direction is computed for the created particle.
  62841. * @param worldMatrix is the world matrix of the particle system
  62842. * @param directionToUpdate is the direction vector to update with the result
  62843. * @param particle is the particle we are computed the direction for
  62844. */
  62845. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62846. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62847. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62848. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62849. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62850. };
  62851. /**
  62852. * Clones the current emitter and returns a copy of it
  62853. * @returns the new emitter
  62854. */
  62855. CylinderDirectedParticleEmitter.prototype.clone = function () {
  62856. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  62857. BABYLON.Tools.DeepCopy(this, newOne);
  62858. return newOne;
  62859. };
  62860. /**
  62861. * Called by the GPUParticleSystem to setup the update shader
  62862. * @param effect defines the update shader
  62863. */
  62864. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62865. effect.setFloat("radius", this.radius);
  62866. effect.setFloat("height", this.height);
  62867. effect.setFloat("radiusRange", this.radiusRange);
  62868. effect.setVector3("direction1", this.direction1);
  62869. effect.setVector3("direction2", this.direction2);
  62870. };
  62871. /**
  62872. * Returns a string to use to update the GPU particles update shader
  62873. * @returns a string containng the defines string
  62874. */
  62875. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62876. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  62877. };
  62878. /**
  62879. * Returns the string "CylinderDirectedParticleEmitter"
  62880. * @returns a string containing the class name
  62881. */
  62882. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  62883. return "CylinderDirectedParticleEmitter";
  62884. };
  62885. /**
  62886. * Serializes the particle system to a JSON object.
  62887. * @returns the JSON object
  62888. */
  62889. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  62890. var serializationObject = _super.prototype.serialize.call(this);
  62891. serializationObject.direction1 = this.direction1.asArray();
  62892. serializationObject.direction2 = this.direction2.asArray();
  62893. return serializationObject;
  62894. };
  62895. /**
  62896. * Parse properties from a JSON object
  62897. * @param serializationObject defines the JSON object
  62898. */
  62899. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62900. _super.prototype.parse.call(this, serializationObject);
  62901. this.direction1.copyFrom(serializationObject.direction1);
  62902. this.direction2.copyFrom(serializationObject.direction2);
  62903. };
  62904. return CylinderDirectedParticleEmitter;
  62905. }(CylinderParticleEmitter));
  62906. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  62907. })(BABYLON || (BABYLON = {}));
  62908. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  62909. var BABYLON;
  62910. (function (BABYLON) {
  62911. /**
  62912. * Particle emitter emitting particles from the inside of a cone.
  62913. * It emits the particles alongside the cone volume from the base to the particle.
  62914. * The emission direction might be randomized.
  62915. */
  62916. var ConeParticleEmitter = /** @class */ (function () {
  62917. /**
  62918. * Creates a new instance ConeParticleEmitter
  62919. * @param radius the radius of the emission cone (1 by default)
  62920. * @param angles the cone base angle (PI by default)
  62921. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  62922. */
  62923. function ConeParticleEmitter(radius, angle,
  62924. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  62925. directionRandomizer) {
  62926. if (radius === void 0) { radius = 1; }
  62927. if (angle === void 0) { angle = Math.PI; }
  62928. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62929. this.directionRandomizer = directionRandomizer;
  62930. /**
  62931. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  62932. */
  62933. this.radiusRange = 1;
  62934. /**
  62935. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  62936. */
  62937. this.heightRange = 1;
  62938. /**
  62939. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  62940. */
  62941. this.emitFromSpawnPointOnly = false;
  62942. this.angle = angle;
  62943. this.radius = radius;
  62944. }
  62945. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  62946. /**
  62947. * Gets or sets the radius of the emission cone
  62948. */
  62949. get: function () {
  62950. return this._radius;
  62951. },
  62952. set: function (value) {
  62953. this._radius = value;
  62954. this._buildHeight();
  62955. },
  62956. enumerable: true,
  62957. configurable: true
  62958. });
  62959. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  62960. /**
  62961. * Gets or sets the angle of the emission cone
  62962. */
  62963. get: function () {
  62964. return this._angle;
  62965. },
  62966. set: function (value) {
  62967. this._angle = value;
  62968. this._buildHeight();
  62969. },
  62970. enumerable: true,
  62971. configurable: true
  62972. });
  62973. ConeParticleEmitter.prototype._buildHeight = function () {
  62974. if (this._angle !== 0) {
  62975. this._height = this._radius / Math.tan(this._angle / 2);
  62976. }
  62977. else {
  62978. this._height = 1;
  62979. }
  62980. };
  62981. /**
  62982. * Called by the particle System when the direction is computed for the created particle.
  62983. * @param worldMatrix is the world matrix of the particle system
  62984. * @param directionToUpdate is the direction vector to update with the result
  62985. * @param particle is the particle we are computed the direction for
  62986. */
  62987. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62988. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  62989. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  62990. }
  62991. else {
  62992. // measure the direction Vector from the emitter to the particle.
  62993. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62994. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62995. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62996. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62997. direction.x += randX;
  62998. direction.y += randY;
  62999. direction.z += randZ;
  63000. direction.normalize();
  63001. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63002. }
  63003. };
  63004. /**
  63005. * Called by the particle System when the position is computed for the created particle.
  63006. * @param worldMatrix is the world matrix of the particle system
  63007. * @param positionToUpdate is the position vector to update with the result
  63008. * @param particle is the particle we are computed the position for
  63009. */
  63010. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63011. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  63012. var h;
  63013. if (!this.emitFromSpawnPointOnly) {
  63014. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  63015. // Better distribution in a cone at normal angles.
  63016. h = 1 - h * h;
  63017. }
  63018. else {
  63019. h = 0.0001;
  63020. }
  63021. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  63022. radius = radius * h;
  63023. var randX = radius * Math.sin(s);
  63024. var randZ = radius * Math.cos(s);
  63025. var randY = h * this._height;
  63026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63027. };
  63028. /**
  63029. * Clones the current emitter and returns a copy of it
  63030. * @returns the new emitter
  63031. */
  63032. ConeParticleEmitter.prototype.clone = function () {
  63033. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  63034. BABYLON.Tools.DeepCopy(this, newOne);
  63035. return newOne;
  63036. };
  63037. /**
  63038. * Called by the GPUParticleSystem to setup the update shader
  63039. * @param effect defines the update shader
  63040. */
  63041. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  63042. effect.setFloat2("radius", this._radius, this.radiusRange);
  63043. effect.setFloat("coneAngle", this._angle);
  63044. effect.setFloat2("height", this._height, this.heightRange);
  63045. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63046. };
  63047. /**
  63048. * Returns a string to use to update the GPU particles update shader
  63049. * @returns a string containng the defines string
  63050. */
  63051. ConeParticleEmitter.prototype.getEffectDefines = function () {
  63052. var defines = "#define CONEEMITTER";
  63053. if (this.emitFromSpawnPointOnly) {
  63054. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63055. }
  63056. return defines;
  63057. };
  63058. /**
  63059. * Returns the string "ConeParticleEmitter"
  63060. * @returns a string containing the class name
  63061. */
  63062. ConeParticleEmitter.prototype.getClassName = function () {
  63063. return "ConeParticleEmitter";
  63064. };
  63065. /**
  63066. * Serializes the particle system to a JSON object.
  63067. * @returns the JSON object
  63068. */
  63069. ConeParticleEmitter.prototype.serialize = function () {
  63070. var serializationObject = {};
  63071. serializationObject.type = this.getClassName();
  63072. serializationObject.radius = this._radius;
  63073. serializationObject.angle = this._angle;
  63074. serializationObject.directionRandomizer = this.directionRandomizer;
  63075. return serializationObject;
  63076. };
  63077. /**
  63078. * Parse properties from a JSON object
  63079. * @param serializationObject defines the JSON object
  63080. */
  63081. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63082. this.radius = serializationObject.radius;
  63083. this.angle = serializationObject.angle;
  63084. this.directionRandomizer = serializationObject.directionRandomizer;
  63085. };
  63086. return ConeParticleEmitter;
  63087. }());
  63088. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63089. })(BABYLON || (BABYLON = {}));
  63090. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  63091. var BABYLON;
  63092. (function (BABYLON) {
  63093. /**
  63094. * Particle emitter emitting particles from the inside of a sphere.
  63095. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63096. */
  63097. var SphereParticleEmitter = /** @class */ (function () {
  63098. /**
  63099. * Creates a new instance SphereParticleEmitter
  63100. * @param radius the radius of the emission sphere (1 by default)
  63101. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63102. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63103. */
  63104. function SphereParticleEmitter(
  63105. /**
  63106. * The radius of the emission sphere.
  63107. */
  63108. radius,
  63109. /**
  63110. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63111. */
  63112. radiusRange,
  63113. /**
  63114. * How much to randomize the particle direction [0-1].
  63115. */
  63116. directionRandomizer) {
  63117. if (radius === void 0) { radius = 1; }
  63118. if (radiusRange === void 0) { radiusRange = 1; }
  63119. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63120. this.radius = radius;
  63121. this.radiusRange = radiusRange;
  63122. this.directionRandomizer = directionRandomizer;
  63123. }
  63124. /**
  63125. * Called by the particle System when the direction is computed for the created particle.
  63126. * @param worldMatrix is the world matrix of the particle system
  63127. * @param directionToUpdate is the direction vector to update with the result
  63128. * @param particle is the particle we are computed the direction for
  63129. */
  63130. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63131. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63132. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63133. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63134. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63135. direction.x += randX;
  63136. direction.y += randY;
  63137. direction.z += randZ;
  63138. direction.normalize();
  63139. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63140. };
  63141. /**
  63142. * Called by the particle System when the position is computed for the created particle.
  63143. * @param worldMatrix is the world matrix of the particle system
  63144. * @param positionToUpdate is the position vector to update with the result
  63145. * @param particle is the particle we are computed the position for
  63146. */
  63147. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63148. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63149. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63150. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63151. var theta = Math.acos(2 * v - 1);
  63152. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63153. var randY = randRadius * Math.cos(theta);
  63154. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63155. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63156. };
  63157. /**
  63158. * Clones the current emitter and returns a copy of it
  63159. * @returns the new emitter
  63160. */
  63161. SphereParticleEmitter.prototype.clone = function () {
  63162. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63163. BABYLON.Tools.DeepCopy(this, newOne);
  63164. return newOne;
  63165. };
  63166. /**
  63167. * Called by the GPUParticleSystem to setup the update shader
  63168. * @param effect defines the update shader
  63169. */
  63170. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63171. effect.setFloat("radius", this.radius);
  63172. effect.setFloat("radiusRange", this.radiusRange);
  63173. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63174. };
  63175. /**
  63176. * Returns a string to use to update the GPU particles update shader
  63177. * @returns a string containng the defines string
  63178. */
  63179. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63180. return "#define SPHEREEMITTER";
  63181. };
  63182. /**
  63183. * Returns the string "SphereParticleEmitter"
  63184. * @returns a string containing the class name
  63185. */
  63186. SphereParticleEmitter.prototype.getClassName = function () {
  63187. return "SphereParticleEmitter";
  63188. };
  63189. /**
  63190. * Serializes the particle system to a JSON object.
  63191. * @returns the JSON object
  63192. */
  63193. SphereParticleEmitter.prototype.serialize = function () {
  63194. var serializationObject = {};
  63195. serializationObject.type = this.getClassName();
  63196. serializationObject.radius = this.radius;
  63197. serializationObject.radiusRange = this.radiusRange;
  63198. serializationObject.directionRandomizer = this.directionRandomizer;
  63199. return serializationObject;
  63200. };
  63201. /**
  63202. * Parse properties from a JSON object
  63203. * @param serializationObject defines the JSON object
  63204. */
  63205. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  63206. this.radius = serializationObject.radius;
  63207. this.radiusRange = serializationObject.radiusRange;
  63208. this.directionRandomizer = serializationObject.directionRandomizer;
  63209. };
  63210. return SphereParticleEmitter;
  63211. }());
  63212. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  63213. /**
  63214. * Particle emitter emitting particles from the inside of a sphere.
  63215. * It emits the particles randomly between two vectors.
  63216. */
  63217. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  63218. __extends(SphereDirectedParticleEmitter, _super);
  63219. /**
  63220. * Creates a new instance SphereDirectedParticleEmitter
  63221. * @param radius the radius of the emission sphere (1 by default)
  63222. * @param direction1 the min limit of the emission direction (up vector by default)
  63223. * @param direction2 the max limit of the emission direction (up vector by default)
  63224. */
  63225. function SphereDirectedParticleEmitter(radius,
  63226. /**
  63227. * The min limit of the emission direction.
  63228. */
  63229. direction1,
  63230. /**
  63231. * The max limit of the emission direction.
  63232. */
  63233. direction2) {
  63234. if (radius === void 0) { radius = 1; }
  63235. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63236. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63237. var _this = _super.call(this, radius) || this;
  63238. _this.direction1 = direction1;
  63239. _this.direction2 = direction2;
  63240. return _this;
  63241. }
  63242. /**
  63243. * Called by the particle System when the direction is computed for the created particle.
  63244. * @param worldMatrix is the world matrix of the particle system
  63245. * @param directionToUpdate is the direction vector to update with the result
  63246. * @param particle is the particle we are computed the direction for
  63247. */
  63248. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63249. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63250. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63251. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63252. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63253. };
  63254. /**
  63255. * Clones the current emitter and returns a copy of it
  63256. * @returns the new emitter
  63257. */
  63258. SphereDirectedParticleEmitter.prototype.clone = function () {
  63259. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  63260. BABYLON.Tools.DeepCopy(this, newOne);
  63261. return newOne;
  63262. };
  63263. /**
  63264. * Called by the GPUParticleSystem to setup the update shader
  63265. * @param effect defines the update shader
  63266. */
  63267. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63268. effect.setFloat("radius", this.radius);
  63269. effect.setFloat("radiusRange", this.radiusRange);
  63270. effect.setVector3("direction1", this.direction1);
  63271. effect.setVector3("direction2", this.direction2);
  63272. };
  63273. /**
  63274. * Returns a string to use to update the GPU particles update shader
  63275. * @returns a string containng the defines string
  63276. */
  63277. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63278. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  63279. };
  63280. /**
  63281. * Returns the string "SphereDirectedParticleEmitter"
  63282. * @returns a string containing the class name
  63283. */
  63284. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  63285. return "SphereDirectedParticleEmitter";
  63286. };
  63287. /**
  63288. * Serializes the particle system to a JSON object.
  63289. * @returns the JSON object
  63290. */
  63291. SphereDirectedParticleEmitter.prototype.serialize = function () {
  63292. var serializationObject = _super.prototype.serialize.call(this);
  63293. serializationObject.direction1 = this.direction1.asArray();
  63294. serializationObject.direction2 = this.direction2.asArray();
  63295. return serializationObject;
  63296. };
  63297. /**
  63298. * Parse properties from a JSON object
  63299. * @param serializationObject defines the JSON object
  63300. */
  63301. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63302. _super.prototype.parse.call(this, serializationObject);
  63303. this.direction1.copyFrom(serializationObject.direction1);
  63304. this.direction2.copyFrom(serializationObject.direction2);
  63305. };
  63306. return SphereDirectedParticleEmitter;
  63307. }(SphereParticleEmitter));
  63308. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  63309. })(BABYLON || (BABYLON = {}));
  63310. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  63311. var BABYLON;
  63312. (function (BABYLON) {
  63313. /**
  63314. * Particle emitter emitting particles from the inside of a hemisphere.
  63315. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  63316. */
  63317. var HemisphericParticleEmitter = /** @class */ (function () {
  63318. /**
  63319. * Creates a new instance HemisphericParticleEmitter
  63320. * @param radius the radius of the emission hemisphere (1 by default)
  63321. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63322. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63323. */
  63324. function HemisphericParticleEmitter(
  63325. /**
  63326. * The radius of the emission hemisphere.
  63327. */
  63328. radius,
  63329. /**
  63330. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63331. */
  63332. radiusRange,
  63333. /**
  63334. * How much to randomize the particle direction [0-1].
  63335. */
  63336. directionRandomizer) {
  63337. if (radius === void 0) { radius = 1; }
  63338. if (radiusRange === void 0) { radiusRange = 1; }
  63339. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63340. this.radius = radius;
  63341. this.radiusRange = radiusRange;
  63342. this.directionRandomizer = directionRandomizer;
  63343. }
  63344. /**
  63345. * Called by the particle System when the direction is computed for the created particle.
  63346. * @param worldMatrix is the world matrix of the particle system
  63347. * @param directionToUpdate is the direction vector to update with the result
  63348. * @param particle is the particle we are computed the direction for
  63349. */
  63350. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63351. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63352. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63353. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63354. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63355. direction.x += randX;
  63356. direction.y += randY;
  63357. direction.z += randZ;
  63358. direction.normalize();
  63359. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63360. };
  63361. /**
  63362. * Called by the particle System when the position is computed for the created particle.
  63363. * @param worldMatrix is the world matrix of the particle system
  63364. * @param positionToUpdate is the position vector to update with the result
  63365. * @param particle is the particle we are computed the position for
  63366. */
  63367. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63368. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63369. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63370. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63371. var theta = Math.acos(2 * v - 1);
  63372. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63373. var randY = randRadius * Math.cos(theta);
  63374. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63375. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  63376. };
  63377. /**
  63378. * Clones the current emitter and returns a copy of it
  63379. * @returns the new emitter
  63380. */
  63381. HemisphericParticleEmitter.prototype.clone = function () {
  63382. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  63383. BABYLON.Tools.DeepCopy(this, newOne);
  63384. return newOne;
  63385. };
  63386. /**
  63387. * Called by the GPUParticleSystem to setup the update shader
  63388. * @param effect defines the update shader
  63389. */
  63390. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  63391. effect.setFloat("radius", this.radius);
  63392. effect.setFloat("radiusRange", this.radiusRange);
  63393. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63394. };
  63395. /**
  63396. * Returns a string to use to update the GPU particles update shader
  63397. * @returns a string containng the defines string
  63398. */
  63399. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  63400. return "#define HEMISPHERICEMITTER";
  63401. };
  63402. /**
  63403. * Returns the string "HemisphericParticleEmitter"
  63404. * @returns a string containing the class name
  63405. */
  63406. HemisphericParticleEmitter.prototype.getClassName = function () {
  63407. return "HemisphericParticleEmitter";
  63408. };
  63409. /**
  63410. * Serializes the particle system to a JSON object.
  63411. * @returns the JSON object
  63412. */
  63413. HemisphericParticleEmitter.prototype.serialize = function () {
  63414. var serializationObject = {};
  63415. serializationObject.type = this.getClassName();
  63416. serializationObject.radius = this.radius;
  63417. serializationObject.radiusRange = this.radiusRange;
  63418. serializationObject.directionRandomizer = this.directionRandomizer;
  63419. return serializationObject;
  63420. };
  63421. /**
  63422. * Parse properties from a JSON object
  63423. * @param serializationObject defines the JSON object
  63424. */
  63425. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  63426. this.radius = serializationObject.radius;
  63427. this.radiusRange = serializationObject.radiusRange;
  63428. this.directionRandomizer = serializationObject.directionRandomizer;
  63429. };
  63430. return HemisphericParticleEmitter;
  63431. }());
  63432. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  63433. })(BABYLON || (BABYLON = {}));
  63434. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  63435. var BABYLON;
  63436. (function (BABYLON) {
  63437. /**
  63438. * Particle emitter emitting particles from a point.
  63439. * It emits the particles randomly between 2 given directions.
  63440. */
  63441. var PointParticleEmitter = /** @class */ (function () {
  63442. /**
  63443. * Creates a new instance PointParticleEmitter
  63444. */
  63445. function PointParticleEmitter() {
  63446. /**
  63447. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63448. */
  63449. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63450. /**
  63451. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63452. */
  63453. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63454. }
  63455. /**
  63456. * Called by the particle System when the direction is computed for the created particle.
  63457. * @param worldMatrix is the world matrix of the particle system
  63458. * @param directionToUpdate is the direction vector to update with the result
  63459. * @param particle is the particle we are computed the direction for
  63460. */
  63461. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63462. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63463. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63464. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63465. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63466. };
  63467. /**
  63468. * Called by the particle System when the position is computed for the created particle.
  63469. * @param worldMatrix is the world matrix of the particle system
  63470. * @param positionToUpdate is the position vector to update with the result
  63471. * @param particle is the particle we are computed the position for
  63472. */
  63473. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63474. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  63475. };
  63476. /**
  63477. * Clones the current emitter and returns a copy of it
  63478. * @returns the new emitter
  63479. */
  63480. PointParticleEmitter.prototype.clone = function () {
  63481. var newOne = new PointParticleEmitter();
  63482. BABYLON.Tools.DeepCopy(this, newOne);
  63483. return newOne;
  63484. };
  63485. /**
  63486. * Called by the GPUParticleSystem to setup the update shader
  63487. * @param effect defines the update shader
  63488. */
  63489. PointParticleEmitter.prototype.applyToShader = function (effect) {
  63490. effect.setVector3("direction1", this.direction1);
  63491. effect.setVector3("direction2", this.direction2);
  63492. };
  63493. /**
  63494. * Returns a string to use to update the GPU particles update shader
  63495. * @returns a string containng the defines string
  63496. */
  63497. PointParticleEmitter.prototype.getEffectDefines = function () {
  63498. return "#define POINTEMITTER";
  63499. };
  63500. /**
  63501. * Returns the string "PointParticleEmitter"
  63502. * @returns a string containing the class name
  63503. */
  63504. PointParticleEmitter.prototype.getClassName = function () {
  63505. return "PointParticleEmitter";
  63506. };
  63507. /**
  63508. * Serializes the particle system to a JSON object.
  63509. * @returns the JSON object
  63510. */
  63511. PointParticleEmitter.prototype.serialize = function () {
  63512. var serializationObject = {};
  63513. serializationObject.type = this.getClassName();
  63514. serializationObject.direction1 = this.direction1.asArray();
  63515. serializationObject.direction2 = this.direction2.asArray();
  63516. return serializationObject;
  63517. };
  63518. /**
  63519. * Parse properties from a JSON object
  63520. * @param serializationObject defines the JSON object
  63521. */
  63522. PointParticleEmitter.prototype.parse = function (serializationObject) {
  63523. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63524. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63525. };
  63526. return PointParticleEmitter;
  63527. }());
  63528. BABYLON.PointParticleEmitter = PointParticleEmitter;
  63529. })(BABYLON || (BABYLON = {}));
  63530. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  63531. var BABYLON;
  63532. (function (BABYLON) {
  63533. // Adds the parsers to the scene parsers.
  63534. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  63535. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  63536. if (!individualParser) {
  63537. return;
  63538. }
  63539. // Particles Systems
  63540. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63541. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63542. var parsedParticleSystem = parsedData.particleSystems[index];
  63543. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  63544. }
  63545. }
  63546. });
  63547. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  63548. if (parsedParticleSystem.activeParticleCount) {
  63549. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63550. return ps;
  63551. }
  63552. else {
  63553. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63554. return ps;
  63555. }
  63556. });
  63557. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  63558. if (uniformsNames === void 0) { uniformsNames = []; }
  63559. if (samplers === void 0) { samplers = []; }
  63560. if (defines === void 0) { defines = ""; }
  63561. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  63562. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  63563. if (defines.indexOf(" BILLBOARD") === -1) {
  63564. defines += "\n#define BILLBOARD\n";
  63565. }
  63566. if (samplers.indexOf("diffuseSampler") === -1) {
  63567. samplers.push("diffuseSampler");
  63568. }
  63569. return this.createEffect({
  63570. vertex: "particles",
  63571. fragmentElement: fragmentName
  63572. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  63573. };
  63574. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  63575. var results = new Array();
  63576. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63577. var particleSystem = this.getScene().particleSystems[index];
  63578. if (particleSystem.emitter === this) {
  63579. results.push(particleSystem);
  63580. }
  63581. }
  63582. return results;
  63583. };
  63584. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  63585. var results = new Array();
  63586. var descendants = this.getDescendants();
  63587. descendants.push(this);
  63588. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63589. var particleSystem = this.getScene().particleSystems[index];
  63590. var emitter = particleSystem.emitter;
  63591. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  63592. results.push(particleSystem);
  63593. }
  63594. }
  63595. return results;
  63596. };
  63597. })(BABYLON || (BABYLON = {}));
  63598. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  63599. var BABYLON;
  63600. (function (BABYLON) {
  63601. /**
  63602. * Type of sub emitter
  63603. */
  63604. var SubEmitterType;
  63605. (function (SubEmitterType) {
  63606. /**
  63607. * Attached to the particle over it's lifetime
  63608. */
  63609. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  63610. /**
  63611. * Created when the particle dies
  63612. */
  63613. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  63614. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  63615. /**
  63616. * Sub emitter class used to emit particles from an existing particle
  63617. */
  63618. var SubEmitter = /** @class */ (function () {
  63619. /**
  63620. * Creates a sub emitter
  63621. * @param particleSystem the particle system to be used by the sub emitter
  63622. */
  63623. function SubEmitter(
  63624. /**
  63625. * the particle system to be used by the sub emitter
  63626. */
  63627. particleSystem) {
  63628. this.particleSystem = particleSystem;
  63629. /**
  63630. * Type of the submitter (Default: END)
  63631. */
  63632. this.type = SubEmitterType.END;
  63633. /**
  63634. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  63635. * Note: This only is supported when using an emitter of type Mesh
  63636. */
  63637. this.inheritDirection = false;
  63638. /**
  63639. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  63640. */
  63641. this.inheritedVelocityAmount = 0;
  63642. // Create mesh as emitter to support rotation
  63643. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  63644. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  63645. }
  63646. // Automatically dispose of subemitter when system is disposed
  63647. particleSystem.onDisposeObservable.add(function () {
  63648. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  63649. particleSystem.emitter.dispose();
  63650. }
  63651. });
  63652. }
  63653. /**
  63654. * Clones the sub emitter
  63655. * @returns the cloned sub emitter
  63656. */
  63657. SubEmitter.prototype.clone = function () {
  63658. // Clone particle system
  63659. var emitter = this.particleSystem.emitter;
  63660. if (!emitter) {
  63661. emitter = new BABYLON.Vector3();
  63662. }
  63663. else if (emitter instanceof BABYLON.Vector3) {
  63664. emitter = emitter.clone();
  63665. }
  63666. else if (emitter instanceof BABYLON.AbstractMesh) {
  63667. emitter = new BABYLON.Mesh("", emitter.getScene());
  63668. emitter.isVisible = false;
  63669. }
  63670. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  63671. // Clone properties
  63672. clone.type = this.type;
  63673. clone.inheritDirection = this.inheritDirection;
  63674. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63675. clone.particleSystem._disposeEmitterOnDispose = true;
  63676. clone.particleSystem.disposeOnStop = true;
  63677. return clone;
  63678. };
  63679. /**
  63680. * Serialize current object to a JSON object
  63681. * @returns the serialized object
  63682. */
  63683. SubEmitter.prototype.serialize = function () {
  63684. var serializationObject = {};
  63685. serializationObject.type = this.type;
  63686. serializationObject.inheritDirection = this.inheritDirection;
  63687. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63688. serializationObject.particleSystem = this.particleSystem.serialize();
  63689. return serializationObject;
  63690. };
  63691. /**
  63692. * Creates a new SubEmitter from a serialized JSON version
  63693. * @param serializationObject defines the JSON object to read from
  63694. * @param scene defines the hosting scene
  63695. * @param rootUrl defines the rootUrl for data loading
  63696. * @returns a new SubEmitter
  63697. */
  63698. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  63699. var system = serializationObject.particleSystem;
  63700. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  63701. subEmitter.type = serializationObject.type;
  63702. subEmitter.inheritDirection = serializationObject.inheritDirection;
  63703. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  63704. subEmitter.particleSystem._isSubEmitter = true;
  63705. return subEmitter;
  63706. };
  63707. /** Release associated resources */
  63708. SubEmitter.prototype.dispose = function () {
  63709. this.particleSystem.dispose();
  63710. };
  63711. return SubEmitter;
  63712. }());
  63713. BABYLON.SubEmitter = SubEmitter;
  63714. })(BABYLON || (BABYLON = {}));
  63715. //# sourceMappingURL=babylon.subEmitter.js.map
  63716. var BABYLON;
  63717. (function (BABYLON) {
  63718. /**
  63719. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  63720. *
  63721. * This returned material effects how the mesh will look based on the code in the shaders.
  63722. *
  63723. * @see http://doc.babylonjs.com/how_to/shader_material
  63724. */
  63725. var ShaderMaterial = /** @class */ (function (_super) {
  63726. __extends(ShaderMaterial, _super);
  63727. /**
  63728. * Instantiate a new shader material.
  63729. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  63730. * This returned material effects how the mesh will look based on the code in the shaders.
  63731. * @see http://doc.babylonjs.com/how_to/shader_material
  63732. * @param name Define the name of the material in the scene
  63733. * @param scene Define the scene the material belongs to
  63734. * @param shaderPath Defines the route to the shader code in one of three ways:
  63735. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  63736. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  63737. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  63738. * @param options Define the options used to create the shader
  63739. */
  63740. function ShaderMaterial(name, scene, shaderPath, options) {
  63741. if (options === void 0) { options = {}; }
  63742. var _this = _super.call(this, name, scene) || this;
  63743. _this._textures = {};
  63744. _this._textureArrays = {};
  63745. _this._floats = {};
  63746. _this._ints = {};
  63747. _this._floatsArrays = {};
  63748. _this._colors3 = {};
  63749. _this._colors3Arrays = {};
  63750. _this._colors4 = {};
  63751. _this._vectors2 = {};
  63752. _this._vectors3 = {};
  63753. _this._vectors4 = {};
  63754. _this._matrices = {};
  63755. _this._matrices3x3 = {};
  63756. _this._matrices2x2 = {};
  63757. _this._vectors2Arrays = {};
  63758. _this._vectors3Arrays = {};
  63759. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  63760. _this._shaderPath = shaderPath;
  63761. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  63762. return _this;
  63763. }
  63764. /**
  63765. * Gets the current class name of the material e.g. "ShaderMaterial"
  63766. * Mainly use in serialization.
  63767. * @returns the class name
  63768. */
  63769. ShaderMaterial.prototype.getClassName = function () {
  63770. return "ShaderMaterial";
  63771. };
  63772. /**
  63773. * Specifies if the material will require alpha blending
  63774. * @returns a boolean specifying if alpha blending is needed
  63775. */
  63776. ShaderMaterial.prototype.needAlphaBlending = function () {
  63777. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  63778. };
  63779. /**
  63780. * Specifies if this material should be rendered in alpha test mode
  63781. * @returns a boolean specifying if an alpha test is needed.
  63782. */
  63783. ShaderMaterial.prototype.needAlphaTesting = function () {
  63784. return this._options.needAlphaTesting;
  63785. };
  63786. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  63787. if (this._options.uniforms.indexOf(uniformName) === -1) {
  63788. this._options.uniforms.push(uniformName);
  63789. }
  63790. };
  63791. /**
  63792. * Set a texture in the shader.
  63793. * @param name Define the name of the uniform samplers as defined in the shader
  63794. * @param texture Define the texture to bind to this sampler
  63795. * @return the material itself allowing "fluent" like uniform updates
  63796. */
  63797. ShaderMaterial.prototype.setTexture = function (name, texture) {
  63798. if (this._options.samplers.indexOf(name) === -1) {
  63799. this._options.samplers.push(name);
  63800. }
  63801. this._textures[name] = texture;
  63802. return this;
  63803. };
  63804. /**
  63805. * Set a texture array in the shader.
  63806. * @param name Define the name of the uniform sampler array as defined in the shader
  63807. * @param textures Define the list of textures to bind to this sampler
  63808. * @return the material itself allowing "fluent" like uniform updates
  63809. */
  63810. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  63811. if (this._options.samplers.indexOf(name) === -1) {
  63812. this._options.samplers.push(name);
  63813. }
  63814. this._checkUniform(name);
  63815. this._textureArrays[name] = textures;
  63816. return this;
  63817. };
  63818. /**
  63819. * Set a float in the shader.
  63820. * @param name Define the name of the uniform as defined in the shader
  63821. * @param value Define the value to give to the uniform
  63822. * @return the material itself allowing "fluent" like uniform updates
  63823. */
  63824. ShaderMaterial.prototype.setFloat = function (name, value) {
  63825. this._checkUniform(name);
  63826. this._floats[name] = value;
  63827. return this;
  63828. };
  63829. /**
  63830. * Set a int in the shader.
  63831. * @param name Define the name of the uniform as defined in the shader
  63832. * @param value Define the value to give to the uniform
  63833. * @return the material itself allowing "fluent" like uniform updates
  63834. */
  63835. ShaderMaterial.prototype.setInt = function (name, value) {
  63836. this._checkUniform(name);
  63837. this._ints[name] = value;
  63838. return this;
  63839. };
  63840. /**
  63841. * Set an array of floats in the shader.
  63842. * @param name Define the name of the uniform as defined in the shader
  63843. * @param value Define the value to give to the uniform
  63844. * @return the material itself allowing "fluent" like uniform updates
  63845. */
  63846. ShaderMaterial.prototype.setFloats = function (name, value) {
  63847. this._checkUniform(name);
  63848. this._floatsArrays[name] = value;
  63849. return this;
  63850. };
  63851. /**
  63852. * Set a vec3 in the shader from a Color3.
  63853. * @param name Define the name of the uniform as defined in the shader
  63854. * @param value Define the value to give to the uniform
  63855. * @return the material itself allowing "fluent" like uniform updates
  63856. */
  63857. ShaderMaterial.prototype.setColor3 = function (name, value) {
  63858. this._checkUniform(name);
  63859. this._colors3[name] = value;
  63860. return this;
  63861. };
  63862. /**
  63863. * Set a vec3 array in the shader from a Color3 array.
  63864. * @param name Define the name of the uniform as defined in the shader
  63865. * @param value Define the value to give to the uniform
  63866. * @return the material itself allowing "fluent" like uniform updates
  63867. */
  63868. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  63869. this._checkUniform(name);
  63870. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  63871. color.toArray(arr, arr.length);
  63872. return arr;
  63873. }, []);
  63874. return this;
  63875. };
  63876. /**
  63877. * Set a vec4 in the shader from a Color4.
  63878. * @param name Define the name of the uniform as defined in the shader
  63879. * @param value Define the value to give to the uniform
  63880. * @return the material itself allowing "fluent" like uniform updates
  63881. */
  63882. ShaderMaterial.prototype.setColor4 = function (name, value) {
  63883. this._checkUniform(name);
  63884. this._colors4[name] = value;
  63885. return this;
  63886. };
  63887. /**
  63888. * Set a vec2 in the shader from a Vector2.
  63889. * @param name Define the name of the uniform as defined in the shader
  63890. * @param value Define the value to give to the uniform
  63891. * @return the material itself allowing "fluent" like uniform updates
  63892. */
  63893. ShaderMaterial.prototype.setVector2 = function (name, value) {
  63894. this._checkUniform(name);
  63895. this._vectors2[name] = value;
  63896. return this;
  63897. };
  63898. /**
  63899. * Set a vec3 in the shader from a Vector3.
  63900. * @param name Define the name of the uniform as defined in the shader
  63901. * @param value Define the value to give to the uniform
  63902. * @return the material itself allowing "fluent" like uniform updates
  63903. */
  63904. ShaderMaterial.prototype.setVector3 = function (name, value) {
  63905. this._checkUniform(name);
  63906. this._vectors3[name] = value;
  63907. return this;
  63908. };
  63909. /**
  63910. * Set a vec4 in the shader from a Vector4.
  63911. * @param name Define the name of the uniform as defined in the shader
  63912. * @param value Define the value to give to the uniform
  63913. * @return the material itself allowing "fluent" like uniform updates
  63914. */
  63915. ShaderMaterial.prototype.setVector4 = function (name, value) {
  63916. this._checkUniform(name);
  63917. this._vectors4[name] = value;
  63918. return this;
  63919. };
  63920. /**
  63921. * Set a mat4 in the shader from a Matrix.
  63922. * @param name Define the name of the uniform as defined in the shader
  63923. * @param value Define the value to give to the uniform
  63924. * @return the material itself allowing "fluent" like uniform updates
  63925. */
  63926. ShaderMaterial.prototype.setMatrix = function (name, value) {
  63927. this._checkUniform(name);
  63928. this._matrices[name] = value;
  63929. return this;
  63930. };
  63931. /**
  63932. * Set a mat3 in the shader from a Float32Array.
  63933. * @param name Define the name of the uniform as defined in the shader
  63934. * @param value Define the value to give to the uniform
  63935. * @return the material itself allowing "fluent" like uniform updates
  63936. */
  63937. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  63938. this._checkUniform(name);
  63939. this._matrices3x3[name] = value;
  63940. return this;
  63941. };
  63942. /**
  63943. * Set a mat2 in the shader from a Float32Array.
  63944. * @param name Define the name of the uniform as defined in the shader
  63945. * @param value Define the value to give to the uniform
  63946. * @return the material itself allowing "fluent" like uniform updates
  63947. */
  63948. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  63949. this._checkUniform(name);
  63950. this._matrices2x2[name] = value;
  63951. return this;
  63952. };
  63953. /**
  63954. * Set a vec2 array in the shader from a number array.
  63955. * @param name Define the name of the uniform as defined in the shader
  63956. * @param value Define the value to give to the uniform
  63957. * @return the material itself allowing "fluent" like uniform updates
  63958. */
  63959. ShaderMaterial.prototype.setArray2 = function (name, value) {
  63960. this._checkUniform(name);
  63961. this._vectors2Arrays[name] = value;
  63962. return this;
  63963. };
  63964. /**
  63965. * Set a vec3 array in the shader from a number array.
  63966. * @param name Define the name of the uniform as defined in the shader
  63967. * @param value Define the value to give to the uniform
  63968. * @return the material itself allowing "fluent" like uniform updates
  63969. */
  63970. ShaderMaterial.prototype.setArray3 = function (name, value) {
  63971. this._checkUniform(name);
  63972. this._vectors3Arrays[name] = value;
  63973. return this;
  63974. };
  63975. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  63976. if (!mesh) {
  63977. return true;
  63978. }
  63979. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  63980. return false;
  63981. }
  63982. return false;
  63983. };
  63984. /**
  63985. * Checks if the material is ready to render the requested mesh
  63986. * @param mesh Define the mesh to render
  63987. * @param useInstances Define whether or not the material is used with instances
  63988. * @returns true if ready, otherwise false
  63989. */
  63990. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  63991. var scene = this.getScene();
  63992. var engine = scene.getEngine();
  63993. if (!this.checkReadyOnEveryCall) {
  63994. if (this._renderId === scene.getRenderId()) {
  63995. if (this._checkCache(scene, mesh, useInstances)) {
  63996. return true;
  63997. }
  63998. }
  63999. }
  64000. // Instances
  64001. var defines = [];
  64002. var attribs = [];
  64003. var fallbacks = new BABYLON.EffectFallbacks();
  64004. for (var index = 0; index < this._options.defines.length; index++) {
  64005. defines.push(this._options.defines[index]);
  64006. }
  64007. for (var index = 0; index < this._options.attributes.length; index++) {
  64008. attribs.push(this._options.attributes[index]);
  64009. }
  64010. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  64011. attribs.push(BABYLON.VertexBuffer.ColorKind);
  64012. defines.push("#define VERTEXCOLOR");
  64013. }
  64014. if (useInstances) {
  64015. defines.push("#define INSTANCES");
  64016. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  64017. }
  64018. // Bones
  64019. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64020. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64021. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64022. if (mesh.numBoneInfluencers > 4) {
  64023. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64024. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64025. }
  64026. var skeleton = mesh.skeleton;
  64027. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64028. fallbacks.addCPUSkinningFallback(0, mesh);
  64029. if (skeleton.isUsingTextureForMatrices) {
  64030. defines.push("#define BONETEXTURE");
  64031. if (this._options.uniforms.indexOf("boneTextureWidth") === -1) {
  64032. this._options.uniforms.push("boneTextureWidth");
  64033. }
  64034. if (this._options.samplers.indexOf("boneSampler") === -1) {
  64035. this._options.samplers.push("boneSampler");
  64036. }
  64037. }
  64038. else {
  64039. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  64040. if (this._options.uniforms.indexOf("mBones") === -1) {
  64041. this._options.uniforms.push("mBones");
  64042. }
  64043. }
  64044. }
  64045. else {
  64046. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64047. }
  64048. // Textures
  64049. for (var name in this._textures) {
  64050. if (!this._textures[name].isReady()) {
  64051. return false;
  64052. }
  64053. }
  64054. // Alpha test
  64055. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64056. defines.push("#define ALPHATEST");
  64057. }
  64058. var previousEffect = this._effect;
  64059. var join = defines.join("\n");
  64060. this._effect = engine.createEffect(this._shaderPath, {
  64061. attributes: attribs,
  64062. uniformsNames: this._options.uniforms,
  64063. uniformBuffersNames: this._options.uniformBuffers,
  64064. samplers: this._options.samplers,
  64065. defines: join,
  64066. fallbacks: fallbacks,
  64067. onCompiled: this.onCompiled,
  64068. onError: this.onError
  64069. }, engine);
  64070. if (!this._effect.isReady()) {
  64071. return false;
  64072. }
  64073. if (previousEffect !== this._effect) {
  64074. scene.resetCachedMaterial();
  64075. }
  64076. this._renderId = scene.getRenderId();
  64077. return true;
  64078. };
  64079. /**
  64080. * Binds the world matrix to the material
  64081. * @param world defines the world transformation matrix
  64082. */
  64083. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64084. var scene = this.getScene();
  64085. if (!this._effect) {
  64086. return;
  64087. }
  64088. if (this._options.uniforms.indexOf("world") !== -1) {
  64089. this._effect.setMatrix("world", world);
  64090. }
  64091. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64092. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64093. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64094. }
  64095. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64096. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64097. }
  64098. };
  64099. /**
  64100. * Binds the material to the mesh
  64101. * @param world defines the world transformation matrix
  64102. * @param mesh defines the mesh to bind the material to
  64103. */
  64104. ShaderMaterial.prototype.bind = function (world, mesh) {
  64105. // Std values
  64106. this.bindOnlyWorldMatrix(world);
  64107. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64108. if (this._options.uniforms.indexOf("view") !== -1) {
  64109. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64110. }
  64111. if (this._options.uniforms.indexOf("projection") !== -1) {
  64112. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64113. }
  64114. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64115. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64116. }
  64117. // Bones
  64118. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64119. var name;
  64120. // Texture
  64121. for (name in this._textures) {
  64122. this._effect.setTexture(name, this._textures[name]);
  64123. }
  64124. // Texture arrays
  64125. for (name in this._textureArrays) {
  64126. this._effect.setTextureArray(name, this._textureArrays[name]);
  64127. }
  64128. // Int
  64129. for (name in this._ints) {
  64130. this._effect.setInt(name, this._ints[name]);
  64131. }
  64132. // Float
  64133. for (name in this._floats) {
  64134. this._effect.setFloat(name, this._floats[name]);
  64135. }
  64136. // Floats
  64137. for (name in this._floatsArrays) {
  64138. this._effect.setArray(name, this._floatsArrays[name]);
  64139. }
  64140. // Color3
  64141. for (name in this._colors3) {
  64142. this._effect.setColor3(name, this._colors3[name]);
  64143. }
  64144. for (name in this._colors3Arrays) {
  64145. this._effect.setArray3(name, this._colors3Arrays[name]);
  64146. }
  64147. // Color4
  64148. for (name in this._colors4) {
  64149. var color = this._colors4[name];
  64150. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64151. }
  64152. // Vector2
  64153. for (name in this._vectors2) {
  64154. this._effect.setVector2(name, this._vectors2[name]);
  64155. }
  64156. // Vector3
  64157. for (name in this._vectors3) {
  64158. this._effect.setVector3(name, this._vectors3[name]);
  64159. }
  64160. // Vector4
  64161. for (name in this._vectors4) {
  64162. this._effect.setVector4(name, this._vectors4[name]);
  64163. }
  64164. // Matrix
  64165. for (name in this._matrices) {
  64166. this._effect.setMatrix(name, this._matrices[name]);
  64167. }
  64168. // Matrix 3x3
  64169. for (name in this._matrices3x3) {
  64170. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64171. }
  64172. // Matrix 2x2
  64173. for (name in this._matrices2x2) {
  64174. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64175. }
  64176. // Vector2Array
  64177. for (name in this._vectors2Arrays) {
  64178. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64179. }
  64180. // Vector3Array
  64181. for (name in this._vectors3Arrays) {
  64182. this._effect.setArray3(name, this._vectors3Arrays[name]);
  64183. }
  64184. }
  64185. this._afterBind(mesh);
  64186. };
  64187. /**
  64188. * Gets the active textures from the material
  64189. * @returns an array of textures
  64190. */
  64191. ShaderMaterial.prototype.getActiveTextures = function () {
  64192. var activeTextures = _super.prototype.getActiveTextures.call(this);
  64193. for (var name in this._textures) {
  64194. activeTextures.push(this._textures[name]);
  64195. }
  64196. for (var name in this._textureArrays) {
  64197. var array = this._textureArrays[name];
  64198. for (var index = 0; index < array.length; index++) {
  64199. activeTextures.push(array[index]);
  64200. }
  64201. }
  64202. return activeTextures;
  64203. };
  64204. /**
  64205. * Specifies if the material uses a texture
  64206. * @param texture defines the texture to check against the material
  64207. * @returns a boolean specifying if the material uses the texture
  64208. */
  64209. ShaderMaterial.prototype.hasTexture = function (texture) {
  64210. if (_super.prototype.hasTexture.call(this, texture)) {
  64211. return true;
  64212. }
  64213. for (var name in this._textures) {
  64214. if (this._textures[name] === texture) {
  64215. return true;
  64216. }
  64217. }
  64218. for (var name in this._textureArrays) {
  64219. var array = this._textureArrays[name];
  64220. for (var index = 0; index < array.length; index++) {
  64221. if (array[index] === texture) {
  64222. return true;
  64223. }
  64224. }
  64225. }
  64226. return false;
  64227. };
  64228. /**
  64229. * Makes a duplicate of the material, and gives it a new name
  64230. * @param name defines the new name for the duplicated material
  64231. * @returns the cloned material
  64232. */
  64233. ShaderMaterial.prototype.clone = function (name) {
  64234. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  64235. return newShaderMaterial;
  64236. };
  64237. /**
  64238. * Disposes the material
  64239. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  64240. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  64241. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  64242. */
  64243. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  64244. if (forceDisposeTextures) {
  64245. var name;
  64246. for (name in this._textures) {
  64247. this._textures[name].dispose();
  64248. }
  64249. for (name in this._textureArrays) {
  64250. var array = this._textureArrays[name];
  64251. for (var index = 0; index < array.length; index++) {
  64252. array[index].dispose();
  64253. }
  64254. }
  64255. }
  64256. this._textures = {};
  64257. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  64258. };
  64259. /**
  64260. * Serializes this material in a JSON representation
  64261. * @returns the serialized material object
  64262. */
  64263. ShaderMaterial.prototype.serialize = function () {
  64264. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64265. serializationObject.customType = "BABYLON.ShaderMaterial";
  64266. serializationObject.options = this._options;
  64267. serializationObject.shaderPath = this._shaderPath;
  64268. var name;
  64269. // Texture
  64270. serializationObject.textures = {};
  64271. for (name in this._textures) {
  64272. serializationObject.textures[name] = this._textures[name].serialize();
  64273. }
  64274. // Texture arrays
  64275. serializationObject.textureArrays = {};
  64276. for (name in this._textureArrays) {
  64277. serializationObject.textureArrays[name] = [];
  64278. var array = this._textureArrays[name];
  64279. for (var index = 0; index < array.length; index++) {
  64280. serializationObject.textureArrays[name].push(array[index].serialize());
  64281. }
  64282. }
  64283. // Float
  64284. serializationObject.floats = {};
  64285. for (name in this._floats) {
  64286. serializationObject.floats[name] = this._floats[name];
  64287. }
  64288. // Float s
  64289. serializationObject.FloatArrays = {};
  64290. for (name in this._floatsArrays) {
  64291. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  64292. }
  64293. // Color3
  64294. serializationObject.colors3 = {};
  64295. for (name in this._colors3) {
  64296. serializationObject.colors3[name] = this._colors3[name].asArray();
  64297. }
  64298. // Color3 array
  64299. serializationObject.colors3Arrays = {};
  64300. for (name in this._colors3Arrays) {
  64301. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  64302. }
  64303. // Color4
  64304. serializationObject.colors4 = {};
  64305. for (name in this._colors4) {
  64306. serializationObject.colors4[name] = this._colors4[name].asArray();
  64307. }
  64308. // Vector2
  64309. serializationObject.vectors2 = {};
  64310. for (name in this._vectors2) {
  64311. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  64312. }
  64313. // Vector3
  64314. serializationObject.vectors3 = {};
  64315. for (name in this._vectors3) {
  64316. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  64317. }
  64318. // Vector4
  64319. serializationObject.vectors4 = {};
  64320. for (name in this._vectors4) {
  64321. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  64322. }
  64323. // Matrix
  64324. serializationObject.matrices = {};
  64325. for (name in this._matrices) {
  64326. serializationObject.matrices[name] = this._matrices[name].asArray();
  64327. }
  64328. // Matrix 3x3
  64329. serializationObject.matrices3x3 = {};
  64330. for (name in this._matrices3x3) {
  64331. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  64332. }
  64333. // Matrix 2x2
  64334. serializationObject.matrices2x2 = {};
  64335. for (name in this._matrices2x2) {
  64336. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  64337. }
  64338. // Vector2Array
  64339. serializationObject.vectors2Arrays = {};
  64340. for (name in this._vectors2Arrays) {
  64341. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  64342. }
  64343. // Vector3Array
  64344. serializationObject.vectors3Arrays = {};
  64345. for (name in this._vectors3Arrays) {
  64346. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  64347. }
  64348. return serializationObject;
  64349. };
  64350. /**
  64351. * Creates a shader material from parsed shader material data
  64352. * @param source defines the JSON represnetation of the material
  64353. * @param scene defines the hosting scene
  64354. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  64355. * @returns a new material
  64356. */
  64357. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  64358. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  64359. var name;
  64360. // Texture
  64361. for (name in source.textures) {
  64362. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  64363. }
  64364. // Texture arrays
  64365. for (name in source.textureArrays) {
  64366. var array = source.textureArrays[name];
  64367. var textureArray = new Array();
  64368. for (var index = 0; index < array.length; index++) {
  64369. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  64370. }
  64371. material.setTextureArray(name, textureArray);
  64372. }
  64373. // Float
  64374. for (name in source.floats) {
  64375. material.setFloat(name, source.floats[name]);
  64376. }
  64377. // Float s
  64378. for (name in source.floatsArrays) {
  64379. material.setFloats(name, source.floatsArrays[name]);
  64380. }
  64381. // Color3
  64382. for (name in source.colors3) {
  64383. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  64384. }
  64385. // Color3 arrays
  64386. for (name in source.colors3Arrays) {
  64387. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  64388. if (i % 3 === 0) {
  64389. arr.push([num]);
  64390. }
  64391. else {
  64392. arr[arr.length - 1].push(num);
  64393. }
  64394. return arr;
  64395. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  64396. material.setColor3Array(name, colors);
  64397. }
  64398. // Color4
  64399. for (name in source.colors4) {
  64400. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  64401. }
  64402. // Vector2
  64403. for (name in source.vectors2) {
  64404. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  64405. }
  64406. // Vector3
  64407. for (name in source.vectors3) {
  64408. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  64409. }
  64410. // Vector4
  64411. for (name in source.vectors4) {
  64412. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  64413. }
  64414. // Matrix
  64415. for (name in source.matrices) {
  64416. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  64417. }
  64418. // Matrix 3x3
  64419. for (name in source.matrices3x3) {
  64420. material.setMatrix3x3(name, source.matrices3x3[name]);
  64421. }
  64422. // Matrix 2x2
  64423. for (name in source.matrices2x2) {
  64424. material.setMatrix2x2(name, source.matrices2x2[name]);
  64425. }
  64426. // Vector2Array
  64427. for (name in source.vectors2Arrays) {
  64428. material.setArray2(name, source.vectors2Arrays[name]);
  64429. }
  64430. // Vector3Array
  64431. for (name in source.vectors3Arrays) {
  64432. material.setArray3(name, source.vectors3Arrays[name]);
  64433. }
  64434. return material;
  64435. };
  64436. return ShaderMaterial;
  64437. }(BABYLON.Material));
  64438. BABYLON.ShaderMaterial = ShaderMaterial;
  64439. })(BABYLON || (BABYLON = {}));
  64440. //# sourceMappingURL=babylon.shaderMaterial.js.map
  64441. var BABYLON;
  64442. (function (BABYLON) {
  64443. /**
  64444. * Mesh representing the gorund
  64445. */
  64446. var GroundMesh = /** @class */ (function (_super) {
  64447. __extends(GroundMesh, _super);
  64448. function GroundMesh(name, scene) {
  64449. var _this = _super.call(this, name, scene) || this;
  64450. /** If octree should be generated */
  64451. _this.generateOctree = false;
  64452. return _this;
  64453. }
  64454. /**
  64455. * "GroundMesh"
  64456. * @returns "GroundMesh"
  64457. */
  64458. GroundMesh.prototype.getClassName = function () {
  64459. return "GroundMesh";
  64460. };
  64461. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  64462. /**
  64463. * The minimum of x and y subdivisions
  64464. */
  64465. get: function () {
  64466. return Math.min(this._subdivisionsX, this._subdivisionsY);
  64467. },
  64468. enumerable: true,
  64469. configurable: true
  64470. });
  64471. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  64472. /**
  64473. * X subdivisions
  64474. */
  64475. get: function () {
  64476. return this._subdivisionsX;
  64477. },
  64478. enumerable: true,
  64479. configurable: true
  64480. });
  64481. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  64482. /**
  64483. * Y subdivisions
  64484. */
  64485. get: function () {
  64486. return this._subdivisionsY;
  64487. },
  64488. enumerable: true,
  64489. configurable: true
  64490. });
  64491. /**
  64492. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  64493. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  64494. * @param chunksCount the number of subdivisions for x and y
  64495. * @param octreeBlocksSize (Default: 32)
  64496. */
  64497. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  64498. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  64499. this._subdivisionsX = chunksCount;
  64500. this._subdivisionsY = chunksCount;
  64501. this.subdivide(chunksCount);
  64502. // Call the octree system optimization if it is defined.
  64503. var thisAsAny = this;
  64504. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  64505. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  64506. }
  64507. };
  64508. /**
  64509. * Returns a height (y) value in the Worl system :
  64510. * the ground altitude at the coordinates (x, z) expressed in the World system.
  64511. * @param x x coordinate
  64512. * @param z z coordinate
  64513. * @returns the ground y position if (x, z) are outside the ground surface.
  64514. */
  64515. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  64516. var world = this.getWorldMatrix();
  64517. var invMat = BABYLON.Tmp.Matrix[5];
  64518. world.invertToRef(invMat);
  64519. var tmpVect = BABYLON.Tmp.Vector3[8];
  64520. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  64521. x = tmpVect.x;
  64522. z = tmpVect.z;
  64523. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64524. return this.position.y;
  64525. }
  64526. if (!this._heightQuads || this._heightQuads.length == 0) {
  64527. this._initHeightQuads();
  64528. this._computeHeightQuads();
  64529. }
  64530. var facet = this._getFacetAt(x, z);
  64531. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  64532. // return y in the World system
  64533. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  64534. return tmpVect.y;
  64535. };
  64536. /**
  64537. * Returns a normalized vector (Vector3) orthogonal to the ground
  64538. * at the ground coordinates (x, z) expressed in the World system.
  64539. * @param x x coordinate
  64540. * @param z z coordinate
  64541. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  64542. */
  64543. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  64544. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  64545. this.getNormalAtCoordinatesToRef(x, z, normal);
  64546. return normal;
  64547. };
  64548. /**
  64549. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  64550. * at the ground coordinates (x, z) expressed in the World system.
  64551. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  64552. * @param x x coordinate
  64553. * @param z z coordinate
  64554. * @param ref vector to store the result
  64555. * @returns the GroundMesh.
  64556. */
  64557. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  64558. var world = this.getWorldMatrix();
  64559. var tmpMat = BABYLON.Tmp.Matrix[5];
  64560. world.invertToRef(tmpMat);
  64561. var tmpVect = BABYLON.Tmp.Vector3[8];
  64562. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  64563. x = tmpVect.x;
  64564. z = tmpVect.z;
  64565. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64566. return this;
  64567. }
  64568. if (!this._heightQuads || this._heightQuads.length == 0) {
  64569. this._initHeightQuads();
  64570. this._computeHeightQuads();
  64571. }
  64572. var facet = this._getFacetAt(x, z);
  64573. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  64574. return this;
  64575. };
  64576. /**
  64577. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  64578. * if the ground has been updated.
  64579. * This can be used in the render loop.
  64580. * @returns the GroundMesh.
  64581. */
  64582. GroundMesh.prototype.updateCoordinateHeights = function () {
  64583. if (!this._heightQuads || this._heightQuads.length == 0) {
  64584. this._initHeightQuads();
  64585. }
  64586. this._computeHeightQuads();
  64587. return this;
  64588. };
  64589. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  64590. GroundMesh.prototype._getFacetAt = function (x, z) {
  64591. // retrieve col and row from x, z coordinates in the ground local system
  64592. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  64593. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  64594. var quad = this._heightQuads[row * this._subdivisionsX + col];
  64595. var facet;
  64596. if (z < quad.slope.x * x + quad.slope.y) {
  64597. facet = quad.facet1;
  64598. }
  64599. else {
  64600. facet = quad.facet2;
  64601. }
  64602. return facet;
  64603. };
  64604. // Creates and populates the heightMap array with "facet" elements :
  64605. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  64606. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64607. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64608. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64609. // Returns the GroundMesh.
  64610. GroundMesh.prototype._initHeightQuads = function () {
  64611. var subdivisionsX = this._subdivisionsX;
  64612. var subdivisionsY = this._subdivisionsY;
  64613. this._heightQuads = new Array();
  64614. for (var row = 0; row < subdivisionsY; row++) {
  64615. for (var col = 0; col < subdivisionsX; col++) {
  64616. 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) };
  64617. this._heightQuads[row * subdivisionsX + col] = quad;
  64618. }
  64619. }
  64620. return this;
  64621. };
  64622. // Compute each quad element values and update the the heightMap array :
  64623. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64624. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64625. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64626. // Returns the GroundMesh.
  64627. GroundMesh.prototype._computeHeightQuads = function () {
  64628. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64629. if (!positions) {
  64630. return this;
  64631. }
  64632. var v1 = BABYLON.Tmp.Vector3[3];
  64633. var v2 = BABYLON.Tmp.Vector3[2];
  64634. var v3 = BABYLON.Tmp.Vector3[1];
  64635. var v4 = BABYLON.Tmp.Vector3[0];
  64636. var v1v2 = BABYLON.Tmp.Vector3[4];
  64637. var v1v3 = BABYLON.Tmp.Vector3[5];
  64638. var v1v4 = BABYLON.Tmp.Vector3[6];
  64639. var norm1 = BABYLON.Tmp.Vector3[7];
  64640. var norm2 = BABYLON.Tmp.Vector3[8];
  64641. var i = 0;
  64642. var j = 0;
  64643. var k = 0;
  64644. var cd = 0; // 2D slope coefficient : z = cd * x + h
  64645. var h = 0;
  64646. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  64647. var d2 = 0;
  64648. var subdivisionsX = this._subdivisionsX;
  64649. var subdivisionsY = this._subdivisionsY;
  64650. for (var row = 0; row < subdivisionsY; row++) {
  64651. for (var col = 0; col < subdivisionsX; col++) {
  64652. i = col * 3;
  64653. j = row * (subdivisionsX + 1) * 3;
  64654. k = (row + 1) * (subdivisionsX + 1) * 3;
  64655. v1.x = positions[j + i];
  64656. v1.y = positions[j + i + 1];
  64657. v1.z = positions[j + i + 2];
  64658. v2.x = positions[j + i + 3];
  64659. v2.y = positions[j + i + 4];
  64660. v2.z = positions[j + i + 5];
  64661. v3.x = positions[k + i];
  64662. v3.y = positions[k + i + 1];
  64663. v3.z = positions[k + i + 2];
  64664. v4.x = positions[k + i + 3];
  64665. v4.y = positions[k + i + 4];
  64666. v4.z = positions[k + i + 5];
  64667. // 2D slope V1V4
  64668. cd = (v4.z - v1.z) / (v4.x - v1.x);
  64669. h = v1.z - cd * v1.x; // v1 belongs to the slope
  64670. // facet equations :
  64671. // we compute each facet normal vector
  64672. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  64673. // we compute the value d by applying the equation to v1 which belongs to the plane
  64674. // then we store the facet equation in a Vector4
  64675. v2.subtractToRef(v1, v1v2);
  64676. v3.subtractToRef(v1, v1v3);
  64677. v4.subtractToRef(v1, v1v4);
  64678. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  64679. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  64680. norm1.normalize();
  64681. norm2.normalize();
  64682. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  64683. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  64684. var quad = this._heightQuads[row * subdivisionsX + col];
  64685. quad.slope.copyFromFloats(cd, h);
  64686. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  64687. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  64688. }
  64689. }
  64690. return this;
  64691. };
  64692. /**
  64693. * Serializes this ground mesh
  64694. * @param serializationObject object to write serialization to
  64695. */
  64696. GroundMesh.prototype.serialize = function (serializationObject) {
  64697. _super.prototype.serialize.call(this, serializationObject);
  64698. serializationObject.subdivisionsX = this._subdivisionsX;
  64699. serializationObject.subdivisionsY = this._subdivisionsY;
  64700. serializationObject.minX = this._minX;
  64701. serializationObject.maxX = this._maxX;
  64702. serializationObject.minZ = this._minZ;
  64703. serializationObject.maxZ = this._maxZ;
  64704. serializationObject.width = this._width;
  64705. serializationObject.height = this._height;
  64706. };
  64707. /**
  64708. * Parses a serialized ground mesh
  64709. * @param parsedMesh the serialized mesh
  64710. * @param scene the scene to create the ground mesh in
  64711. * @returns the created ground mesh
  64712. */
  64713. GroundMesh.Parse = function (parsedMesh, scene) {
  64714. var result = new GroundMesh(parsedMesh.name, scene);
  64715. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  64716. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  64717. result._minX = parsedMesh.minX;
  64718. result._maxX = parsedMesh.maxX;
  64719. result._minZ = parsedMesh.minZ;
  64720. result._maxZ = parsedMesh.maxZ;
  64721. result._width = parsedMesh.width;
  64722. result._height = parsedMesh.height;
  64723. return result;
  64724. };
  64725. return GroundMesh;
  64726. }(BABYLON.Mesh));
  64727. BABYLON.GroundMesh = GroundMesh;
  64728. })(BABYLON || (BABYLON = {}));
  64729. //# sourceMappingURL=babylon.groundMesh.js.map
  64730. var BABYLON;
  64731. (function (BABYLON) {
  64732. /**
  64733. * Creates an instance based on a source mesh.
  64734. */
  64735. var InstancedMesh = /** @class */ (function (_super) {
  64736. __extends(InstancedMesh, _super);
  64737. function InstancedMesh(name, source) {
  64738. var _this = _super.call(this, name, source.getScene()) || this;
  64739. /** @hidden */
  64740. _this._indexInSourceMeshInstanceArray = -1;
  64741. source.addInstance(_this);
  64742. _this._sourceMesh = source;
  64743. _this.position.copyFrom(source.position);
  64744. _this.rotation.copyFrom(source.rotation);
  64745. _this.scaling.copyFrom(source.scaling);
  64746. if (source.rotationQuaternion) {
  64747. _this.rotationQuaternion = source.rotationQuaternion.clone();
  64748. }
  64749. _this.infiniteDistance = source.infiniteDistance;
  64750. _this.setPivotMatrix(source.getPivotMatrix());
  64751. _this.refreshBoundingInfo();
  64752. _this._syncSubMeshes();
  64753. return _this;
  64754. }
  64755. /**
  64756. * Returns the string "InstancedMesh".
  64757. */
  64758. InstancedMesh.prototype.getClassName = function () {
  64759. return "InstancedMesh";
  64760. };
  64761. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  64762. // Methods
  64763. /**
  64764. * If the source mesh receives shadows
  64765. */
  64766. get: function () {
  64767. return this._sourceMesh.receiveShadows;
  64768. },
  64769. enumerable: true,
  64770. configurable: true
  64771. });
  64772. Object.defineProperty(InstancedMesh.prototype, "material", {
  64773. /**
  64774. * The material of the source mesh
  64775. */
  64776. get: function () {
  64777. return this._sourceMesh.material;
  64778. },
  64779. enumerable: true,
  64780. configurable: true
  64781. });
  64782. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  64783. /**
  64784. * Visibility of the source mesh
  64785. */
  64786. get: function () {
  64787. return this._sourceMesh.visibility;
  64788. },
  64789. enumerable: true,
  64790. configurable: true
  64791. });
  64792. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  64793. /**
  64794. * Skeleton of the source mesh
  64795. */
  64796. get: function () {
  64797. return this._sourceMesh.skeleton;
  64798. },
  64799. enumerable: true,
  64800. configurable: true
  64801. });
  64802. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  64803. /**
  64804. * Rendering ground id of the source mesh
  64805. */
  64806. get: function () {
  64807. return this._sourceMesh.renderingGroupId;
  64808. },
  64809. set: function (value) {
  64810. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  64811. return;
  64812. }
  64813. //no-op with warning
  64814. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  64815. },
  64816. enumerable: true,
  64817. configurable: true
  64818. });
  64819. /**
  64820. * Returns the total number of vertices (integer).
  64821. */
  64822. InstancedMesh.prototype.getTotalVertices = function () {
  64823. return this._sourceMesh.getTotalVertices();
  64824. };
  64825. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  64826. /**
  64827. * The source mesh of the instance
  64828. */
  64829. get: function () {
  64830. return this._sourceMesh;
  64831. },
  64832. enumerable: true,
  64833. configurable: true
  64834. });
  64835. /**
  64836. * Is this node ready to be used/rendered
  64837. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  64838. * @return {boolean} is it ready
  64839. */
  64840. InstancedMesh.prototype.isReady = function (completeCheck) {
  64841. if (completeCheck === void 0) { completeCheck = false; }
  64842. return this._sourceMesh.isReady(completeCheck, true);
  64843. };
  64844. /**
  64845. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  64846. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  64847. * @param copyWhenShared If 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.
  64848. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  64849. */
  64850. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  64851. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  64852. };
  64853. /**
  64854. * Sets the vertex data of the mesh geometry for the requested `kind`.
  64855. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  64856. * The `data` are either a numeric array either a Float32Array.
  64857. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  64858. * 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).
  64859. * Note that a new underlying VertexBuffer object is created each call.
  64860. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  64861. *
  64862. * Possible `kind` values :
  64863. * - BABYLON.VertexBuffer.PositionKind
  64864. * - BABYLON.VertexBuffer.UVKind
  64865. * - BABYLON.VertexBuffer.UV2Kind
  64866. * - BABYLON.VertexBuffer.UV3Kind
  64867. * - BABYLON.VertexBuffer.UV4Kind
  64868. * - BABYLON.VertexBuffer.UV5Kind
  64869. * - BABYLON.VertexBuffer.UV6Kind
  64870. * - BABYLON.VertexBuffer.ColorKind
  64871. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64872. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64873. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64874. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64875. *
  64876. * Returns the Mesh.
  64877. */
  64878. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  64879. if (this.sourceMesh) {
  64880. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  64881. }
  64882. return this.sourceMesh;
  64883. };
  64884. /**
  64885. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  64886. * If the mesh has no geometry, it is simply returned as it is.
  64887. * The `data` are either a numeric array either a Float32Array.
  64888. * No new underlying VertexBuffer object is created.
  64889. * 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.
  64890. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  64891. *
  64892. * Possible `kind` values :
  64893. * - BABYLON.VertexBuffer.PositionKind
  64894. * - BABYLON.VertexBuffer.UVKind
  64895. * - BABYLON.VertexBuffer.UV2Kind
  64896. * - BABYLON.VertexBuffer.UV3Kind
  64897. * - BABYLON.VertexBuffer.UV4Kind
  64898. * - BABYLON.VertexBuffer.UV5Kind
  64899. * - BABYLON.VertexBuffer.UV6Kind
  64900. * - BABYLON.VertexBuffer.ColorKind
  64901. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64902. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64903. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64904. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64905. *
  64906. * Returns the Mesh.
  64907. */
  64908. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  64909. if (this.sourceMesh) {
  64910. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  64911. }
  64912. return this.sourceMesh;
  64913. };
  64914. /**
  64915. * Sets the mesh indices.
  64916. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  64917. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  64918. * This method creates a new index buffer each call.
  64919. * Returns the Mesh.
  64920. */
  64921. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  64922. if (totalVertices === void 0) { totalVertices = null; }
  64923. if (this.sourceMesh) {
  64924. this.sourceMesh.setIndices(indices, totalVertices);
  64925. }
  64926. return this.sourceMesh;
  64927. };
  64928. /**
  64929. * Boolean : True if the mesh owns the requested kind of data.
  64930. */
  64931. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  64932. return this._sourceMesh.isVerticesDataPresent(kind);
  64933. };
  64934. /**
  64935. * Returns an array of indices (IndicesArray).
  64936. */
  64937. InstancedMesh.prototype.getIndices = function () {
  64938. return this._sourceMesh.getIndices();
  64939. };
  64940. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  64941. get: function () {
  64942. return this._sourceMesh._positions;
  64943. },
  64944. enumerable: true,
  64945. configurable: true
  64946. });
  64947. /**
  64948. * reconstructs and updates the BoundingInfo of the mesh.
  64949. * @returns the mesh.
  64950. */
  64951. InstancedMesh.prototype.refreshBoundingInfo = function () {
  64952. var meshBB = this._sourceMesh.getBoundingInfo();
  64953. if (this._boundingInfo) {
  64954. this._boundingInfo.reConstruct(meshBB.minimum, meshBB.maximum);
  64955. }
  64956. else {
  64957. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum, meshBB.maximum);
  64958. }
  64959. this._updateBoundingInfo();
  64960. return this;
  64961. };
  64962. /** @hidden */
  64963. InstancedMesh.prototype._preActivate = function () {
  64964. if (this._currentLOD) {
  64965. this._currentLOD._preActivate();
  64966. }
  64967. return this;
  64968. };
  64969. /** @hidden */
  64970. InstancedMesh.prototype._activate = function (renderId) {
  64971. if (this._currentLOD) {
  64972. this._currentLOD._registerInstanceForRenderId(this, renderId);
  64973. }
  64974. return this;
  64975. };
  64976. /**
  64977. * Returns the current associated LOD AbstractMesh.
  64978. */
  64979. InstancedMesh.prototype.getLOD = function (camera) {
  64980. if (!camera) {
  64981. return this;
  64982. }
  64983. var boundingInfo = this.getBoundingInfo();
  64984. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  64985. if (this._currentLOD === this.sourceMesh) {
  64986. return this;
  64987. }
  64988. return this._currentLOD;
  64989. };
  64990. /** @hidden */
  64991. InstancedMesh.prototype._syncSubMeshes = function () {
  64992. this.releaseSubMeshes();
  64993. if (this._sourceMesh.subMeshes) {
  64994. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  64995. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  64996. }
  64997. }
  64998. return this;
  64999. };
  65000. /** @hidden */
  65001. InstancedMesh.prototype._generatePointsArray = function () {
  65002. return this._sourceMesh._generatePointsArray();
  65003. };
  65004. /**
  65005. * Creates a new InstancedMesh from the current mesh.
  65006. * - name (string) : the cloned mesh name
  65007. * - newParent (optional Node) : the optional Node to parent the clone to.
  65008. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  65009. *
  65010. * Returns the clone.
  65011. */
  65012. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65013. var result = this._sourceMesh.createInstance(name);
  65014. // Deep copy
  65015. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  65016. // Bounding info
  65017. this.refreshBoundingInfo();
  65018. // Parent
  65019. if (newParent) {
  65020. result.parent = newParent;
  65021. }
  65022. if (!doNotCloneChildren) {
  65023. // Children
  65024. for (var index = 0; index < this.getScene().meshes.length; index++) {
  65025. var mesh = this.getScene().meshes[index];
  65026. if (mesh.parent === this) {
  65027. mesh.clone(mesh.name, result);
  65028. }
  65029. }
  65030. }
  65031. result.computeWorldMatrix(true);
  65032. return result;
  65033. };
  65034. /**
  65035. * Disposes the InstancedMesh.
  65036. * Returns nothing.
  65037. */
  65038. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  65039. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  65040. // Remove from mesh
  65041. this._sourceMesh.removeInstance(this);
  65042. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  65043. };
  65044. return InstancedMesh;
  65045. }(BABYLON.AbstractMesh));
  65046. BABYLON.InstancedMesh = InstancedMesh;
  65047. })(BABYLON || (BABYLON = {}));
  65048. //# sourceMappingURL=babylon.instancedMesh.js.map
  65049. var BABYLON;
  65050. (function (BABYLON) {
  65051. /**
  65052. * Line mesh
  65053. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65054. */
  65055. var LinesMesh = /** @class */ (function (_super) {
  65056. __extends(LinesMesh, _super);
  65057. /**
  65058. * Creates a new LinesMesh
  65059. * @param name defines the name
  65060. * @param scene defines the hosting scene
  65061. * @param parent defines the parent mesh if any
  65062. * @param source defines the optional source LinesMesh used to clone data from
  65063. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65064. * When false, achieved by calling a clone(), also passing False.
  65065. * This will make creation of children, recursive.
  65066. * @param useVertexColor defines if this LinesMesh supports vertex color
  65067. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65068. */
  65069. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65070. /**
  65071. * If vertex color should be applied to the mesh
  65072. */
  65073. useVertexColor,
  65074. /**
  65075. * If vertex alpha should be applied to the mesh
  65076. */
  65077. useVertexAlpha) {
  65078. if (scene === void 0) { scene = null; }
  65079. if (parent === void 0) { parent = null; }
  65080. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65081. _this.useVertexColor = useVertexColor;
  65082. _this.useVertexAlpha = useVertexAlpha;
  65083. /**
  65084. * Color of the line (Default: White)
  65085. */
  65086. _this.color = new BABYLON.Color3(1, 1, 1);
  65087. /**
  65088. * Alpha of the line (Default: 1)
  65089. */
  65090. _this.alpha = 1;
  65091. if (source) {
  65092. _this.color = source.color.clone();
  65093. _this.alpha = source.alpha;
  65094. _this.useVertexColor = source.useVertexColor;
  65095. _this.useVertexAlpha = source.useVertexAlpha;
  65096. }
  65097. _this._intersectionThreshold = 0.1;
  65098. var defines = [];
  65099. var options = {
  65100. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65101. uniforms: ["world", "viewProjection"],
  65102. needAlphaBlending: true,
  65103. defines: defines
  65104. };
  65105. if (useVertexAlpha === false) {
  65106. options.needAlphaBlending = false;
  65107. }
  65108. if (!useVertexColor) {
  65109. options.uniforms.push("color");
  65110. }
  65111. else {
  65112. options.defines.push("#define VERTEXCOLOR");
  65113. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65114. }
  65115. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65116. return _this;
  65117. }
  65118. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  65119. /**
  65120. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65121. * This margin is expressed in world space coordinates, so its value may vary.
  65122. * Default value is 0.1
  65123. * @returns the intersection Threshold value.
  65124. */
  65125. get: function () {
  65126. return this._intersectionThreshold;
  65127. },
  65128. /**
  65129. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65130. * This margin is expressed in world space coordinates, so its value may vary.
  65131. */
  65132. set: function (value) {
  65133. if (this._intersectionThreshold === value) {
  65134. return;
  65135. }
  65136. this._intersectionThreshold = value;
  65137. },
  65138. enumerable: true,
  65139. configurable: true
  65140. });
  65141. /**
  65142. * Returns the string "LineMesh"
  65143. */
  65144. LinesMesh.prototype.getClassName = function () {
  65145. return "LinesMesh";
  65146. };
  65147. Object.defineProperty(LinesMesh.prototype, "material", {
  65148. /**
  65149. * @hidden
  65150. */
  65151. get: function () {
  65152. return this._colorShader;
  65153. },
  65154. /**
  65155. * @hidden
  65156. */
  65157. set: function (value) {
  65158. // Do nothing
  65159. },
  65160. enumerable: true,
  65161. configurable: true
  65162. });
  65163. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65164. /**
  65165. * @hidden
  65166. */
  65167. get: function () {
  65168. return false;
  65169. },
  65170. enumerable: true,
  65171. configurable: true
  65172. });
  65173. /** @hidden */
  65174. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65175. if (!this._geometry) {
  65176. return this;
  65177. }
  65178. // VBOs
  65179. this._geometry._bind(this._colorShader.getEffect());
  65180. // Color
  65181. if (!this.useVertexColor) {
  65182. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65183. }
  65184. return this;
  65185. };
  65186. /** @hidden */
  65187. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65188. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65189. return this;
  65190. }
  65191. var engine = this.getScene().getEngine();
  65192. // Draw order
  65193. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65194. return this;
  65195. };
  65196. /**
  65197. * Disposes of the line mesh
  65198. * @param doNotRecurse If children should be disposed
  65199. */
  65200. LinesMesh.prototype.dispose = function (doNotRecurse) {
  65201. this._colorShader.dispose(false, false, true);
  65202. _super.prototype.dispose.call(this, doNotRecurse);
  65203. };
  65204. /**
  65205. * Returns a new LineMesh object cloned from the current one.
  65206. */
  65207. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65208. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  65209. };
  65210. return LinesMesh;
  65211. }(BABYLON.Mesh));
  65212. BABYLON.LinesMesh = LinesMesh;
  65213. })(BABYLON || (BABYLON = {}));
  65214. //# sourceMappingURL=babylon.linesMesh.js.map
  65215. var BABYLON;
  65216. (function (BABYLON) {
  65217. /**
  65218. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65219. * The underlying implementation relies on an associative array to ensure the best performances.
  65220. * The value can be anything including 'null' but except 'undefined'
  65221. */
  65222. var StringDictionary = /** @class */ (function () {
  65223. function StringDictionary() {
  65224. this._count = 0;
  65225. this._data = {};
  65226. }
  65227. /**
  65228. * This will clear this dictionary and copy the content from the 'source' one.
  65229. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65230. * @param source the dictionary to take the content from and copy to this dictionary
  65231. */
  65232. StringDictionary.prototype.copyFrom = function (source) {
  65233. var _this = this;
  65234. this.clear();
  65235. source.forEach(function (t, v) { return _this.add(t, v); });
  65236. };
  65237. /**
  65238. * Get a value based from its key
  65239. * @param key the given key to get the matching value from
  65240. * @return the value if found, otherwise undefined is returned
  65241. */
  65242. StringDictionary.prototype.get = function (key) {
  65243. var val = this._data[key];
  65244. if (val !== undefined) {
  65245. return val;
  65246. }
  65247. return undefined;
  65248. };
  65249. /**
  65250. * Get a value from its key or add it if it doesn't exist.
  65251. * This method will ensure you that a given key/data will be present in the dictionary.
  65252. * @param key the given key to get the matching value from
  65253. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65254. * The factory will only be invoked if there's no data for the given key.
  65255. * @return the value corresponding to the key.
  65256. */
  65257. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65258. var val = this.get(key);
  65259. if (val !== undefined) {
  65260. return val;
  65261. }
  65262. val = factory(key);
  65263. if (val) {
  65264. this.add(key, val);
  65265. }
  65266. return val;
  65267. };
  65268. /**
  65269. * Get a value from its key if present in the dictionary otherwise add it
  65270. * @param key the key to get the value from
  65271. * @param val if there's no such key/value pair in the dictionary add it with this value
  65272. * @return the value corresponding to the key
  65273. */
  65274. StringDictionary.prototype.getOrAdd = function (key, val) {
  65275. var curVal = this.get(key);
  65276. if (curVal !== undefined) {
  65277. return curVal;
  65278. }
  65279. this.add(key, val);
  65280. return val;
  65281. };
  65282. /**
  65283. * Check if there's a given key in the dictionary
  65284. * @param key the key to check for
  65285. * @return true if the key is present, false otherwise
  65286. */
  65287. StringDictionary.prototype.contains = function (key) {
  65288. return this._data[key] !== undefined;
  65289. };
  65290. /**
  65291. * Add a new key and its corresponding value
  65292. * @param key the key to add
  65293. * @param value the value corresponding to the key
  65294. * @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
  65295. */
  65296. StringDictionary.prototype.add = function (key, value) {
  65297. if (this._data[key] !== undefined) {
  65298. return false;
  65299. }
  65300. this._data[key] = value;
  65301. ++this._count;
  65302. return true;
  65303. };
  65304. /**
  65305. * Update a specific value associated to a key
  65306. * @param key defines the key to use
  65307. * @param value defines the value to store
  65308. * @returns true if the value was updated (or false if the key was not found)
  65309. */
  65310. StringDictionary.prototype.set = function (key, value) {
  65311. if (this._data[key] === undefined) {
  65312. return false;
  65313. }
  65314. this._data[key] = value;
  65315. return true;
  65316. };
  65317. /**
  65318. * Get the element of the given key and remove it from the dictionary
  65319. * @param key defines the key to search
  65320. * @returns the value associated with the key or null if not found
  65321. */
  65322. StringDictionary.prototype.getAndRemove = function (key) {
  65323. var val = this.get(key);
  65324. if (val !== undefined) {
  65325. delete this._data[key];
  65326. --this._count;
  65327. return val;
  65328. }
  65329. return null;
  65330. };
  65331. /**
  65332. * Remove a key/value from the dictionary.
  65333. * @param key the key to remove
  65334. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65335. */
  65336. StringDictionary.prototype.remove = function (key) {
  65337. if (this.contains(key)) {
  65338. delete this._data[key];
  65339. --this._count;
  65340. return true;
  65341. }
  65342. return false;
  65343. };
  65344. /**
  65345. * Clear the whole content of the dictionary
  65346. */
  65347. StringDictionary.prototype.clear = function () {
  65348. this._data = {};
  65349. this._count = 0;
  65350. };
  65351. Object.defineProperty(StringDictionary.prototype, "count", {
  65352. /**
  65353. * Gets the current count
  65354. */
  65355. get: function () {
  65356. return this._count;
  65357. },
  65358. enumerable: true,
  65359. configurable: true
  65360. });
  65361. /**
  65362. * Execute a callback on each key/val of the dictionary.
  65363. * Note that you can remove any element in this dictionary in the callback implementation
  65364. * @param callback the callback to execute on a given key/value pair
  65365. */
  65366. StringDictionary.prototype.forEach = function (callback) {
  65367. for (var cur in this._data) {
  65368. var val = this._data[cur];
  65369. callback(cur, val);
  65370. }
  65371. };
  65372. /**
  65373. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65374. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65375. * Note that you can remove any element in this dictionary in the callback implementation
  65376. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65377. * @returns the first item
  65378. */
  65379. StringDictionary.prototype.first = function (callback) {
  65380. for (var cur in this._data) {
  65381. var val = this._data[cur];
  65382. var res = callback(cur, val);
  65383. if (res) {
  65384. return res;
  65385. }
  65386. }
  65387. return null;
  65388. };
  65389. return StringDictionary;
  65390. }());
  65391. BABYLON.StringDictionary = StringDictionary;
  65392. })(BABYLON || (BABYLON = {}));
  65393. //# sourceMappingURL=babylon.stringDictionary.js.map
  65394. var BABYLON;
  65395. (function (BABYLON) {
  65396. var Debug;
  65397. (function (Debug) {
  65398. /**
  65399. * Class used to render a debug view of a given skeleton
  65400. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  65401. */
  65402. var SkeletonViewer = /** @class */ (function () {
  65403. /**
  65404. * Creates a new SkeletonViewer
  65405. * @param skeleton defines the skeleton to render
  65406. * @param mesh defines the mesh attached to the skeleton
  65407. * @param scene defines the hosting scene
  65408. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  65409. * @param renderingGroupId defines the rendering group id to use with the viewer
  65410. */
  65411. function SkeletonViewer(
  65412. /** defines the skeleton to render */
  65413. skeleton,
  65414. /** defines the mesh attached to the skeleton */
  65415. mesh, scene,
  65416. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  65417. autoUpdateBonesMatrices,
  65418. /** defines the rendering group id to use with the viewer */
  65419. renderingGroupId) {
  65420. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65421. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65422. this.skeleton = skeleton;
  65423. this.mesh = mesh;
  65424. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65425. this.renderingGroupId = renderingGroupId;
  65426. /** Gets or sets the color used to render the skeleton */
  65427. this.color = BABYLON.Color3.White();
  65428. this._debugLines = new Array();
  65429. this._isEnabled = false;
  65430. this._scene = scene;
  65431. this.update();
  65432. this._renderFunction = this.update.bind(this);
  65433. }
  65434. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65435. get: function () {
  65436. return this._isEnabled;
  65437. },
  65438. /** Gets or sets a boolean indicating if the viewer is enabled */
  65439. set: function (value) {
  65440. if (this._isEnabled === value) {
  65441. return;
  65442. }
  65443. this._isEnabled = value;
  65444. if (value) {
  65445. this._scene.registerBeforeRender(this._renderFunction);
  65446. }
  65447. else {
  65448. this._scene.unregisterBeforeRender(this._renderFunction);
  65449. }
  65450. },
  65451. enumerable: true,
  65452. configurable: true
  65453. });
  65454. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65455. if (x === void 0) { x = 0; }
  65456. if (y === void 0) { y = 0; }
  65457. if (z === void 0) { z = 0; }
  65458. var tmat = BABYLON.Tmp.Matrix[0];
  65459. var parentBone = bone.getParent();
  65460. tmat.copyFrom(bone.getLocalMatrix());
  65461. if (x !== 0 || y !== 0 || z !== 0) {
  65462. var tmat2 = BABYLON.Tmp.Matrix[1];
  65463. BABYLON.Matrix.IdentityToRef(tmat2);
  65464. tmat2.setTranslationFromFloats(x, y, z);
  65465. tmat2.multiplyToRef(tmat, tmat);
  65466. }
  65467. if (parentBone) {
  65468. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65469. }
  65470. tmat.multiplyToRef(meshMat, tmat);
  65471. position.x = tmat.m[12];
  65472. position.y = tmat.m[13];
  65473. position.z = tmat.m[14];
  65474. };
  65475. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65476. var len = bones.length;
  65477. var meshPos = this.mesh.position;
  65478. for (var i = 0; i < len; i++) {
  65479. var bone = bones[i];
  65480. var points = this._debugLines[i];
  65481. if (!points) {
  65482. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65483. this._debugLines[i] = points;
  65484. }
  65485. this._getBonePosition(points[0], bone, meshMat);
  65486. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65487. points[0].subtractInPlace(meshPos);
  65488. points[1].subtractInPlace(meshPos);
  65489. }
  65490. };
  65491. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65492. var len = bones.length;
  65493. var boneNum = 0;
  65494. var meshPos = this.mesh.position;
  65495. for (var i = len - 1; i >= 0; i--) {
  65496. var childBone = bones[i];
  65497. var parentBone = childBone.getParent();
  65498. if (!parentBone) {
  65499. continue;
  65500. }
  65501. var points = this._debugLines[boneNum];
  65502. if (!points) {
  65503. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65504. this._debugLines[boneNum] = points;
  65505. }
  65506. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65507. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65508. points[0].subtractInPlace(meshPos);
  65509. points[1].subtractInPlace(meshPos);
  65510. boneNum++;
  65511. }
  65512. };
  65513. /** Update the viewer to sync with current skeleton state */
  65514. SkeletonViewer.prototype.update = function () {
  65515. if (this.autoUpdateBonesMatrices) {
  65516. this.skeleton.computeAbsoluteTransforms();
  65517. }
  65518. if (this.skeleton.bones[0].length === undefined) {
  65519. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65520. }
  65521. else {
  65522. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65523. }
  65524. if (!this._debugMesh) {
  65525. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  65526. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65527. }
  65528. else {
  65529. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  65530. }
  65531. this._debugMesh.position.copyFrom(this.mesh.position);
  65532. this._debugMesh.color = this.color;
  65533. };
  65534. /** Release associated resources */
  65535. SkeletonViewer.prototype.dispose = function () {
  65536. if (this._debugMesh) {
  65537. this.isEnabled = false;
  65538. this._debugMesh.dispose();
  65539. this._debugMesh = null;
  65540. }
  65541. };
  65542. return SkeletonViewer;
  65543. }());
  65544. Debug.SkeletonViewer = SkeletonViewer;
  65545. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65546. })(BABYLON || (BABYLON = {}));
  65547. //# sourceMappingURL=babylon.skeletonViewer.js.map
  65548. /**
  65549. * Module Debug contains the (visual) components to debug a scene correctly
  65550. */
  65551. var BABYLON;
  65552. (function (BABYLON) {
  65553. var Debug;
  65554. (function (Debug) {
  65555. /**
  65556. * The Axes viewer will show 3 axes in a specific point in space
  65557. */
  65558. var AxesViewer = /** @class */ (function () {
  65559. /**
  65560. * Creates a new AxesViewer
  65561. * @param scene defines the hosting scene
  65562. * @param scaleLines defines a number used to scale line length (1 by default)
  65563. */
  65564. function AxesViewer(scene, scaleLines) {
  65565. if (scaleLines === void 0) { scaleLines = 1; }
  65566. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65567. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65568. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65569. /**
  65570. * Gets or sets a number used to scale line length
  65571. */
  65572. this.scaleLines = 1;
  65573. this.scaleLines = scaleLines;
  65574. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65575. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65576. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65577. this._xmesh.renderingGroupId = 2;
  65578. this._ymesh.renderingGroupId = 2;
  65579. this._zmesh.renderingGroupId = 2;
  65580. this._xmesh.material.checkReadyOnlyOnce = true;
  65581. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65582. this._ymesh.material.checkReadyOnlyOnce = true;
  65583. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65584. this._zmesh.material.checkReadyOnlyOnce = true;
  65585. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65586. this.scene = scene;
  65587. }
  65588. /**
  65589. * Force the viewer to update
  65590. * @param position defines the position of the viewer
  65591. * @param xaxis defines the x axis of the viewer
  65592. * @param yaxis defines the y axis of the viewer
  65593. * @param zaxis defines the z axis of the viewer
  65594. */
  65595. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65596. var scaleLines = this.scaleLines;
  65597. if (this._xmesh) {
  65598. this._xmesh.position.copyFrom(position);
  65599. }
  65600. if (this._ymesh) {
  65601. this._ymesh.position.copyFrom(position);
  65602. }
  65603. if (this._zmesh) {
  65604. this._zmesh.position.copyFrom(position);
  65605. }
  65606. var point2 = this._xline[1];
  65607. point2.x = xaxis.x * scaleLines;
  65608. point2.y = xaxis.y * scaleLines;
  65609. point2.z = xaxis.z * scaleLines;
  65610. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  65611. point2 = this._yline[1];
  65612. point2.x = yaxis.x * scaleLines;
  65613. point2.y = yaxis.y * scaleLines;
  65614. point2.z = yaxis.z * scaleLines;
  65615. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  65616. point2 = this._zline[1];
  65617. point2.x = zaxis.x * scaleLines;
  65618. point2.y = zaxis.y * scaleLines;
  65619. point2.z = zaxis.z * scaleLines;
  65620. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  65621. };
  65622. /** Releases resources */
  65623. AxesViewer.prototype.dispose = function () {
  65624. if (this._xmesh) {
  65625. this._xmesh.dispose();
  65626. }
  65627. if (this._ymesh) {
  65628. this._ymesh.dispose();
  65629. }
  65630. if (this._zmesh) {
  65631. this._zmesh.dispose();
  65632. }
  65633. this._xmesh = null;
  65634. this._ymesh = null;
  65635. this._zmesh = null;
  65636. this.scene = null;
  65637. };
  65638. return AxesViewer;
  65639. }());
  65640. Debug.AxesViewer = AxesViewer;
  65641. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65642. })(BABYLON || (BABYLON = {}));
  65643. //# sourceMappingURL=babylon.axesViewer.js.map
  65644. var BABYLON;
  65645. (function (BABYLON) {
  65646. var Debug;
  65647. (function (Debug) {
  65648. /**
  65649. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  65650. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  65651. */
  65652. var BoneAxesViewer = /** @class */ (function (_super) {
  65653. __extends(BoneAxesViewer, _super);
  65654. /**
  65655. * Creates a new BoneAxesViewer
  65656. * @param scene defines the hosting scene
  65657. * @param bone defines the target bone
  65658. * @param mesh defines the target mesh
  65659. * @param scaleLines defines a scaling factor for line length (1 by default)
  65660. */
  65661. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  65662. if (scaleLines === void 0) { scaleLines = 1; }
  65663. var _this = _super.call(this, scene, scaleLines) || this;
  65664. /** Gets current position */
  65665. _this.pos = BABYLON.Vector3.Zero();
  65666. /** Gets direction of X axis */
  65667. _this.xaxis = BABYLON.Vector3.Zero();
  65668. /** Gets direction of Y axis */
  65669. _this.yaxis = BABYLON.Vector3.Zero();
  65670. /** Gets direction of Z axis */
  65671. _this.zaxis = BABYLON.Vector3.Zero();
  65672. _this.mesh = mesh;
  65673. _this.bone = bone;
  65674. return _this;
  65675. }
  65676. /**
  65677. * Force the viewer to update
  65678. */
  65679. BoneAxesViewer.prototype.update = function () {
  65680. if (!this.mesh || !this.bone) {
  65681. return;
  65682. }
  65683. var bone = this.bone;
  65684. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  65685. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  65686. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  65687. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  65688. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  65689. };
  65690. /** Releases resources */
  65691. BoneAxesViewer.prototype.dispose = function () {
  65692. if (this.mesh) {
  65693. this.mesh = null;
  65694. this.bone = null;
  65695. _super.prototype.dispose.call(this);
  65696. }
  65697. };
  65698. return BoneAxesViewer;
  65699. }(Debug.AxesViewer));
  65700. Debug.BoneAxesViewer = BoneAxesViewer;
  65701. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65702. })(BABYLON || (BABYLON = {}));
  65703. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  65704. var BABYLON;
  65705. (function (BABYLON) {
  65706. /**
  65707. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65708. * in order to better appreciate the issue one might have.
  65709. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65710. */
  65711. var RayHelper = /** @class */ (function () {
  65712. /**
  65713. * Instantiate a new ray helper.
  65714. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65715. * in order to better appreciate the issue one might have.
  65716. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65717. * @param ray Defines the ray we are currently tryin to visualize
  65718. */
  65719. function RayHelper(ray) {
  65720. this.ray = ray;
  65721. }
  65722. /**
  65723. * Helper function to create a colored helper in a scene in one line.
  65724. * @param ray Defines the ray we are currently tryin to visualize
  65725. * @param scene Defines the scene the ray is used in
  65726. * @param color Defines the color we want to see the ray in
  65727. * @returns The newly created ray helper.
  65728. */
  65729. RayHelper.CreateAndShow = function (ray, scene, color) {
  65730. var helper = new RayHelper(ray);
  65731. helper.show(scene, color);
  65732. return helper;
  65733. };
  65734. /**
  65735. * Shows the ray we are willing to debug.
  65736. * @param scene Defines the scene the ray needs to be rendered in
  65737. * @param color Defines the color the ray needs to be rendered in
  65738. */
  65739. RayHelper.prototype.show = function (scene, color) {
  65740. if (!this._renderFunction && this.ray) {
  65741. var ray = this.ray;
  65742. this._renderFunction = this._render.bind(this);
  65743. this._scene = scene;
  65744. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  65745. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  65746. if (this._renderFunction) {
  65747. this._scene.registerBeforeRender(this._renderFunction);
  65748. }
  65749. }
  65750. if (color && this._renderLine) {
  65751. this._renderLine.color.copyFrom(color);
  65752. }
  65753. };
  65754. /**
  65755. * Hides the ray we are debugging.
  65756. */
  65757. RayHelper.prototype.hide = function () {
  65758. if (this._renderFunction && this._scene) {
  65759. this._scene.unregisterBeforeRender(this._renderFunction);
  65760. this._scene = null;
  65761. this._renderFunction = null;
  65762. if (this._renderLine) {
  65763. this._renderLine.dispose();
  65764. this._renderLine = null;
  65765. }
  65766. this._renderPoints = [];
  65767. }
  65768. };
  65769. RayHelper.prototype._render = function () {
  65770. var ray = this.ray;
  65771. if (!ray) {
  65772. return;
  65773. }
  65774. var point = this._renderPoints[1];
  65775. var len = Math.min(ray.length, 1000000);
  65776. point.copyFrom(ray.direction);
  65777. point.scaleInPlace(len);
  65778. point.addInPlace(ray.origin);
  65779. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  65780. };
  65781. /**
  65782. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  65783. * @param mesh Defines the mesh we want the helper attached to
  65784. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  65785. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  65786. * @param length Defines the length of the ray
  65787. */
  65788. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  65789. this._attachedToMesh = mesh;
  65790. var ray = this.ray;
  65791. if (!ray) {
  65792. return;
  65793. }
  65794. if (!ray.direction) {
  65795. ray.direction = BABYLON.Vector3.Zero();
  65796. }
  65797. if (!ray.origin) {
  65798. ray.origin = BABYLON.Vector3.Zero();
  65799. }
  65800. if (length) {
  65801. ray.length = length;
  65802. }
  65803. if (!meshSpaceOrigin) {
  65804. meshSpaceOrigin = BABYLON.Vector3.Zero();
  65805. }
  65806. if (!meshSpaceDirection) {
  65807. // -1 so that this will work with Mesh.lookAt
  65808. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  65809. }
  65810. if (!this._meshSpaceDirection) {
  65811. this._meshSpaceDirection = meshSpaceDirection.clone();
  65812. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  65813. }
  65814. else {
  65815. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  65816. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  65817. }
  65818. if (!this._updateToMeshFunction) {
  65819. this._updateToMeshFunction = this._updateToMesh.bind(this);
  65820. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  65821. }
  65822. this._updateToMesh();
  65823. };
  65824. /**
  65825. * Detach the ray helper from the mesh it has previously been attached to.
  65826. */
  65827. RayHelper.prototype.detachFromMesh = function () {
  65828. if (this._attachedToMesh) {
  65829. if (this._updateToMeshFunction) {
  65830. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  65831. }
  65832. this._attachedToMesh = null;
  65833. this._updateToMeshFunction = null;
  65834. }
  65835. };
  65836. RayHelper.prototype._updateToMesh = function () {
  65837. var ray = this.ray;
  65838. if (!this._attachedToMesh || !ray) {
  65839. return;
  65840. }
  65841. if (this._attachedToMesh._isDisposed) {
  65842. this.detachFromMesh();
  65843. return;
  65844. }
  65845. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  65846. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  65847. };
  65848. /**
  65849. * Dispose the helper and release its associated resources.
  65850. */
  65851. RayHelper.prototype.dispose = function () {
  65852. this.hide();
  65853. this.detachFromMesh();
  65854. this.ray = null;
  65855. };
  65856. return RayHelper;
  65857. }());
  65858. BABYLON.RayHelper = RayHelper;
  65859. })(BABYLON || (BABYLON = {}));
  65860. //# sourceMappingURL=babylon.rayHelper.js.map
  65861. var BABYLON;
  65862. (function (BABYLON) {
  65863. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  65864. get: function () {
  65865. if (!this._debugLayer) {
  65866. this._debugLayer = new DebugLayer(this);
  65867. }
  65868. return this._debugLayer;
  65869. },
  65870. enumerable: true,
  65871. configurable: true
  65872. });
  65873. /**
  65874. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65875. * what is happening in your scene
  65876. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65877. */
  65878. var DebugLayer = /** @class */ (function () {
  65879. /**
  65880. * Instantiates a new debug layer.
  65881. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65882. * what is happening in your scene
  65883. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65884. * @param scene Defines the scene to inspect
  65885. */
  65886. function DebugLayer(scene) {
  65887. var _this = this;
  65888. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65889. /**
  65890. * Observable triggered when a property is changed through the inspector.
  65891. */
  65892. this.onPropertyChangedObservable = new BABYLON.Observable();
  65893. this._scene = scene;
  65894. this._scene.onDisposeObservable.add(function () {
  65895. // Debug layer
  65896. if (_this._scene._debugLayer) {
  65897. _this._scene._debugLayer.hide();
  65898. }
  65899. });
  65900. }
  65901. /** Creates the inspector window. */
  65902. DebugLayer.prototype._createInspector = function (config) {
  65903. if (config === void 0) { config = {}; }
  65904. var popup = config.popup || false;
  65905. var initialTab = config.initialTab || 0;
  65906. var parentElement = config.parentElement || null;
  65907. if (!this._inspector) {
  65908. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65909. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  65910. } // else nothing to do as instance is already created
  65911. };
  65912. /**
  65913. * Get if the inspector is visible or not.
  65914. * @returns true if visible otherwise, false
  65915. */
  65916. DebugLayer.prototype.isVisible = function () {
  65917. if (!this._inspector) {
  65918. return false;
  65919. }
  65920. return true;
  65921. };
  65922. /**
  65923. * Hide the inspector and close its window.
  65924. */
  65925. DebugLayer.prototype.hide = function () {
  65926. if (this._inspector) {
  65927. try {
  65928. this._inspector.dispose();
  65929. }
  65930. catch (e) {
  65931. // If the inspector has been removed directly from the inspector tool
  65932. }
  65933. this.onPropertyChangedObservable.clear();
  65934. this._inspector = null;
  65935. }
  65936. };
  65937. /**
  65938. *
  65939. * Launch the debugLayer.
  65940. *
  65941. * initialTab:
  65942. * | Value | Tab Name |
  65943. * | --- | --- |
  65944. * | 0 | Scene |
  65945. * | 1 | Console |
  65946. * | 2 | Stats |
  65947. * | 3 | Textures |
  65948. * | 4 | Mesh |
  65949. * | 5 | Light |
  65950. * | 6 | Material |
  65951. * | 7 | GLTF |
  65952. * | 8 | GUI |
  65953. * | 9 | Physics |
  65954. * | 10 | Camera |
  65955. * | 11 | Audio |
  65956. *
  65957. * @param config Define the configuration of the inspector
  65958. */
  65959. DebugLayer.prototype.show = function (config) {
  65960. if (config === void 0) { config = {}; }
  65961. if (typeof this.BJSINSPECTOR == 'undefined') {
  65962. // Load inspector and add it to the DOM
  65963. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  65964. }
  65965. else {
  65966. // Otherwise creates the inspector
  65967. this._createInspector(config);
  65968. }
  65969. };
  65970. /**
  65971. * Gets the active tab
  65972. * @return the index of the active tab or -1 if the inspector is hidden
  65973. */
  65974. DebugLayer.prototype.getActiveTab = function () {
  65975. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  65976. };
  65977. /**
  65978. * Define the url to get the inspector script from.
  65979. * By default it uses the babylonjs CDN.
  65980. * @ignoreNaming
  65981. */
  65982. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  65983. return DebugLayer;
  65984. }());
  65985. BABYLON.DebugLayer = DebugLayer;
  65986. })(BABYLON || (BABYLON = {}));
  65987. //# sourceMappingURL=babylon.debugLayer.js.map
  65988. var BABYLON;
  65989. (function (BABYLON) {
  65990. var Debug;
  65991. (function (Debug) {
  65992. /**
  65993. * Used to show the physics impostor around the specific mesh
  65994. */
  65995. var PhysicsViewer = /** @class */ (function () {
  65996. /**
  65997. * Creates a new PhysicsViewer
  65998. * @param scene defines the hosting scene
  65999. */
  66000. function PhysicsViewer(scene) {
  66001. /** @hidden */
  66002. this._impostors = [];
  66003. /** @hidden */
  66004. this._meshes = [];
  66005. /** @hidden */
  66006. this._numMeshes = 0;
  66007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66008. var physicEngine = this._scene.getPhysicsEngine();
  66009. if (physicEngine) {
  66010. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  66011. }
  66012. }
  66013. /** @hidden */
  66014. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66015. var plugin = this._physicsEnginePlugin;
  66016. for (var i = 0; i < this._numMeshes; i++) {
  66017. var impostor = this._impostors[i];
  66018. if (!impostor) {
  66019. continue;
  66020. }
  66021. if (impostor.isDisposed) {
  66022. this.hideImpostor(this._impostors[i--]);
  66023. }
  66024. else {
  66025. var mesh = this._meshes[i];
  66026. if (mesh && plugin) {
  66027. plugin.syncMeshWithImpostor(mesh, impostor);
  66028. }
  66029. }
  66030. }
  66031. };
  66032. /**
  66033. * Renders a specified physic impostor
  66034. * @param impostor defines the impostor to render
  66035. */
  66036. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66037. if (!this._scene) {
  66038. return;
  66039. }
  66040. for (var i = 0; i < this._numMeshes; i++) {
  66041. if (this._impostors[i] == impostor) {
  66042. return;
  66043. }
  66044. }
  66045. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66046. if (debugMesh) {
  66047. this._impostors[this._numMeshes] = impostor;
  66048. this._meshes[this._numMeshes] = debugMesh;
  66049. if (this._numMeshes === 0) {
  66050. this._renderFunction = this._updateDebugMeshes.bind(this);
  66051. this._scene.registerBeforeRender(this._renderFunction);
  66052. }
  66053. this._numMeshes++;
  66054. }
  66055. };
  66056. /**
  66057. * Hides a specified physic impostor
  66058. * @param impostor defines the impostor to hide
  66059. */
  66060. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66061. if (!impostor || !this._scene) {
  66062. return;
  66063. }
  66064. var removed = false;
  66065. for (var i = 0; i < this._numMeshes; i++) {
  66066. if (this._impostors[i] == impostor) {
  66067. var mesh = this._meshes[i];
  66068. if (!mesh) {
  66069. continue;
  66070. }
  66071. this._scene.removeMesh(mesh);
  66072. mesh.dispose();
  66073. this._numMeshes--;
  66074. if (this._numMeshes > 0) {
  66075. this._meshes[i] = this._meshes[this._numMeshes];
  66076. this._impostors[i] = this._impostors[this._numMeshes];
  66077. this._meshes[this._numMeshes] = null;
  66078. this._impostors[this._numMeshes] = null;
  66079. }
  66080. else {
  66081. this._meshes[0] = null;
  66082. this._impostors[0] = null;
  66083. }
  66084. removed = true;
  66085. break;
  66086. }
  66087. }
  66088. if (removed && this._numMeshes === 0) {
  66089. this._scene.unregisterBeforeRender(this._renderFunction);
  66090. }
  66091. };
  66092. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66093. if (!this._debugMaterial) {
  66094. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66095. this._debugMaterial.wireframe = true;
  66096. }
  66097. return this._debugMaterial;
  66098. };
  66099. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66100. if (!this._debugBoxMesh) {
  66101. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66102. this._debugBoxMesh.renderingGroupId = 1;
  66103. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66104. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66105. scene.removeMesh(this._debugBoxMesh);
  66106. }
  66107. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66108. };
  66109. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66110. if (!this._debugSphereMesh) {
  66111. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66112. this._debugSphereMesh.renderingGroupId = 1;
  66113. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66114. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66115. scene.removeMesh(this._debugSphereMesh);
  66116. }
  66117. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66118. };
  66119. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66120. var mesh = null;
  66121. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66122. mesh = this._getDebugBoxMesh(scene);
  66123. impostor.getBoxSizeToRef(mesh.scaling);
  66124. }
  66125. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66126. mesh = this._getDebugSphereMesh(scene);
  66127. var radius = impostor.getRadius();
  66128. mesh.scaling.x = radius * 2;
  66129. mesh.scaling.y = radius * 2;
  66130. mesh.scaling.z = radius * 2;
  66131. }
  66132. return mesh;
  66133. };
  66134. /** Releases all resources */
  66135. PhysicsViewer.prototype.dispose = function () {
  66136. for (var i = 0; i < this._numMeshes; i++) {
  66137. this.hideImpostor(this._impostors[i]);
  66138. }
  66139. if (this._debugBoxMesh) {
  66140. this._debugBoxMesh.dispose();
  66141. }
  66142. if (this._debugSphereMesh) {
  66143. this._debugSphereMesh.dispose();
  66144. }
  66145. if (this._debugMaterial) {
  66146. this._debugMaterial.dispose();
  66147. }
  66148. this._impostors.length = 0;
  66149. this._scene = null;
  66150. this._physicsEnginePlugin = null;
  66151. };
  66152. return PhysicsViewer;
  66153. }());
  66154. Debug.PhysicsViewer = PhysicsViewer;
  66155. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66156. })(BABYLON || (BABYLON = {}));
  66157. //# sourceMappingURL=babylon.physicsViewer.js.map
  66158. var BABYLON;
  66159. (function (BABYLON) {
  66160. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  66161. get: function () {
  66162. return this._forceShowBoundingBoxes || false;
  66163. },
  66164. set: function (value) {
  66165. this._forceShowBoundingBoxes = value;
  66166. // Lazyly creates a BB renderer if needed.
  66167. if (value) {
  66168. this.getBoundingBoxRenderer();
  66169. }
  66170. },
  66171. enumerable: true,
  66172. configurable: true
  66173. });
  66174. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  66175. if (!this._boundingBoxRenderer) {
  66176. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  66177. }
  66178. return this._boundingBoxRenderer;
  66179. };
  66180. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  66181. get: function () {
  66182. return this._showBoundingBox || false;
  66183. },
  66184. set: function (value) {
  66185. this._showBoundingBox = value;
  66186. // Lazyly creates a BB renderer if needed.
  66187. if (value) {
  66188. this.getScene().getBoundingBoxRenderer();
  66189. }
  66190. },
  66191. enumerable: true,
  66192. configurable: true
  66193. });
  66194. /**
  66195. * Component responsible of rendering the bounding box of the meshes in a scene.
  66196. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  66197. */
  66198. var BoundingBoxRenderer = /** @class */ (function () {
  66199. /**
  66200. * Instantiates a new bounding box renderer in a scene.
  66201. * @param scene the scene the renderer renders in
  66202. */
  66203. function BoundingBoxRenderer(scene) {
  66204. /**
  66205. * The component name helpfull to identify the component in the list of scene components.
  66206. */
  66207. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  66208. /**
  66209. * Color of the bounding box lines placed in front of an object
  66210. */
  66211. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66212. /**
  66213. * Color of the bounding box lines placed behind an object
  66214. */
  66215. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66216. /**
  66217. * Defines if the renderer should show the back lines or not
  66218. */
  66219. this.showBackLines = true;
  66220. /**
  66221. * @hidden
  66222. */
  66223. this.renderList = new BABYLON.SmartArray(32);
  66224. this._vertexBuffers = {};
  66225. this.scene = scene;
  66226. scene._addComponent(this);
  66227. }
  66228. /**
  66229. * Registers the component in a given scene
  66230. */
  66231. BoundingBoxRenderer.prototype.register = function () {
  66232. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  66233. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  66234. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  66235. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  66236. };
  66237. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  66238. if (mesh.showSubMeshesBoundingBox) {
  66239. var boundingInfo = subMesh.getBoundingInfo();
  66240. if (boundingInfo !== null && boundingInfo !== undefined) {
  66241. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66242. this.renderList.push(boundingInfo.boundingBox);
  66243. }
  66244. }
  66245. };
  66246. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  66247. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  66248. var boundingInfo = sourceMesh.getBoundingInfo();
  66249. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66250. this.renderList.push(boundingInfo.boundingBox);
  66251. }
  66252. };
  66253. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66254. if (this._colorShader) {
  66255. return;
  66256. }
  66257. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  66258. attributes: [BABYLON.VertexBuffer.PositionKind],
  66259. uniforms: ["world", "viewProjection", "color"]
  66260. });
  66261. var engine = this.scene.getEngine();
  66262. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66264. this._createIndexBuffer();
  66265. };
  66266. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66267. var engine = this.scene.getEngine();
  66268. 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]);
  66269. };
  66270. /**
  66271. * Rebuilds the elements related to this component in case of
  66272. * context lost for instance.
  66273. */
  66274. BoundingBoxRenderer.prototype.rebuild = function () {
  66275. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66276. if (vb) {
  66277. vb._rebuild();
  66278. }
  66279. this._createIndexBuffer();
  66280. };
  66281. /**
  66282. * @hidden
  66283. */
  66284. BoundingBoxRenderer.prototype.reset = function () {
  66285. this.renderList.reset();
  66286. };
  66287. /**
  66288. * Render the bounding boxes of a specific rendering group
  66289. * @param renderingGroupId defines the rendering group to render
  66290. */
  66291. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  66292. if (this.renderList.length === 0) {
  66293. return;
  66294. }
  66295. this._prepareRessources();
  66296. if (!this._colorShader.isReady()) {
  66297. return;
  66298. }
  66299. var engine = this.scene.getEngine();
  66300. engine.setDepthWrite(false);
  66301. this._colorShader._preBind();
  66302. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66303. var boundingBox = this.renderList.data[boundingBoxIndex];
  66304. if (boundingBox._tag !== renderingGroupId) {
  66305. continue;
  66306. }
  66307. var min = boundingBox.minimum;
  66308. var max = boundingBox.maximum;
  66309. var diff = max.subtract(min);
  66310. var median = min.add(diff.scale(0.5));
  66311. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66312. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66313. .multiply(boundingBox.getWorldMatrix());
  66314. // VBOs
  66315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66316. if (this.showBackLines) {
  66317. // Back
  66318. engine.setDepthFunctionToGreaterOrEqual();
  66319. this.scene.resetCachedMaterial();
  66320. this._colorShader.setColor4("color", this.backColor.toColor4());
  66321. this._colorShader.bind(worldMatrix);
  66322. // Draw order
  66323. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66324. }
  66325. // Front
  66326. engine.setDepthFunctionToLess();
  66327. this.scene.resetCachedMaterial();
  66328. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66329. this._colorShader.bind(worldMatrix);
  66330. // Draw order
  66331. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66332. }
  66333. this._colorShader.unbind();
  66334. engine.setDepthFunctionToLessOrEqual();
  66335. engine.setDepthWrite(true);
  66336. };
  66337. /**
  66338. * In case of occlusion queries, we can render the occlusion bounding box through this method
  66339. * @param mesh Define the mesh to render the occlusion bounding box for
  66340. */
  66341. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66342. this._prepareRessources();
  66343. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  66344. return;
  66345. }
  66346. var engine = this.scene.getEngine();
  66347. engine.setDepthWrite(false);
  66348. engine.setColorWrite(false);
  66349. this._colorShader._preBind();
  66350. var boundingBox = mesh._boundingInfo.boundingBox;
  66351. var min = boundingBox.minimum;
  66352. var max = boundingBox.maximum;
  66353. var diff = max.subtract(min);
  66354. var median = min.add(diff.scale(0.5));
  66355. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66356. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66357. .multiply(boundingBox.getWorldMatrix());
  66358. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66359. engine.setDepthFunctionToLess();
  66360. this.scene.resetCachedMaterial();
  66361. this._colorShader.bind(worldMatrix);
  66362. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66363. this._colorShader.unbind();
  66364. engine.setDepthFunctionToLessOrEqual();
  66365. engine.setDepthWrite(true);
  66366. engine.setColorWrite(true);
  66367. };
  66368. /**
  66369. * Dispose and release the resources attached to this renderer.
  66370. */
  66371. BoundingBoxRenderer.prototype.dispose = function () {
  66372. if (!this._colorShader) {
  66373. return;
  66374. }
  66375. this.renderList.dispose();
  66376. this._colorShader.dispose();
  66377. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66378. if (buffer) {
  66379. buffer.dispose();
  66380. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66381. }
  66382. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  66383. };
  66384. return BoundingBoxRenderer;
  66385. }());
  66386. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66387. })(BABYLON || (BABYLON = {}));
  66388. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66389. var BABYLON;
  66390. (function (BABYLON) {
  66391. BABYLON.Engine.prototype.createTransformFeedback = function () {
  66392. return this._gl.createTransformFeedback();
  66393. };
  66394. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  66395. this._gl.deleteTransformFeedback(value);
  66396. };
  66397. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  66398. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  66399. };
  66400. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  66401. if (usePoints === void 0) { usePoints = true; }
  66402. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  66403. };
  66404. BABYLON.Engine.prototype.endTransformFeedback = function () {
  66405. this._gl.endTransformFeedback();
  66406. };
  66407. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  66408. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  66409. };
  66410. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  66411. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  66412. };
  66413. })(BABYLON || (BABYLON = {}));
  66414. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  66415. var BABYLON;
  66416. (function (BABYLON) {
  66417. /**
  66418. * This represents a GPU particle system in Babylon
  66419. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  66420. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  66421. */
  66422. var GPUParticleSystem = /** @class */ (function (_super) {
  66423. __extends(GPUParticleSystem, _super);
  66424. /**
  66425. * Instantiates a GPU particle system.
  66426. * 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.
  66427. * @param name The name of the particle system
  66428. * @param options The options used to create the system
  66429. * @param scene The scene the particle system belongs to
  66430. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  66431. */
  66432. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  66433. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  66434. var _this = _super.call(this, name) || this;
  66435. /**
  66436. * The layer mask we are rendering the particles through.
  66437. */
  66438. _this.layerMask = 0x0FFFFFFF;
  66439. _this._accumulatedCount = 0;
  66440. _this._targetIndex = 0;
  66441. _this._currentRenderId = -1;
  66442. _this._started = false;
  66443. _this._stopped = false;
  66444. _this._timeDelta = 0;
  66445. _this._actualFrame = 0;
  66446. _this._rawTextureWidth = 256;
  66447. /**
  66448. * An event triggered when the system is disposed.
  66449. */
  66450. _this.onDisposeObservable = new BABYLON.Observable();
  66451. /**
  66452. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  66453. * to override the particles.
  66454. */
  66455. _this.forceDepthWrite = false;
  66456. _this._preWarmDone = false;
  66457. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66458. // Setup the default processing configuration to the scene.
  66459. _this._attachImageProcessingConfiguration(null);
  66460. _this._engine = _this._scene.getEngine();
  66461. if (!options.randomTextureSize) {
  66462. delete options.randomTextureSize;
  66463. }
  66464. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  66465. var optionsAsNumber = options;
  66466. if (isFinite(optionsAsNumber)) {
  66467. fullOptions.capacity = optionsAsNumber;
  66468. }
  66469. _this._capacity = fullOptions.capacity;
  66470. _this._activeCount = fullOptions.capacity;
  66471. _this._currentActiveCount = 0;
  66472. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  66473. _this._scene.particleSystems.push(_this);
  66474. _this._updateEffectOptions = {
  66475. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  66476. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  66477. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  66478. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  66479. uniformBuffersNames: [],
  66480. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  66481. defines: "",
  66482. fallbacks: null,
  66483. onCompiled: null,
  66484. onError: null,
  66485. indexParameters: null,
  66486. maxSimultaneousLights: 0,
  66487. transformFeedbackVaryings: []
  66488. };
  66489. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  66490. // Random data
  66491. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  66492. var d = [];
  66493. for (var i = 0; i < maxTextureSize; ++i) {
  66494. d.push(Math.random());
  66495. d.push(Math.random());
  66496. d.push(Math.random());
  66497. d.push(Math.random());
  66498. }
  66499. _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);
  66500. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66501. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66502. d = [];
  66503. for (var i = 0; i < maxTextureSize; ++i) {
  66504. d.push(Math.random());
  66505. d.push(Math.random());
  66506. d.push(Math.random());
  66507. d.push(Math.random());
  66508. }
  66509. _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);
  66510. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66511. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66512. _this._randomTextureSize = maxTextureSize;
  66513. return _this;
  66514. }
  66515. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  66516. /**
  66517. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  66518. */
  66519. get: function () {
  66520. if (!BABYLON.Engine.LastCreatedEngine) {
  66521. return false;
  66522. }
  66523. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  66524. },
  66525. enumerable: true,
  66526. configurable: true
  66527. });
  66528. /**
  66529. * Gets the maximum number of particles active at the same time.
  66530. * @returns The max number of active particles.
  66531. */
  66532. GPUParticleSystem.prototype.getCapacity = function () {
  66533. return this._capacity;
  66534. };
  66535. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  66536. /**
  66537. * Gets or set the number of active particles
  66538. */
  66539. get: function () {
  66540. return this._activeCount;
  66541. },
  66542. set: function (value) {
  66543. this._activeCount = Math.min(value, this._capacity);
  66544. },
  66545. enumerable: true,
  66546. configurable: true
  66547. });
  66548. /**
  66549. * Is this system ready to be used/rendered
  66550. * @return true if the system is ready
  66551. */
  66552. GPUParticleSystem.prototype.isReady = function () {
  66553. if (!this._updateEffect) {
  66554. this._recreateUpdateEffect();
  66555. this._recreateRenderEffect();
  66556. return false;
  66557. }
  66558. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  66559. return false;
  66560. }
  66561. return true;
  66562. };
  66563. /**
  66564. * Gets if the system has been started. (Note: this will still be true after stop is called)
  66565. * @returns True if it has been started, otherwise false.
  66566. */
  66567. GPUParticleSystem.prototype.isStarted = function () {
  66568. return this._started;
  66569. };
  66570. /**
  66571. * Starts the particle system and begins to emit
  66572. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  66573. */
  66574. GPUParticleSystem.prototype.start = function (delay) {
  66575. var _this = this;
  66576. if (delay === void 0) { delay = this.startDelay; }
  66577. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  66578. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  66579. }
  66580. if (delay) {
  66581. setTimeout(function () {
  66582. _this.start(0);
  66583. }, delay);
  66584. return;
  66585. }
  66586. this._started = true;
  66587. this._stopped = false;
  66588. this._preWarmDone = false;
  66589. // Animations
  66590. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  66591. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  66592. }
  66593. };
  66594. /**
  66595. * Stops the particle system.
  66596. */
  66597. GPUParticleSystem.prototype.stop = function () {
  66598. this._stopped = true;
  66599. };
  66600. /**
  66601. * Remove all active particles
  66602. */
  66603. GPUParticleSystem.prototype.reset = function () {
  66604. this._releaseBuffers();
  66605. this._releaseVAOs();
  66606. this._currentActiveCount = 0;
  66607. this._targetIndex = 0;
  66608. };
  66609. /**
  66610. * Returns the string "GPUParticleSystem"
  66611. * @returns a string containing the class name
  66612. */
  66613. GPUParticleSystem.prototype.getClassName = function () {
  66614. return "GPUParticleSystem";
  66615. };
  66616. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  66617. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  66618. this._releaseBuffers();
  66619. return this;
  66620. };
  66621. /**
  66622. * Adds a new color gradient
  66623. * @param gradient defines the gradient to use (between 0 and 1)
  66624. * @param color1 defines the color to affect to the specified gradient
  66625. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  66626. * @returns the current particle system
  66627. */
  66628. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  66629. if (!this._colorGradients) {
  66630. this._colorGradients = [];
  66631. }
  66632. var colorGradient = new BABYLON.ColorGradient();
  66633. colorGradient.gradient = gradient;
  66634. colorGradient.color1 = color1;
  66635. this._colorGradients.push(colorGradient);
  66636. this._colorGradients.sort(function (a, b) {
  66637. if (a.gradient < b.gradient) {
  66638. return -1;
  66639. }
  66640. else if (a.gradient > b.gradient) {
  66641. return 1;
  66642. }
  66643. return 0;
  66644. });
  66645. if (this._colorGradientsTexture) {
  66646. this._colorGradientsTexture.dispose();
  66647. this._colorGradientsTexture = null;
  66648. }
  66649. this._releaseBuffers();
  66650. return this;
  66651. };
  66652. /**
  66653. * Remove a specific color gradient
  66654. * @param gradient defines the gradient to remove
  66655. * @returns the current particle system
  66656. */
  66657. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  66658. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  66659. this._colorGradientsTexture = null;
  66660. return this;
  66661. };
  66662. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  66663. var valueGradient = new BABYLON.FactorGradient();
  66664. valueGradient.gradient = gradient;
  66665. valueGradient.factor1 = factor;
  66666. factorGradients.push(valueGradient);
  66667. factorGradients.sort(function (a, b) {
  66668. if (a.gradient < b.gradient) {
  66669. return -1;
  66670. }
  66671. else if (a.gradient > b.gradient) {
  66672. return 1;
  66673. }
  66674. return 0;
  66675. });
  66676. this._releaseBuffers();
  66677. };
  66678. /**
  66679. * Adds a new size gradient
  66680. * @param gradient defines the gradient to use (between 0 and 1)
  66681. * @param factor defines the size factor to affect to the specified gradient
  66682. * @returns the current particle system
  66683. */
  66684. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  66685. if (!this._sizeGradients) {
  66686. this._sizeGradients = [];
  66687. }
  66688. this._addFactorGradient(this._sizeGradients, gradient, factor);
  66689. if (this._sizeGradientsTexture) {
  66690. this._sizeGradientsTexture.dispose();
  66691. this._sizeGradientsTexture = null;
  66692. }
  66693. this._releaseBuffers();
  66694. return this;
  66695. };
  66696. /**
  66697. * Remove a specific size gradient
  66698. * @param gradient defines the gradient to remove
  66699. * @returns the current particle system
  66700. */
  66701. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  66702. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  66703. this._sizeGradientsTexture = null;
  66704. return this;
  66705. };
  66706. /**
  66707. * Adds a new angular speed gradient
  66708. * @param gradient defines the gradient to use (between 0 and 1)
  66709. * @param factor defines the angular speed to affect to the specified gradient
  66710. * @returns the current particle system
  66711. */
  66712. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  66713. if (!this._angularSpeedGradients) {
  66714. this._angularSpeedGradients = [];
  66715. }
  66716. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  66717. if (this._angularSpeedGradientsTexture) {
  66718. this._angularSpeedGradientsTexture.dispose();
  66719. this._angularSpeedGradientsTexture = null;
  66720. }
  66721. this._releaseBuffers();
  66722. return this;
  66723. };
  66724. /**
  66725. * Remove a specific angular speed gradient
  66726. * @param gradient defines the gradient to remove
  66727. * @returns the current particle system
  66728. */
  66729. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  66730. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  66731. this._angularSpeedGradientsTexture = null;
  66732. return this;
  66733. };
  66734. /**
  66735. * Adds a new velocity gradient
  66736. * @param gradient defines the gradient to use (between 0 and 1)
  66737. * @param factor defines the velocity to affect to the specified gradient
  66738. * @returns the current particle system
  66739. */
  66740. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  66741. if (!this._velocityGradients) {
  66742. this._velocityGradients = [];
  66743. }
  66744. this._addFactorGradient(this._velocityGradients, gradient, factor);
  66745. if (this._velocityGradientsTexture) {
  66746. this._velocityGradientsTexture.dispose();
  66747. this._velocityGradientsTexture = null;
  66748. }
  66749. this._releaseBuffers();
  66750. return this;
  66751. };
  66752. /**
  66753. * Remove a specific velocity gradient
  66754. * @param gradient defines the gradient to remove
  66755. * @returns the current particle system
  66756. */
  66757. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  66758. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  66759. this._velocityGradientsTexture = null;
  66760. return this;
  66761. };
  66762. /**
  66763. * Adds a new limit velocity gradient
  66764. * @param gradient defines the gradient to use (between 0 and 1)
  66765. * @param factor defines the limit velocity value to affect to the specified gradient
  66766. * @returns the current particle system
  66767. */
  66768. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  66769. if (!this._limitVelocityGradients) {
  66770. this._limitVelocityGradients = [];
  66771. }
  66772. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  66773. if (this._limitVelocityGradientsTexture) {
  66774. this._limitVelocityGradientsTexture.dispose();
  66775. this._limitVelocityGradientsTexture = null;
  66776. }
  66777. this._releaseBuffers();
  66778. return this;
  66779. };
  66780. /**
  66781. * Remove a specific limit velocity gradient
  66782. * @param gradient defines the gradient to remove
  66783. * @returns the current particle system
  66784. */
  66785. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  66786. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  66787. this._limitVelocityGradientsTexture = null;
  66788. return this;
  66789. };
  66790. /**
  66791. * Adds a new drag gradient
  66792. * @param gradient defines the gradient to use (between 0 and 1)
  66793. * @param factor defines the drag value to affect to the specified gradient
  66794. * @returns the current particle system
  66795. */
  66796. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  66797. if (!this._dragGradients) {
  66798. this._dragGradients = [];
  66799. }
  66800. this._addFactorGradient(this._dragGradients, gradient, factor);
  66801. if (this._dragGradientsTexture) {
  66802. this._dragGradientsTexture.dispose();
  66803. this._dragGradientsTexture = null;
  66804. }
  66805. this._releaseBuffers();
  66806. return this;
  66807. };
  66808. /**
  66809. * Remove a specific drag gradient
  66810. * @param gradient defines the gradient to remove
  66811. * @returns the current particle system
  66812. */
  66813. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  66814. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  66815. this._dragGradientsTexture = null;
  66816. return this;
  66817. };
  66818. /**
  66819. * Not supported by GPUParticleSystem
  66820. * @param gradient defines the gradient to use (between 0 and 1)
  66821. * @param factor defines the emit rate value to affect to the specified gradient
  66822. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66823. * @returns the current particle system
  66824. */
  66825. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  66826. // Do nothing as emit rate is not supported by GPUParticleSystem
  66827. return this;
  66828. };
  66829. /**
  66830. * Not supported by GPUParticleSystem
  66831. * @param gradient defines the gradient to remove
  66832. * @returns the current particle system
  66833. */
  66834. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  66835. // Do nothing as emit rate is not supported by GPUParticleSystem
  66836. return this;
  66837. };
  66838. /**
  66839. * Not supported by GPUParticleSystem
  66840. * @param gradient defines the gradient to use (between 0 and 1)
  66841. * @param factor defines the start size value to affect to the specified gradient
  66842. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66843. * @returns the current particle system
  66844. */
  66845. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  66846. // Do nothing as start size is not supported by GPUParticleSystem
  66847. return this;
  66848. };
  66849. /**
  66850. * Not supported by GPUParticleSystem
  66851. * @param gradient defines the gradient to remove
  66852. * @returns the current particle system
  66853. */
  66854. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  66855. // Do nothing as start size is not supported by GPUParticleSystem
  66856. return this;
  66857. };
  66858. /**
  66859. * Not supported by GPUParticleSystem
  66860. * @param gradient defines the gradient to use (between 0 and 1)
  66861. * @param min defines the color remap minimal range
  66862. * @param max defines the color remap maximal range
  66863. * @returns the current particle system
  66864. */
  66865. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  66866. // Do nothing as start size is not supported by GPUParticleSystem
  66867. return this;
  66868. };
  66869. /**
  66870. * Not supported by GPUParticleSystem
  66871. * @param gradient defines the gradient to remove
  66872. * @returns the current particle system
  66873. */
  66874. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  66875. // Do nothing as start size is not supported by GPUParticleSystem
  66876. return this;
  66877. };
  66878. /**
  66879. * Not supported by GPUParticleSystem
  66880. * @param gradient defines the gradient to use (between 0 and 1)
  66881. * @param min defines the alpha remap minimal range
  66882. * @param max defines the alpha remap maximal range
  66883. * @returns the current particle system
  66884. */
  66885. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  66886. // Do nothing as start size is not supported by GPUParticleSystem
  66887. return this;
  66888. };
  66889. /**
  66890. * Not supported by GPUParticleSystem
  66891. * @param gradient defines the gradient to remove
  66892. * @returns the current particle system
  66893. */
  66894. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  66895. // Do nothing as start size is not supported by GPUParticleSystem
  66896. return this;
  66897. };
  66898. /**
  66899. * Not supported by GPUParticleSystem
  66900. * @param gradient defines the gradient to use (between 0 and 1)
  66901. * @param color defines the color to affect to the specified gradient
  66902. * @returns the current particle system
  66903. */
  66904. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  66905. //Not supported by GPUParticleSystem
  66906. return this;
  66907. };
  66908. /**
  66909. * Not supported by GPUParticleSystem
  66910. * @param gradient defines the gradient to remove
  66911. * @returns the current particle system
  66912. */
  66913. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  66914. //Not supported by GPUParticleSystem
  66915. return this;
  66916. };
  66917. /**
  66918. * Not supported by GPUParticleSystem
  66919. * @returns the list of ramp gradients
  66920. */
  66921. GPUParticleSystem.prototype.getRampGradients = function () {
  66922. return null;
  66923. };
  66924. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  66925. /**
  66926. * Not supported by GPUParticleSystem
  66927. * Gets or sets a boolean indicating that ramp gradients must be used
  66928. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  66929. */
  66930. get: function () {
  66931. //Not supported by GPUParticleSystem
  66932. return false;
  66933. },
  66934. set: function (value) {
  66935. //Not supported by GPUParticleSystem
  66936. },
  66937. enumerable: true,
  66938. configurable: true
  66939. });
  66940. /**
  66941. * Not supported by GPUParticleSystem
  66942. * @param gradient defines the gradient to use (between 0 and 1)
  66943. * @param factor defines the life time factor to affect to the specified gradient
  66944. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66945. * @returns the current particle system
  66946. */
  66947. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  66948. //Not supported by GPUParticleSystem
  66949. return this;
  66950. };
  66951. /**
  66952. * Not supported by GPUParticleSystem
  66953. * @param gradient defines the gradient to remove
  66954. * @returns the current particle system
  66955. */
  66956. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  66957. //Not supported by GPUParticleSystem
  66958. return this;
  66959. };
  66960. GPUParticleSystem.prototype._reset = function () {
  66961. this._releaseBuffers();
  66962. };
  66963. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  66964. var updateVertexBuffers = {};
  66965. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  66966. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  66967. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  66968. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  66969. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  66970. var offset = 12;
  66971. if (!this._colorGradientsTexture) {
  66972. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  66973. offset += 4;
  66974. }
  66975. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  66976. offset += 3;
  66977. if (!this._isBillboardBased) {
  66978. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  66979. offset += 3;
  66980. }
  66981. if (this._angularSpeedGradientsTexture) {
  66982. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  66983. offset += 1;
  66984. }
  66985. else {
  66986. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  66987. offset += 2;
  66988. }
  66989. if (this._isAnimationSheetEnabled) {
  66990. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  66991. offset += 1;
  66992. if (this.spriteRandomStartCell) {
  66993. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  66994. offset += 1;
  66995. }
  66996. }
  66997. if (this.noiseTexture) {
  66998. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  66999. offset += 3;
  67000. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  67001. offset += 3;
  67002. }
  67003. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  67004. this._engine.bindArrayBuffer(null);
  67005. return vao;
  67006. };
  67007. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  67008. var renderVertexBuffers = {};
  67009. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  67010. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  67011. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  67012. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  67013. var offset = 12;
  67014. if (!this._colorGradientsTexture) {
  67015. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  67016. offset += 4;
  67017. }
  67018. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  67019. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  67020. }
  67021. offset += 3; // Direction
  67022. if (!this._isBillboardBased) {
  67023. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  67024. offset += 3;
  67025. }
  67026. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  67027. if (this._angularSpeedGradientsTexture) {
  67028. offset++;
  67029. }
  67030. else {
  67031. offset += 2;
  67032. }
  67033. if (this._isAnimationSheetEnabled) {
  67034. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  67035. offset += 1;
  67036. if (this.spriteRandomStartCell) {
  67037. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  67038. offset += 1;
  67039. }
  67040. }
  67041. if (this.noiseTexture) {
  67042. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  67043. offset += 3;
  67044. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  67045. offset += 3;
  67046. }
  67047. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  67048. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  67049. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  67050. this._engine.bindArrayBuffer(null);
  67051. return vao;
  67052. };
  67053. GPUParticleSystem.prototype._initialize = function (force) {
  67054. if (force === void 0) { force = false; }
  67055. if (this._buffer0 && !force) {
  67056. return;
  67057. }
  67058. var engine = this._scene.getEngine();
  67059. var data = new Array();
  67060. this._attributesStrideSize = 21;
  67061. this._targetIndex = 0;
  67062. if (!this.isBillboardBased) {
  67063. this._attributesStrideSize += 3;
  67064. }
  67065. if (this._colorGradientsTexture) {
  67066. this._attributesStrideSize -= 4;
  67067. }
  67068. if (this._angularSpeedGradientsTexture) {
  67069. this._attributesStrideSize -= 1;
  67070. }
  67071. if (this._isAnimationSheetEnabled) {
  67072. this._attributesStrideSize += 1;
  67073. if (this.spriteRandomStartCell) {
  67074. this._attributesStrideSize += 1;
  67075. }
  67076. }
  67077. if (this.noiseTexture) {
  67078. this._attributesStrideSize += 6;
  67079. }
  67080. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67081. // position
  67082. data.push(0.0);
  67083. data.push(0.0);
  67084. data.push(0.0);
  67085. // Age and life
  67086. data.push(0.0); // create the particle as a dead one to create a new one at start
  67087. data.push(0.0);
  67088. // Seed
  67089. data.push(Math.random());
  67090. data.push(Math.random());
  67091. data.push(Math.random());
  67092. data.push(Math.random());
  67093. // Size
  67094. data.push(0.0);
  67095. data.push(0.0);
  67096. data.push(0.0);
  67097. if (!this._colorGradientsTexture) {
  67098. // color
  67099. data.push(0.0);
  67100. data.push(0.0);
  67101. data.push(0.0);
  67102. data.push(0.0);
  67103. }
  67104. // direction
  67105. data.push(0.0);
  67106. data.push(0.0);
  67107. data.push(0.0);
  67108. if (!this.isBillboardBased) {
  67109. // initialDirection
  67110. data.push(0.0);
  67111. data.push(0.0);
  67112. data.push(0.0);
  67113. }
  67114. // angle
  67115. data.push(0.0);
  67116. if (!this._angularSpeedGradientsTexture) {
  67117. data.push(0.0);
  67118. }
  67119. if (this._isAnimationSheetEnabled) {
  67120. data.push(0.0);
  67121. if (this.spriteRandomStartCell) {
  67122. data.push(0.0);
  67123. }
  67124. }
  67125. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  67126. data.push(Math.random());
  67127. data.push(Math.random());
  67128. data.push(Math.random());
  67129. data.push(Math.random());
  67130. data.push(Math.random());
  67131. data.push(Math.random());
  67132. }
  67133. }
  67134. // Sprite data
  67135. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  67136. -0.5, 0.5, 0, 1,
  67137. -0.5, -0.5, 0, 0,
  67138. 0.5, -0.5, 1, 0]);
  67139. // Buffers
  67140. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67141. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67142. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  67143. // Update VAO
  67144. this._updateVAO = [];
  67145. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  67146. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  67147. // Render VAO
  67148. this._renderVAO = [];
  67149. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  67150. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  67151. // Links
  67152. this._sourceBuffer = this._buffer0;
  67153. this._targetBuffer = this._buffer1;
  67154. };
  67155. /** @hidden */
  67156. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  67157. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  67158. if (this._isBillboardBased) {
  67159. defines += "\n#define BILLBOARD";
  67160. }
  67161. if (this._colorGradientsTexture) {
  67162. defines += "\n#define COLORGRADIENTS";
  67163. }
  67164. if (this._sizeGradientsTexture) {
  67165. defines += "\n#define SIZEGRADIENTS";
  67166. }
  67167. if (this._angularSpeedGradientsTexture) {
  67168. defines += "\n#define ANGULARSPEEDGRADIENTS";
  67169. }
  67170. if (this._velocityGradientsTexture) {
  67171. defines += "\n#define VELOCITYGRADIENTS";
  67172. }
  67173. if (this._limitVelocityGradientsTexture) {
  67174. defines += "\n#define LIMITVELOCITYGRADIENTS";
  67175. }
  67176. if (this._dragGradientsTexture) {
  67177. defines += "\n#define DRAGGRADIENTS";
  67178. }
  67179. if (this.isAnimationSheetEnabled) {
  67180. defines += "\n#define ANIMATESHEET";
  67181. if (this.spriteRandomStartCell) {
  67182. defines += "\n#define ANIMATESHEETRANDOMSTART";
  67183. }
  67184. }
  67185. if (this.noiseTexture) {
  67186. defines += "\n#define NOISE";
  67187. }
  67188. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  67189. return;
  67190. }
  67191. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  67192. if (!this._colorGradientsTexture) {
  67193. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  67194. }
  67195. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  67196. if (!this._isBillboardBased) {
  67197. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  67198. }
  67199. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  67200. if (this.isAnimationSheetEnabled) {
  67201. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  67202. if (this.spriteRandomStartCell) {
  67203. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  67204. }
  67205. }
  67206. if (this.noiseTexture) {
  67207. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  67208. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  67209. }
  67210. this._updateEffectOptions.defines = defines;
  67211. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  67212. };
  67213. /** @hidden */
  67214. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  67215. var defines = "";
  67216. if (this._scene.clipPlane) {
  67217. defines = "\n#define CLIPPLANE";
  67218. }
  67219. if (this._scene.clipPlane2) {
  67220. defines = "\n#define CLIPPLANE2";
  67221. }
  67222. if (this._scene.clipPlane3) {
  67223. defines = "\n#define CLIPPLANE3";
  67224. }
  67225. if (this._scene.clipPlane4) {
  67226. defines = "\n#define CLIPPLANE4";
  67227. }
  67228. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  67229. defines = "\n#define BLENDMULTIPLYMODE";
  67230. }
  67231. if (this._isBillboardBased) {
  67232. defines += "\n#define BILLBOARD";
  67233. switch (this.billboardMode) {
  67234. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  67235. defines += "\n#define BILLBOARDY";
  67236. break;
  67237. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  67238. defines += "\n#define BILLBOARDSTRETCHED";
  67239. break;
  67240. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  67241. default:
  67242. break;
  67243. }
  67244. }
  67245. if (this._colorGradientsTexture) {
  67246. defines += "\n#define COLORGRADIENTS";
  67247. }
  67248. if (this.isAnimationSheetEnabled) {
  67249. defines += "\n#define ANIMATESHEET";
  67250. }
  67251. if (this._imageProcessingConfiguration) {
  67252. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  67253. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  67254. }
  67255. if (this._renderEffect && this._renderEffect.defines === defines) {
  67256. return;
  67257. }
  67258. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  67259. var samplers = ["textureSampler", "colorGradientSampler"];
  67260. if (BABYLON.ImageProcessingConfiguration) {
  67261. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  67262. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  67263. }
  67264. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  67265. };
  67266. /**
  67267. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  67268. * @param preWarm defines if we are in the pre-warmimg phase
  67269. */
  67270. GPUParticleSystem.prototype.animate = function (preWarm) {
  67271. if (preWarm === void 0) { preWarm = false; }
  67272. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  67273. this._actualFrame += this._timeDelta;
  67274. if (!this._stopped) {
  67275. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  67276. this.stop();
  67277. }
  67278. }
  67279. };
  67280. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  67281. var texture = this[textureName];
  67282. if (!factorGradients || !factorGradients.length || texture) {
  67283. return;
  67284. }
  67285. var data = new Float32Array(this._rawTextureWidth);
  67286. for (var x = 0; x < this._rawTextureWidth; x++) {
  67287. var ratio = x / this._rawTextureWidth;
  67288. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  67289. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  67290. });
  67291. }
  67292. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67293. };
  67294. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  67295. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  67296. };
  67297. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  67298. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  67299. };
  67300. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  67301. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  67302. };
  67303. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  67304. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  67305. };
  67306. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  67307. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  67308. };
  67309. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  67310. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  67311. return;
  67312. }
  67313. var data = new Uint8Array(this._rawTextureWidth * 4);
  67314. var tmpColor = BABYLON.Tmp.Color4[0];
  67315. for (var x = 0; x < this._rawTextureWidth; x++) {
  67316. var ratio = x / this._rawTextureWidth;
  67317. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  67318. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  67319. data[x * 4] = tmpColor.r * 255;
  67320. data[x * 4 + 1] = tmpColor.g * 255;
  67321. data[x * 4 + 2] = tmpColor.b * 255;
  67322. data[x * 4 + 3] = tmpColor.a * 255;
  67323. });
  67324. }
  67325. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67326. };
  67327. /**
  67328. * Renders the particle system in its current state
  67329. * @param preWarm defines if the system should only update the particles but not render them
  67330. * @returns the current number of particles
  67331. */
  67332. GPUParticleSystem.prototype.render = function (preWarm) {
  67333. if (preWarm === void 0) { preWarm = false; }
  67334. if (!this._started) {
  67335. return 0;
  67336. }
  67337. this._createColorGradientTexture();
  67338. this._createSizeGradientTexture();
  67339. this._createAngularSpeedGradientTexture();
  67340. this._createVelocityGradientTexture();
  67341. this._createLimitVelocityGradientTexture();
  67342. this._createDragGradientTexture();
  67343. this._recreateUpdateEffect();
  67344. this._recreateRenderEffect();
  67345. if (!this.isReady()) {
  67346. return 0;
  67347. }
  67348. if (!preWarm) {
  67349. if (!this._preWarmDone && this.preWarmCycles) {
  67350. for (var index = 0; index < this.preWarmCycles; index++) {
  67351. this.animate(true);
  67352. this.render(true);
  67353. }
  67354. this._preWarmDone = true;
  67355. }
  67356. if (this._currentRenderId === this._scene.getFrameId()) {
  67357. return 0;
  67358. }
  67359. this._currentRenderId = this._scene.getFrameId();
  67360. }
  67361. // Get everything ready to render
  67362. this._initialize();
  67363. this._accumulatedCount += this.emitRate * this._timeDelta;
  67364. if (this._accumulatedCount > 1) {
  67365. var intPart = this._accumulatedCount | 0;
  67366. this._accumulatedCount -= intPart;
  67367. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  67368. }
  67369. if (!this._currentActiveCount) {
  67370. return 0;
  67371. }
  67372. // Enable update effect
  67373. this._engine.enableEffect(this._updateEffect);
  67374. this._engine.setState(false);
  67375. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  67376. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  67377. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  67378. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  67379. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  67380. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  67381. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  67382. if (!this._colorGradientsTexture) {
  67383. this._updateEffect.setDirectColor4("color1", this.color1);
  67384. this._updateEffect.setDirectColor4("color2", this.color2);
  67385. }
  67386. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  67387. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  67388. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  67389. this._updateEffect.setVector3("gravity", this.gravity);
  67390. if (this._sizeGradientsTexture) {
  67391. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  67392. }
  67393. if (this._angularSpeedGradientsTexture) {
  67394. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  67395. }
  67396. if (this._velocityGradientsTexture) {
  67397. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  67398. }
  67399. if (this._limitVelocityGradientsTexture) {
  67400. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  67401. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  67402. }
  67403. if (this._dragGradientsTexture) {
  67404. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  67405. }
  67406. if (this.particleEmitterType) {
  67407. this.particleEmitterType.applyToShader(this._updateEffect);
  67408. }
  67409. if (this._isAnimationSheetEnabled) {
  67410. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  67411. }
  67412. if (this.noiseTexture) {
  67413. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  67414. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  67415. }
  67416. var emitterWM;
  67417. if (this.emitter.position) {
  67418. var emitterMesh = this.emitter;
  67419. emitterWM = emitterMesh.getWorldMatrix();
  67420. }
  67421. else {
  67422. var emitterPosition = this.emitter;
  67423. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  67424. }
  67425. this._updateEffect.setMatrix("emitterWM", emitterWM);
  67426. // Bind source VAO
  67427. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  67428. // Update
  67429. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  67430. this._engine.setRasterizerState(false);
  67431. this._engine.beginTransformFeedback(true);
  67432. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  67433. this._engine.endTransformFeedback();
  67434. this._engine.setRasterizerState(true);
  67435. this._engine.bindTransformFeedbackBuffer(null);
  67436. if (!preWarm) {
  67437. // Enable render effect
  67438. this._engine.enableEffect(this._renderEffect);
  67439. var viewMatrix = this._scene.getViewMatrix();
  67440. this._renderEffect.setMatrix("view", viewMatrix);
  67441. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  67442. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  67443. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  67444. if (this._colorGradientsTexture) {
  67445. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  67446. }
  67447. else {
  67448. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  67449. }
  67450. if (this._isAnimationSheetEnabled && this.particleTexture) {
  67451. var baseSize = this.particleTexture.getBaseSize();
  67452. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  67453. }
  67454. if (this._isBillboardBased) {
  67455. var camera = this._scene.activeCamera;
  67456. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  67457. }
  67458. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  67459. var invView = viewMatrix.clone();
  67460. invView.invert();
  67461. this._renderEffect.setMatrix("invView", invView);
  67462. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  67463. }
  67464. // image processing
  67465. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  67466. this._imageProcessingConfiguration.bind(this._renderEffect);
  67467. }
  67468. // Draw order
  67469. switch (this.blendMode) {
  67470. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  67471. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  67472. break;
  67473. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  67474. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  67475. break;
  67476. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  67477. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67478. break;
  67479. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  67480. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  67481. break;
  67482. }
  67483. if (this.forceDepthWrite) {
  67484. this._engine.setDepthWrite(true);
  67485. }
  67486. // Bind source VAO
  67487. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  67488. // Render
  67489. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  67490. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67491. }
  67492. // Switch VAOs
  67493. this._targetIndex++;
  67494. if (this._targetIndex === 2) {
  67495. this._targetIndex = 0;
  67496. }
  67497. // Switch buffers
  67498. var tmpBuffer = this._sourceBuffer;
  67499. this._sourceBuffer = this._targetBuffer;
  67500. this._targetBuffer = tmpBuffer;
  67501. return this._currentActiveCount;
  67502. };
  67503. /**
  67504. * Rebuilds the particle system
  67505. */
  67506. GPUParticleSystem.prototype.rebuild = function () {
  67507. this._initialize(true);
  67508. };
  67509. GPUParticleSystem.prototype._releaseBuffers = function () {
  67510. if (this._buffer0) {
  67511. this._buffer0.dispose();
  67512. this._buffer0 = null;
  67513. }
  67514. if (this._buffer1) {
  67515. this._buffer1.dispose();
  67516. this._buffer1 = null;
  67517. }
  67518. if (this._spriteBuffer) {
  67519. this._spriteBuffer.dispose();
  67520. this._spriteBuffer = null;
  67521. }
  67522. };
  67523. GPUParticleSystem.prototype._releaseVAOs = function () {
  67524. if (!this._updateVAO) {
  67525. return;
  67526. }
  67527. for (var index = 0; index < this._updateVAO.length; index++) {
  67528. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  67529. }
  67530. this._updateVAO = [];
  67531. for (var index = 0; index < this._renderVAO.length; index++) {
  67532. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  67533. }
  67534. this._renderVAO = [];
  67535. };
  67536. /**
  67537. * Disposes the particle system and free the associated resources
  67538. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  67539. */
  67540. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  67541. if (disposeTexture === void 0) { disposeTexture = true; }
  67542. var index = this._scene.particleSystems.indexOf(this);
  67543. if (index > -1) {
  67544. this._scene.particleSystems.splice(index, 1);
  67545. }
  67546. this._releaseBuffers();
  67547. this._releaseVAOs();
  67548. if (this._colorGradientsTexture) {
  67549. this._colorGradientsTexture.dispose();
  67550. this._colorGradientsTexture = null;
  67551. }
  67552. if (this._sizeGradientsTexture) {
  67553. this._sizeGradientsTexture.dispose();
  67554. this._sizeGradientsTexture = null;
  67555. }
  67556. if (this._angularSpeedGradientsTexture) {
  67557. this._angularSpeedGradientsTexture.dispose();
  67558. this._angularSpeedGradientsTexture = null;
  67559. }
  67560. if (this._velocityGradientsTexture) {
  67561. this._velocityGradientsTexture.dispose();
  67562. this._velocityGradientsTexture = null;
  67563. }
  67564. if (this._limitVelocityGradientsTexture) {
  67565. this._limitVelocityGradientsTexture.dispose();
  67566. this._limitVelocityGradientsTexture = null;
  67567. }
  67568. if (this._dragGradientsTexture) {
  67569. this._dragGradientsTexture.dispose();
  67570. this._dragGradientsTexture = null;
  67571. }
  67572. if (this._randomTexture) {
  67573. this._randomTexture.dispose();
  67574. this._randomTexture = null;
  67575. }
  67576. if (this._randomTexture2) {
  67577. this._randomTexture2.dispose();
  67578. this._randomTexture2 = null;
  67579. }
  67580. if (disposeTexture && this.particleTexture) {
  67581. this.particleTexture.dispose();
  67582. this.particleTexture = null;
  67583. }
  67584. if (disposeTexture && this.noiseTexture) {
  67585. this.noiseTexture.dispose();
  67586. this.noiseTexture = null;
  67587. }
  67588. // Callback
  67589. this.onDisposeObservable.notifyObservers(this);
  67590. this.onDisposeObservable.clear();
  67591. };
  67592. /**
  67593. * Clones the particle system.
  67594. * @param name The name of the cloned object
  67595. * @param newEmitter The new emitter to use
  67596. * @returns the cloned particle system
  67597. */
  67598. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  67599. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  67600. BABYLON.Tools.DeepCopy(this, result);
  67601. if (newEmitter === undefined) {
  67602. newEmitter = this.emitter;
  67603. }
  67604. result.emitter = newEmitter;
  67605. if (this.particleTexture) {
  67606. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  67607. }
  67608. return result;
  67609. };
  67610. /**
  67611. * Serializes the particle system to a JSON object.
  67612. * @returns the JSON object
  67613. */
  67614. GPUParticleSystem.prototype.serialize = function () {
  67615. var serializationObject = {};
  67616. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  67617. serializationObject.activeParticleCount = this.activeParticleCount;
  67618. return serializationObject;
  67619. };
  67620. /**
  67621. * Parses a JSON object to create a GPU particle system.
  67622. * @param parsedParticleSystem The JSON object to parse
  67623. * @param scene The scene to create the particle system in
  67624. * @param rootUrl The root url to use to load external dependencies like texture
  67625. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  67626. * @returns the parsed GPU particle system
  67627. */
  67628. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  67629. if (doNotStart === void 0) { doNotStart = false; }
  67630. var name = parsedParticleSystem.name;
  67631. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  67632. if (parsedParticleSystem.activeParticleCount) {
  67633. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  67634. }
  67635. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  67636. // Auto start
  67637. if (parsedParticleSystem.preventAutoStart) {
  67638. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  67639. }
  67640. if (!doNotStart && !particleSystem.preventAutoStart) {
  67641. particleSystem.start();
  67642. }
  67643. return particleSystem;
  67644. };
  67645. return GPUParticleSystem;
  67646. }(BABYLON.BaseParticleSystem));
  67647. BABYLON.GPUParticleSystem = GPUParticleSystem;
  67648. })(BABYLON || (BABYLON = {}));
  67649. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  67650. var BABYLON;
  67651. (function (BABYLON) {
  67652. /**
  67653. * Represents one particle of a solid particle system.
  67654. */
  67655. var SolidParticle = /** @class */ (function () {
  67656. /**
  67657. * Creates a Solid Particle object.
  67658. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  67659. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  67660. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  67661. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  67662. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  67663. * @param shapeId (integer) is the model shape identifier in the SPS.
  67664. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  67665. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  67666. */
  67667. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  67668. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  67669. /**
  67670. * particle global index
  67671. */
  67672. this.idx = 0;
  67673. /**
  67674. * The color of the particle
  67675. */
  67676. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67677. /**
  67678. * The world space position of the particle.
  67679. */
  67680. this.position = BABYLON.Vector3.Zero();
  67681. /**
  67682. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  67683. */
  67684. this.rotation = BABYLON.Vector3.Zero();
  67685. /**
  67686. * The scaling of the particle.
  67687. */
  67688. this.scaling = BABYLON.Vector3.One();
  67689. /**
  67690. * The uvs of the particle.
  67691. */
  67692. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  67693. /**
  67694. * The current speed of the particle.
  67695. */
  67696. this.velocity = BABYLON.Vector3.Zero();
  67697. /**
  67698. * The pivot point in the particle local space.
  67699. */
  67700. this.pivot = BABYLON.Vector3.Zero();
  67701. /**
  67702. * Must the particle be translated from its pivot point in its local space ?
  67703. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  67704. * Default : false
  67705. */
  67706. this.translateFromPivot = false;
  67707. /**
  67708. * Is the particle active or not ?
  67709. */
  67710. this.alive = true;
  67711. /**
  67712. * Is the particle visible or not ?
  67713. */
  67714. this.isVisible = true;
  67715. /**
  67716. * Index of this particle in the global "positions" array (Internal use)
  67717. * @hidden
  67718. */
  67719. this._pos = 0;
  67720. /**
  67721. * @hidden Index of this particle in the global "indices" array (Internal use)
  67722. */
  67723. this._ind = 0;
  67724. /**
  67725. * ModelShape id of this particle
  67726. */
  67727. this.shapeId = 0;
  67728. /**
  67729. * Index of the particle in its shape id (Internal use)
  67730. */
  67731. this.idxInShape = 0;
  67732. /**
  67733. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  67734. */
  67735. this._stillInvisible = false;
  67736. /**
  67737. * @hidden Last computed particle rotation matrix
  67738. */
  67739. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  67740. /**
  67741. * Parent particle Id, if any.
  67742. * Default null.
  67743. */
  67744. this.parentId = null;
  67745. /**
  67746. * @hidden Internal global position in the SPS.
  67747. */
  67748. this._globalPosition = BABYLON.Vector3.Zero();
  67749. this.idx = particleIndex;
  67750. this._pos = positionIndex;
  67751. this._ind = indiceIndex;
  67752. this._model = model;
  67753. this.shapeId = shapeId;
  67754. this.idxInShape = idxInShape;
  67755. this._sps = sps;
  67756. if (modelBoundingInfo) {
  67757. this._modelBoundingInfo = modelBoundingInfo;
  67758. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  67759. }
  67760. }
  67761. Object.defineProperty(SolidParticle.prototype, "scale", {
  67762. /**
  67763. * Legacy support, changed scale to scaling
  67764. */
  67765. get: function () {
  67766. return this.scaling;
  67767. },
  67768. /**
  67769. * Legacy support, changed scale to scaling
  67770. */
  67771. set: function (scale) {
  67772. this.scaling = scale;
  67773. },
  67774. enumerable: true,
  67775. configurable: true
  67776. });
  67777. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  67778. /**
  67779. * Legacy support, changed quaternion to rotationQuaternion
  67780. */
  67781. get: function () {
  67782. return this.rotationQuaternion;
  67783. },
  67784. /**
  67785. * Legacy support, changed quaternion to rotationQuaternion
  67786. */
  67787. set: function (q) {
  67788. this.rotationQuaternion = q;
  67789. },
  67790. enumerable: true,
  67791. configurable: true
  67792. });
  67793. /**
  67794. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  67795. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  67796. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  67797. * @returns true if it intersects
  67798. */
  67799. SolidParticle.prototype.intersectsMesh = function (target) {
  67800. if (!this._boundingInfo || !target._boundingInfo) {
  67801. return false;
  67802. }
  67803. if (this._sps._bSphereOnly) {
  67804. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  67805. }
  67806. return this._boundingInfo.intersects(target._boundingInfo, false);
  67807. };
  67808. /**
  67809. * get the rotation matrix of the particle
  67810. * @hidden
  67811. */
  67812. SolidParticle.prototype.getRotationMatrix = function (m) {
  67813. var quaternion;
  67814. if (this.rotationQuaternion) {
  67815. quaternion = this.rotationQuaternion;
  67816. }
  67817. else {
  67818. quaternion = BABYLON.Tmp.Quaternion[0];
  67819. var rotation = this.rotation;
  67820. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  67821. }
  67822. quaternion.toRotationMatrix(m);
  67823. };
  67824. return SolidParticle;
  67825. }());
  67826. BABYLON.SolidParticle = SolidParticle;
  67827. /**
  67828. * Represents the shape of the model used by one particle of a solid particle system.
  67829. * SPS internal tool, don't use it manually.
  67830. */
  67831. var ModelShape = /** @class */ (function () {
  67832. /**
  67833. * 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.
  67834. * SPS internal tool, don't use it manually.
  67835. * @hidden
  67836. */
  67837. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  67838. /**
  67839. * length of the shape in the model indices array (internal use)
  67840. * @hidden
  67841. */
  67842. this._indicesLength = 0;
  67843. this.shapeID = id;
  67844. this._shape = shape;
  67845. this._indicesLength = indicesLength;
  67846. this._shapeUV = shapeUV;
  67847. this._positionFunction = posFunction;
  67848. this._vertexFunction = vtxFunction;
  67849. }
  67850. return ModelShape;
  67851. }());
  67852. BABYLON.ModelShape = ModelShape;
  67853. /**
  67854. * Represents a Depth Sorted Particle in the solid particle system.
  67855. */
  67856. var DepthSortedParticle = /** @class */ (function () {
  67857. function DepthSortedParticle() {
  67858. /**
  67859. * Index of the particle in the "indices" array
  67860. */
  67861. this.ind = 0;
  67862. /**
  67863. * Length of the particle shape in the "indices" array
  67864. */
  67865. this.indicesLength = 0;
  67866. /**
  67867. * Squared distance from the particle to the camera
  67868. */
  67869. this.sqDistance = 0.0;
  67870. }
  67871. return DepthSortedParticle;
  67872. }());
  67873. BABYLON.DepthSortedParticle = DepthSortedParticle;
  67874. })(BABYLON || (BABYLON = {}));
  67875. //# sourceMappingURL=babylon.solidParticle.js.map
  67876. var BABYLON;
  67877. (function (BABYLON) {
  67878. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  67879. /**
  67880. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  67881. *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.
  67882. * The SPS is also a particle system. It provides some methods to manage the particles.
  67883. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  67884. *
  67885. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  67886. */
  67887. var SolidParticleSystem = /** @class */ (function () {
  67888. /**
  67889. * Creates a SPS (Solid Particle System) object.
  67890. * @param name (String) is the SPS name, this will be the underlying mesh name.
  67891. * @param scene (Scene) is the scene in which the SPS is added.
  67892. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  67893. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  67894. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  67895. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  67896. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  67897. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  67898. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  67899. */
  67900. function SolidParticleSystem(name, scene, options) {
  67901. /**
  67902. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  67903. * Example : var p = SPS.particles[i];
  67904. */
  67905. this.particles = new Array();
  67906. /**
  67907. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  67908. */
  67909. this.nbParticles = 0;
  67910. /**
  67911. * If the particles must ever face the camera (default false). Useful for planar particles.
  67912. */
  67913. this.billboard = false;
  67914. /**
  67915. * Recompute normals when adding a shape
  67916. */
  67917. this.recomputeNormals = true;
  67918. /**
  67919. * This a counter ofr your own usage. It's not set by any SPS functions.
  67920. */
  67921. this.counter = 0;
  67922. /**
  67923. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  67924. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  67925. */
  67926. this.vars = {};
  67927. /**
  67928. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  67929. * @hidden
  67930. */
  67931. this._bSphereOnly = false;
  67932. /**
  67933. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  67934. * @hidden
  67935. */
  67936. this._bSphereRadiusFactor = 1.0;
  67937. this._positions = new Array();
  67938. this._indices = new Array();
  67939. this._normals = new Array();
  67940. this._colors = new Array();
  67941. this._uvs = new Array();
  67942. this._index = 0; // indices index
  67943. this._updatable = true;
  67944. this._pickable = false;
  67945. this._isVisibilityBoxLocked = false;
  67946. this._alwaysVisible = false;
  67947. this._depthSort = false;
  67948. this._shapeCounter = 0;
  67949. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  67950. this._color = new BABYLON.Color4(0, 0, 0, 0);
  67951. this._computeParticleColor = true;
  67952. this._computeParticleTexture = true;
  67953. this._computeParticleRotation = true;
  67954. this._computeParticleVertex = false;
  67955. this._computeBoundingBox = false;
  67956. this._depthSortParticles = true;
  67957. this._mustUnrotateFixedNormals = false;
  67958. this._particlesIntersect = false;
  67959. this._needs32Bits = false;
  67960. this.name = name;
  67961. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67962. this._camera = scene.activeCamera;
  67963. this._pickable = options ? options.isPickable : false;
  67964. this._depthSort = options ? options.enableDepthSort : false;
  67965. this._particlesIntersect = options ? options.particleIntersection : false;
  67966. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  67967. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  67968. if (options && options.updatable !== undefined) {
  67969. this._updatable = options.updatable;
  67970. }
  67971. else {
  67972. this._updatable = true;
  67973. }
  67974. if (this._pickable) {
  67975. this.pickedParticles = [];
  67976. }
  67977. if (this._depthSort) {
  67978. this.depthSortedParticles = [];
  67979. }
  67980. }
  67981. /**
  67982. * Builds the SPS underlying mesh. Returns a standard Mesh.
  67983. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  67984. * @returns the created mesh
  67985. */
  67986. SolidParticleSystem.prototype.buildMesh = function () {
  67987. if (this.nbParticles === 0) {
  67988. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  67989. this.addShape(triangle, 1);
  67990. triangle.dispose();
  67991. }
  67992. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  67993. this._positions32 = new Float32Array(this._positions);
  67994. this._uvs32 = new Float32Array(this._uvs);
  67995. this._colors32 = new Float32Array(this._colors);
  67996. if (this.recomputeNormals) {
  67997. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  67998. }
  67999. this._normals32 = new Float32Array(this._normals);
  68000. this._fixedNormal32 = new Float32Array(this._normals);
  68001. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  68002. this._unrotateFixedNormals();
  68003. }
  68004. var vertexData = new BABYLON.VertexData();
  68005. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  68006. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  68007. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  68008. if (this._uvs32.length > 0) {
  68009. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  68010. }
  68011. if (this._colors32.length > 0) {
  68012. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  68013. }
  68014. var mesh = new BABYLON.Mesh(this.name, this._scene);
  68015. vertexData.applyToMesh(mesh, this._updatable);
  68016. this.mesh = mesh;
  68017. this.mesh.isPickable = this._pickable;
  68018. // free memory
  68019. if (!this._depthSort) {
  68020. this._indices = null;
  68021. }
  68022. this._positions = null;
  68023. this._normals = null;
  68024. this._uvs = null;
  68025. this._colors = null;
  68026. if (!this._updatable) {
  68027. this.particles.length = 0;
  68028. }
  68029. return mesh;
  68030. };
  68031. /**
  68032. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  68033. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  68034. * Thus the particles generated from `digest()` have their property `position` set yet.
  68035. * @param mesh ( Mesh ) is the mesh to be digested
  68036. * @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
  68037. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  68038. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  68039. * @returns the current SPS
  68040. */
  68041. SolidParticleSystem.prototype.digest = function (mesh, options) {
  68042. var size = (options && options.facetNb) || 1;
  68043. var number = (options && options.number) || 0;
  68044. var delta = (options && options.delta) || 0;
  68045. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68046. var meshInd = mesh.getIndices();
  68047. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68048. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68049. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68050. var f = 0; // facet counter
  68051. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  68052. // compute size from number
  68053. if (number) {
  68054. number = (number > totalFacets) ? totalFacets : number;
  68055. size = Math.round(totalFacets / number);
  68056. delta = 0;
  68057. }
  68058. else {
  68059. size = (size > totalFacets) ? totalFacets : size;
  68060. }
  68061. var facetPos = []; // submesh positions
  68062. var facetInd = []; // submesh indices
  68063. var facetUV = []; // submesh UV
  68064. var facetCol = []; // submesh colors
  68065. var barycenter = BABYLON.Vector3.Zero();
  68066. var sizeO = size;
  68067. while (f < totalFacets) {
  68068. size = sizeO + Math.floor((1 + delta) * Math.random());
  68069. if (f > totalFacets - size) {
  68070. size = totalFacets - f;
  68071. }
  68072. // reset temp arrays
  68073. facetPos.length = 0;
  68074. facetInd.length = 0;
  68075. facetUV.length = 0;
  68076. facetCol.length = 0;
  68077. // iterate over "size" facets
  68078. var fi = 0;
  68079. for (var j = f * 3; j < (f + size) * 3; j++) {
  68080. facetInd.push(fi);
  68081. var i = meshInd[j];
  68082. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68083. if (meshUV) {
  68084. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68085. }
  68086. if (meshCol) {
  68087. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68088. }
  68089. fi++;
  68090. }
  68091. // create a model shape for each single particle
  68092. var idx = this.nbParticles;
  68093. var shape = this._posToShape(facetPos);
  68094. var shapeUV = this._uvsToShapeUV(facetUV);
  68095. // compute the barycenter of the shape
  68096. var v;
  68097. for (v = 0; v < shape.length; v++) {
  68098. barycenter.addInPlace(shape[v]);
  68099. }
  68100. barycenter.scaleInPlace(1 / shape.length);
  68101. // shift the shape from its barycenter to the origin
  68102. for (v = 0; v < shape.length; v++) {
  68103. shape[v].subtractInPlace(barycenter);
  68104. }
  68105. var bInfo;
  68106. if (this._particlesIntersect) {
  68107. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  68108. }
  68109. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  68110. // add the particle in the SPS
  68111. var currentPos = this._positions.length;
  68112. var currentInd = this._indices.length;
  68113. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  68114. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  68115. // initialize the particle position
  68116. this.particles[this.nbParticles].position.addInPlace(barycenter);
  68117. this._index += shape.length;
  68118. idx++;
  68119. this.nbParticles++;
  68120. this._shapeCounter++;
  68121. f += size;
  68122. }
  68123. return this;
  68124. };
  68125. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  68126. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  68127. var index = 0;
  68128. var idx = 0;
  68129. var tmpNormal = BABYLON.Tmp.Vector3[0];
  68130. var quaternion = BABYLON.Tmp.Quaternion[0];
  68131. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  68132. for (var p = 0; p < this.particles.length; p++) {
  68133. var particle = this.particles[p];
  68134. var shape = particle._model._shape;
  68135. // computing the inverse of the rotation matrix from the quaternion
  68136. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  68137. if (particle.rotationQuaternion) {
  68138. particle.rotationQuaternion.conjugateToRef(quaternion);
  68139. }
  68140. else {
  68141. var rotation = particle.rotation;
  68142. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68143. quaternion.conjugateInPlace();
  68144. }
  68145. quaternion.toRotationMatrix(invertedRotMatrix);
  68146. for (var pt = 0; pt < shape.length; pt++) {
  68147. idx = index + pt * 3;
  68148. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  68149. tmpNormal.toArray(this._fixedNormal32, idx);
  68150. }
  68151. index = idx + 3;
  68152. }
  68153. };
  68154. //reset copy
  68155. SolidParticleSystem.prototype._resetCopy = function () {
  68156. var copy = this._copy;
  68157. copy.position.setAll(0);
  68158. copy.rotation.setAll(0);
  68159. copy.rotationQuaternion = null;
  68160. copy.scaling.setAll(1);
  68161. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  68162. copy.color = null;
  68163. copy.translateFromPivot = false;
  68164. };
  68165. // _meshBuilder : inserts the shape model in the global SPS mesh
  68166. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  68167. var i;
  68168. var u = 0;
  68169. var c = 0;
  68170. var n = 0;
  68171. this._resetCopy();
  68172. var copy = this._copy;
  68173. if (options && options.positionFunction) { // call to custom positionFunction
  68174. options.positionFunction(copy, idx, idxInShape);
  68175. this._mustUnrotateFixedNormals = true;
  68176. }
  68177. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68178. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68179. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68180. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68181. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68182. copy.getRotationMatrix(rotMatrix);
  68183. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  68184. if (copy.translateFromPivot) {
  68185. pivotBackTranslation.setAll(0.0);
  68186. }
  68187. else {
  68188. pivotBackTranslation.copyFrom(scaledPivot);
  68189. }
  68190. for (i = 0; i < shape.length; i++) {
  68191. tmpVertex.copyFrom(shape[i]);
  68192. if (options && options.vertexFunction) {
  68193. options.vertexFunction(copy, tmpVertex, i);
  68194. }
  68195. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68196. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68197. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  68198. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  68199. if (meshUV) {
  68200. var copyUvs = copy.uvs;
  68201. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  68202. u += 2;
  68203. }
  68204. if (copy.color) {
  68205. this._color = copy.color;
  68206. }
  68207. else {
  68208. var color = this._color;
  68209. if (meshCol && meshCol[c] !== undefined) {
  68210. color.r = meshCol[c];
  68211. color.g = meshCol[c + 1];
  68212. color.b = meshCol[c + 2];
  68213. color.a = meshCol[c + 3];
  68214. }
  68215. else {
  68216. color.r = 1.0;
  68217. color.g = 1.0;
  68218. color.b = 1.0;
  68219. color.a = 1.0;
  68220. }
  68221. }
  68222. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  68223. c += 4;
  68224. if (!this.recomputeNormals && meshNor) {
  68225. tmpVertex.x = meshNor[n];
  68226. tmpVertex.y = meshNor[n + 1];
  68227. tmpVertex.z = meshNor[n + 2];
  68228. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  68229. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  68230. n += 3;
  68231. }
  68232. }
  68233. for (i = 0; i < meshInd.length; i++) {
  68234. var current_ind = p + meshInd[i];
  68235. indices.push(current_ind);
  68236. if (current_ind > 65535) {
  68237. this._needs32Bits = true;
  68238. }
  68239. }
  68240. if (this._pickable) {
  68241. var nbfaces = meshInd.length / 3;
  68242. for (i = 0; i < nbfaces; i++) {
  68243. this.pickedParticles.push({ idx: idx, faceId: i });
  68244. }
  68245. }
  68246. if (this._depthSort) {
  68247. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  68248. }
  68249. return copy;
  68250. };
  68251. // returns a shape array from positions array
  68252. SolidParticleSystem.prototype._posToShape = function (positions) {
  68253. var shape = [];
  68254. for (var i = 0; i < positions.length; i += 3) {
  68255. shape.push(BABYLON.Vector3.FromArray(positions, i));
  68256. }
  68257. return shape;
  68258. };
  68259. // returns a shapeUV array from a Vector4 uvs
  68260. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  68261. var shapeUV = [];
  68262. if (uvs) {
  68263. for (var i = 0; i < uvs.length; i++) {
  68264. shapeUV.push(uvs[i]);
  68265. }
  68266. }
  68267. return shapeUV;
  68268. };
  68269. // adds a new particle object in the particles array
  68270. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  68271. if (bInfo === void 0) { bInfo = null; }
  68272. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  68273. this.particles.push(sp);
  68274. return sp;
  68275. };
  68276. /**
  68277. * Adds some particles to the SPS from the model shape. Returns the shape id.
  68278. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  68279. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  68280. * @param nb (positive integer) the number of particles to be created from this model
  68281. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  68282. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  68283. * @returns the number of shapes in the system
  68284. */
  68285. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  68286. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68287. var meshInd = mesh.getIndices();
  68288. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68289. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68290. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68291. var bbInfo;
  68292. if (this._particlesIntersect) {
  68293. bbInfo = mesh.getBoundingInfo();
  68294. }
  68295. var shape = this._posToShape(meshPos);
  68296. var shapeUV = this._uvsToShapeUV(meshUV);
  68297. var posfunc = options ? options.positionFunction : null;
  68298. var vtxfunc = options ? options.vertexFunction : null;
  68299. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  68300. // particles
  68301. var sp;
  68302. var currentCopy;
  68303. var idx = this.nbParticles;
  68304. for (var i = 0; i < nb; i++) {
  68305. var currentPos = this._positions.length;
  68306. var currentInd = this._indices.length;
  68307. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  68308. if (this._updatable) {
  68309. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  68310. sp.position.copyFrom(currentCopy.position);
  68311. sp.rotation.copyFrom(currentCopy.rotation);
  68312. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  68313. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  68314. }
  68315. if (currentCopy.color && sp.color) {
  68316. sp.color.copyFrom(currentCopy.color);
  68317. }
  68318. sp.scaling.copyFrom(currentCopy.scaling);
  68319. sp.uvs.copyFrom(currentCopy.uvs);
  68320. }
  68321. this._index += shape.length;
  68322. idx++;
  68323. }
  68324. this.nbParticles += nb;
  68325. this._shapeCounter++;
  68326. return this._shapeCounter - 1;
  68327. };
  68328. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  68329. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  68330. this._resetCopy();
  68331. var copy = this._copy;
  68332. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  68333. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  68334. }
  68335. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68336. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68337. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68338. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68339. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68340. copy.getRotationMatrix(rotMatrix);
  68341. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  68342. if (copy.translateFromPivot) {
  68343. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  68344. }
  68345. else {
  68346. pivotBackTranslation.copyFrom(scaledPivot);
  68347. }
  68348. var shape = particle._model._shape;
  68349. for (var pt = 0; pt < shape.length; pt++) {
  68350. tmpVertex.copyFrom(shape[pt]);
  68351. if (particle._model._vertexFunction) {
  68352. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  68353. }
  68354. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68355. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68356. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  68357. }
  68358. particle.position.setAll(0.0);
  68359. particle.rotation.setAll(0.0);
  68360. particle.rotationQuaternion = null;
  68361. particle.scaling.setAll(1.0);
  68362. particle.uvs.setAll(0.0);
  68363. particle.pivot.setAll(0.0);
  68364. particle.translateFromPivot = false;
  68365. particle.parentId = null;
  68366. };
  68367. /**
  68368. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  68369. * @returns the SPS.
  68370. */
  68371. SolidParticleSystem.prototype.rebuildMesh = function () {
  68372. for (var p = 0; p < this.particles.length; p++) {
  68373. this._rebuildParticle(this.particles[p]);
  68374. }
  68375. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  68376. return this;
  68377. };
  68378. /**
  68379. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  68380. * This method calls `updateParticle()` for each particle of the SPS.
  68381. * For an animated SPS, it is usually called within the render loop.
  68382. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  68383. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  68384. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  68385. * @returns the SPS.
  68386. */
  68387. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  68388. if (start === void 0) { start = 0; }
  68389. if (end === void 0) { end = this.nbParticles - 1; }
  68390. if (update === void 0) { update = true; }
  68391. if (!this._updatable) {
  68392. return this;
  68393. }
  68394. // custom beforeUpdate
  68395. this.beforeUpdateParticles(start, end, update);
  68396. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68397. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  68398. var mesh = this.mesh;
  68399. var colors32 = this._colors32;
  68400. var positions32 = this._positions32;
  68401. var normals32 = this._normals32;
  68402. var uvs32 = this._uvs32;
  68403. var indices32 = this._indices32;
  68404. var indices = this._indices;
  68405. var fixedNormal32 = this._fixedNormal32;
  68406. var tempVectors = BABYLON.Tmp.Vector3;
  68407. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  68408. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  68409. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  68410. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  68411. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  68412. var camInvertedPosition = tempVectors[10].setAll(0);
  68413. // cases when the World Matrix is to be computed first
  68414. if (this.billboard || this._depthSort) {
  68415. this.mesh.computeWorldMatrix(true);
  68416. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  68417. }
  68418. // if the particles will always face the camera
  68419. if (this.billboard) {
  68420. // compute the camera position and un-rotate it by the current mesh rotation
  68421. var tmpVertex = tempVectors[0];
  68422. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  68423. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  68424. camAxisZ.normalize();
  68425. // same for camera up vector extracted from the cam view matrix
  68426. var view = this._camera.getViewMatrix(true);
  68427. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  68428. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  68429. camAxisY.normalize();
  68430. camAxisX.normalize();
  68431. }
  68432. // if depthSort, compute the camera global position in the mesh local system
  68433. if (this._depthSort) {
  68434. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  68435. }
  68436. BABYLON.Matrix.IdentityToRef(rotMatrix);
  68437. var idx = 0; // current position index in the global array positions32
  68438. var index = 0; // position start index in the global array positions32 of the current particle
  68439. var colidx = 0; // current color index in the global array colors32
  68440. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  68441. var uvidx = 0; // current uv index in the global array uvs32
  68442. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  68443. var pt = 0; // current index in the particle model shape
  68444. if (this.mesh.isFacetDataEnabled) {
  68445. this._computeBoundingBox = true;
  68446. }
  68447. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  68448. if (this._computeBoundingBox) {
  68449. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  68450. var boundingInfo = this.mesh._boundingInfo;
  68451. if (boundingInfo) {
  68452. minimum.copyFrom(boundingInfo.minimum);
  68453. maximum.copyFrom(boundingInfo.maximum);
  68454. }
  68455. }
  68456. }
  68457. // particle loop
  68458. index = this.particles[start]._pos;
  68459. var vpos = (index / 3) | 0;
  68460. colorIndex = vpos * 4;
  68461. uvIndex = vpos * 2;
  68462. for (var p = start; p <= end; p++) {
  68463. var particle = this.particles[p];
  68464. // call to custom user function to update the particle properties
  68465. this.updateParticle(particle);
  68466. var shape = particle._model._shape;
  68467. var shapeUV = particle._model._shapeUV;
  68468. var particleRotationMatrix = particle._rotationMatrix;
  68469. var particlePosition = particle.position;
  68470. var particleRotation = particle.rotation;
  68471. var particleScaling = particle.scaling;
  68472. var particleGlobalPosition = particle._globalPosition;
  68473. // camera-particle distance for depth sorting
  68474. if (this._depthSort && this._depthSortParticles) {
  68475. var dsp = this.depthSortedParticles[p];
  68476. dsp.ind = particle._ind;
  68477. dsp.indicesLength = particle._model._indicesLength;
  68478. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  68479. }
  68480. // skip the computations for inactive or already invisible particles
  68481. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  68482. // increment indexes for the next particle
  68483. pt = shape.length;
  68484. index += pt * 3;
  68485. colorIndex += pt * 4;
  68486. uvIndex += pt * 2;
  68487. continue;
  68488. }
  68489. if (particle.isVisible) {
  68490. particle._stillInvisible = false; // un-mark permanent invisibility
  68491. var scaledPivot = tempVectors[12];
  68492. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  68493. // particle rotation matrix
  68494. if (this.billboard) {
  68495. particleRotation.x = 0.0;
  68496. particleRotation.y = 0.0;
  68497. }
  68498. if (this._computeParticleRotation || this.billboard) {
  68499. particle.getRotationMatrix(rotMatrix);
  68500. }
  68501. var particleHasParent = (particle.parentId !== null);
  68502. if (particleHasParent) {
  68503. var parent_1 = this.particles[particle.parentId];
  68504. var parentRotationMatrix = parent_1._rotationMatrix;
  68505. var parentGlobalPosition = parent_1._globalPosition;
  68506. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  68507. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  68508. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  68509. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  68510. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  68511. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  68512. if (this._computeParticleRotation || this.billboard) {
  68513. var rotMatrixValues = rotMatrix.m;
  68514. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  68515. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  68516. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  68517. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  68518. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  68519. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  68520. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  68521. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  68522. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  68523. }
  68524. }
  68525. else {
  68526. particleGlobalPosition.x = particlePosition.x;
  68527. particleGlobalPosition.y = particlePosition.y;
  68528. particleGlobalPosition.z = particlePosition.z;
  68529. if (this._computeParticleRotation || this.billboard) {
  68530. var rotMatrixValues = rotMatrix.m;
  68531. particleRotationMatrix[0] = rotMatrixValues[0];
  68532. particleRotationMatrix[1] = rotMatrixValues[1];
  68533. particleRotationMatrix[2] = rotMatrixValues[2];
  68534. particleRotationMatrix[3] = rotMatrixValues[4];
  68535. particleRotationMatrix[4] = rotMatrixValues[5];
  68536. particleRotationMatrix[5] = rotMatrixValues[6];
  68537. particleRotationMatrix[6] = rotMatrixValues[8];
  68538. particleRotationMatrix[7] = rotMatrixValues[9];
  68539. particleRotationMatrix[8] = rotMatrixValues[10];
  68540. }
  68541. }
  68542. var pivotBackTranslation = tempVectors[11];
  68543. if (particle.translateFromPivot) {
  68544. pivotBackTranslation.setAll(0.0);
  68545. }
  68546. else {
  68547. pivotBackTranslation.copyFrom(scaledPivot);
  68548. }
  68549. // particle vertex loop
  68550. for (pt = 0; pt < shape.length; pt++) {
  68551. idx = index + pt * 3;
  68552. colidx = colorIndex + pt * 4;
  68553. uvidx = uvIndex + pt * 2;
  68554. var tmpVertex = tempVectors[0];
  68555. tmpVertex.copyFrom(shape[pt]);
  68556. if (this._computeParticleVertex) {
  68557. this.updateParticleVertex(particle, tmpVertex, pt);
  68558. }
  68559. // positions
  68560. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  68561. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  68562. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  68563. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  68564. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  68565. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  68566. rotatedX += pivotBackTranslation.x;
  68567. rotatedY += pivotBackTranslation.y;
  68568. rotatedZ += pivotBackTranslation.z;
  68569. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68570. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68571. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68572. if (this._computeBoundingBox) {
  68573. minimum.minimizeInPlaceFromFloats(px, py, pz);
  68574. maximum.maximizeInPlaceFromFloats(px, py, pz);
  68575. }
  68576. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  68577. if (!this._computeParticleVertex) {
  68578. var normalx = fixedNormal32[idx];
  68579. var normaly = fixedNormal32[idx + 1];
  68580. var normalz = fixedNormal32[idx + 2];
  68581. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  68582. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  68583. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  68584. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  68585. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  68586. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  68587. }
  68588. if (this._computeParticleColor && particle.color) {
  68589. var color = particle.color;
  68590. var colors32_1 = this._colors32;
  68591. colors32_1[colidx] = color.r;
  68592. colors32_1[colidx + 1] = color.g;
  68593. colors32_1[colidx + 2] = color.b;
  68594. colors32_1[colidx + 3] = color.a;
  68595. }
  68596. if (this._computeParticleTexture) {
  68597. var uvs = particle.uvs;
  68598. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68599. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68600. }
  68601. }
  68602. }
  68603. // particle just set invisible : scaled to zero and positioned at the origin
  68604. else {
  68605. particle._stillInvisible = true; // mark the particle as invisible
  68606. for (pt = 0; pt < shape.length; pt++) {
  68607. idx = index + pt * 3;
  68608. colidx = colorIndex + pt * 4;
  68609. uvidx = uvIndex + pt * 2;
  68610. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  68611. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  68612. if (this._computeParticleColor && particle.color) {
  68613. var color = particle.color;
  68614. colors32[colidx] = color.r;
  68615. colors32[colidx + 1] = color.g;
  68616. colors32[colidx + 2] = color.b;
  68617. colors32[colidx + 3] = color.a;
  68618. }
  68619. if (this._computeParticleTexture) {
  68620. var uvs = particle.uvs;
  68621. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68622. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68623. }
  68624. }
  68625. }
  68626. // if the particle intersections must be computed : update the bbInfo
  68627. if (this._particlesIntersect) {
  68628. var bInfo = particle._boundingInfo;
  68629. var bBox = bInfo.boundingBox;
  68630. var bSphere = bInfo.boundingSphere;
  68631. var modelBoundingInfo = particle._modelBoundingInfo;
  68632. if (!this._bSphereOnly) {
  68633. // place, scale and rotate the particle bbox within the SPS local system, then update it
  68634. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  68635. var tempMin = tempVectors[1];
  68636. var tempMax = tempVectors[2];
  68637. tempMin.setAll(Number.MAX_VALUE);
  68638. tempMax.setAll(-Number.MAX_VALUE);
  68639. for (var b = 0; b < 8; b++) {
  68640. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  68641. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  68642. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  68643. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  68644. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  68645. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  68646. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68647. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68648. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68649. tempMin.minimizeInPlaceFromFloats(x, y, z);
  68650. tempMax.maximizeInPlaceFromFloats(x, y, z);
  68651. }
  68652. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  68653. }
  68654. // place and scale the particle bouding sphere in the SPS local system, then update it
  68655. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  68656. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  68657. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5);
  68658. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  68659. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  68660. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  68661. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  68662. }
  68663. // increment indexes for the next particle
  68664. index = idx + 3;
  68665. colorIndex = colidx + 4;
  68666. uvIndex = uvidx + 2;
  68667. }
  68668. // if the VBO must be updated
  68669. if (update) {
  68670. if (this._computeParticleColor) {
  68671. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  68672. }
  68673. if (this._computeParticleTexture) {
  68674. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  68675. }
  68676. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  68677. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  68678. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  68679. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  68680. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  68681. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  68682. for (var i = 0; i < normals32.length; i++) {
  68683. fixedNormal32[i] = normals32[i];
  68684. }
  68685. }
  68686. if (!mesh.areNormalsFrozen) {
  68687. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  68688. }
  68689. }
  68690. if (this._depthSort && this._depthSortParticles) {
  68691. var depthSortedParticles = this.depthSortedParticles;
  68692. depthSortedParticles.sort(depthSortFunction);
  68693. var dspl = depthSortedParticles.length;
  68694. var sid = 0;
  68695. for (var sorted = 0; sorted < dspl; sorted++) {
  68696. var lind = depthSortedParticles[sorted].indicesLength;
  68697. var sind = depthSortedParticles[sorted].ind;
  68698. for (var i = 0; i < lind; i++) {
  68699. indices32[sid] = indices[sind + i];
  68700. sid++;
  68701. }
  68702. }
  68703. mesh.updateIndices(indices32);
  68704. }
  68705. }
  68706. if (this._computeBoundingBox) {
  68707. if (mesh._boundingInfo) {
  68708. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  68709. }
  68710. else {
  68711. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  68712. }
  68713. }
  68714. this.afterUpdateParticles(start, end, update);
  68715. return this;
  68716. };
  68717. /**
  68718. * Disposes the SPS.
  68719. */
  68720. SolidParticleSystem.prototype.dispose = function () {
  68721. this.mesh.dispose();
  68722. this.vars = null;
  68723. // drop references to internal big arrays for the GC
  68724. this._positions = null;
  68725. this._indices = null;
  68726. this._normals = null;
  68727. this._uvs = null;
  68728. this._colors = null;
  68729. this._indices32 = null;
  68730. this._positions32 = null;
  68731. this._normals32 = null;
  68732. this._fixedNormal32 = null;
  68733. this._uvs32 = null;
  68734. this._colors32 = null;
  68735. this.pickedParticles = null;
  68736. };
  68737. /**
  68738. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  68739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68740. * @returns the SPS.
  68741. */
  68742. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  68743. if (!this._isVisibilityBoxLocked) {
  68744. this.mesh.refreshBoundingInfo();
  68745. }
  68746. return this;
  68747. };
  68748. /**
  68749. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  68750. * @param size the size (float) of the visibility box
  68751. * note : this doesn't lock the SPS mesh bounding box.
  68752. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68753. */
  68754. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  68755. var vis = size / 2;
  68756. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  68757. };
  68758. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  68759. /**
  68760. * Gets whether the SPS as always visible or not
  68761. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68762. */
  68763. get: function () {
  68764. return this._alwaysVisible;
  68765. },
  68766. /**
  68767. * Sets the SPS as always visible or not
  68768. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68769. */
  68770. set: function (val) {
  68771. this._alwaysVisible = val;
  68772. this.mesh.alwaysSelectAsActiveMesh = val;
  68773. },
  68774. enumerable: true,
  68775. configurable: true
  68776. });
  68777. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  68778. /**
  68779. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68780. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68781. */
  68782. get: function () {
  68783. return this._isVisibilityBoxLocked;
  68784. },
  68785. /**
  68786. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68787. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68788. */
  68789. set: function (val) {
  68790. this._isVisibilityBoxLocked = val;
  68791. var boundingInfo = this.mesh.getBoundingInfo();
  68792. boundingInfo.isLocked = val;
  68793. },
  68794. enumerable: true,
  68795. configurable: true
  68796. });
  68797. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  68798. /**
  68799. * Gets if `setParticles()` computes the particle rotations or not.
  68800. * Default value : true. The SPS is faster when it's set to false.
  68801. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68802. */
  68803. get: function () {
  68804. return this._computeParticleRotation;
  68805. },
  68806. /**
  68807. * Tells to `setParticles()` to compute the particle rotations or not.
  68808. * Default value : true. The SPS is faster when it's set to false.
  68809. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68810. */
  68811. set: function (val) {
  68812. this._computeParticleRotation = val;
  68813. },
  68814. enumerable: true,
  68815. configurable: true
  68816. });
  68817. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  68818. /**
  68819. * Gets if `setParticles()` computes the particle colors or not.
  68820. * Default value : true. The SPS is faster when it's set to false.
  68821. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68822. */
  68823. get: function () {
  68824. return this._computeParticleColor;
  68825. },
  68826. /**
  68827. * Tells to `setParticles()` to compute the particle colors or not.
  68828. * Default value : true. The SPS is faster when it's set to false.
  68829. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68830. */
  68831. set: function (val) {
  68832. this._computeParticleColor = val;
  68833. },
  68834. enumerable: true,
  68835. configurable: true
  68836. });
  68837. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  68838. /**
  68839. * Gets if `setParticles()` computes the particle textures or not.
  68840. * Default value : true. The SPS is faster when it's set to false.
  68841. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  68842. */
  68843. get: function () {
  68844. return this._computeParticleTexture;
  68845. },
  68846. set: function (val) {
  68847. this._computeParticleTexture = val;
  68848. },
  68849. enumerable: true,
  68850. configurable: true
  68851. });
  68852. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  68853. /**
  68854. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  68855. * Default value : false. The SPS is faster when it's set to false.
  68856. * Note : the particle custom vertex positions aren't stored values.
  68857. */
  68858. get: function () {
  68859. return this._computeParticleVertex;
  68860. },
  68861. /**
  68862. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  68863. * Default value : false. The SPS is faster when it's set to false.
  68864. * Note : the particle custom vertex positions aren't stored values.
  68865. */
  68866. set: function (val) {
  68867. this._computeParticleVertex = val;
  68868. },
  68869. enumerable: true,
  68870. configurable: true
  68871. });
  68872. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  68873. /**
  68874. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  68875. */
  68876. get: function () {
  68877. return this._computeBoundingBox;
  68878. },
  68879. /**
  68880. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  68881. */
  68882. set: function (val) {
  68883. this._computeBoundingBox = val;
  68884. },
  68885. enumerable: true,
  68886. configurable: true
  68887. });
  68888. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  68889. /**
  68890. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  68891. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68892. * Default : `true`
  68893. */
  68894. get: function () {
  68895. return this._depthSortParticles;
  68896. },
  68897. /**
  68898. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  68899. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68900. * Default : `true`
  68901. */
  68902. set: function (val) {
  68903. this._depthSortParticles = val;
  68904. },
  68905. enumerable: true,
  68906. configurable: true
  68907. });
  68908. // =======================================================================
  68909. // Particle behavior logic
  68910. // these following methods may be overwritten by the user to fit his needs
  68911. /**
  68912. * This function does nothing. It may be overwritten to set all the particle first values.
  68913. * The SPS doesn't call this function, you may have to call it by your own.
  68914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68915. */
  68916. SolidParticleSystem.prototype.initParticles = function () {
  68917. };
  68918. /**
  68919. * This function does nothing. It may be overwritten to recycle a particle.
  68920. * The SPS doesn't call this function, you may have to call it by your own.
  68921. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68922. * @param particle The particle to recycle
  68923. * @returns the recycled particle
  68924. */
  68925. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  68926. return particle;
  68927. };
  68928. /**
  68929. * Updates a particle : this function should be overwritten by the user.
  68930. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  68931. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68932. * @example : just set a particle position or velocity and recycle conditions
  68933. * @param particle The particle to update
  68934. * @returns the updated particle
  68935. */
  68936. SolidParticleSystem.prototype.updateParticle = function (particle) {
  68937. return particle;
  68938. };
  68939. /**
  68940. * Updates a vertex of a particle : it can be overwritten by the user.
  68941. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  68942. * @param particle the current particle
  68943. * @param vertex the current index of the current particle
  68944. * @param pt the index of the current vertex in the particle shape
  68945. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  68946. * @example : just set a vertex particle position
  68947. * @returns the updated vertex
  68948. */
  68949. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  68950. return vertex;
  68951. };
  68952. /**
  68953. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  68954. * This does nothing and may be overwritten by the user.
  68955. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68956. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68957. * @param update the boolean update value actually passed to setParticles()
  68958. */
  68959. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  68960. };
  68961. /**
  68962. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  68963. * This will be passed three parameters.
  68964. * This does nothing and may be overwritten by the user.
  68965. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68966. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68967. * @param update the boolean update value actually passed to setParticles()
  68968. */
  68969. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  68970. };
  68971. return SolidParticleSystem;
  68972. }());
  68973. BABYLON.SolidParticleSystem = SolidParticleSystem;
  68974. })(BABYLON || (BABYLON = {}));
  68975. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  68976. var BABYLON;
  68977. (function (BABYLON) {
  68978. /**
  68979. * Class containing static functions to help procedurally build meshes
  68980. */
  68981. var MeshBuilder = /** @class */ (function () {
  68982. function MeshBuilder() {
  68983. }
  68984. MeshBuilder.updateSideOrientation = function (orientation) {
  68985. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  68986. return BABYLON.Mesh.DOUBLESIDE;
  68987. }
  68988. if (orientation === undefined || orientation === null) {
  68989. return BABYLON.Mesh.FRONTSIDE;
  68990. }
  68991. return orientation;
  68992. };
  68993. /**
  68994. * Creates a box mesh
  68995. * * The parameter `size` sets the size (float) of each box side (default 1)
  68996. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  68997. * * 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)
  68998. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68999. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69000. * * 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
  69001. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69002. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  69003. * @param name defines the name of the mesh
  69004. * @param options defines the options used to create the mesh
  69005. * @param scene defines the hosting scene
  69006. * @returns the box mesh
  69007. */
  69008. MeshBuilder.CreateBox = function (name, options, scene) {
  69009. if (scene === void 0) { scene = null; }
  69010. var box = new BABYLON.Mesh(name, scene);
  69011. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69012. box._originalBuilderSideOrientation = options.sideOrientation;
  69013. var vertexData = BABYLON.VertexData.CreateBox(options);
  69014. vertexData.applyToMesh(box, options.updatable);
  69015. return box;
  69016. };
  69017. /**
  69018. * Creates a sphere mesh
  69019. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  69020. * * 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 of `diameter`)
  69021. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  69022. * * 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
  69023. * * 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)
  69024. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69025. * * 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
  69026. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69027. * @param name defines the name of the mesh
  69028. * @param options defines the options used to create the mesh
  69029. * @param scene defines the hosting scene
  69030. * @returns the sphere mesh
  69031. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  69032. */
  69033. MeshBuilder.CreateSphere = function (name, options, scene) {
  69034. var sphere = new BABYLON.Mesh(name, scene);
  69035. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69036. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69037. var vertexData = BABYLON.VertexData.CreateSphere(options);
  69038. vertexData.applyToMesh(sphere, options.updatable);
  69039. return sphere;
  69040. };
  69041. /**
  69042. * Creates a plane polygonal mesh. By default, this is a disc
  69043. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  69044. * * 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
  69045. * * 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
  69046. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69047. * * 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
  69048. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69049. * @param name defines the name of the mesh
  69050. * @param options defines the options used to create the mesh
  69051. * @param scene defines the hosting scene
  69052. * @returns the plane polygonal mesh
  69053. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69054. */
  69055. MeshBuilder.CreateDisc = function (name, options, scene) {
  69056. if (scene === void 0) { scene = null; }
  69057. var disc = new BABYLON.Mesh(name, scene);
  69058. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69059. disc._originalBuilderSideOrientation = options.sideOrientation;
  69060. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69061. vertexData.applyToMesh(disc, options.updatable);
  69062. return disc;
  69063. };
  69064. /**
  69065. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69066. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69067. * * 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 of `radius`)
  69068. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69069. * * 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
  69070. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69071. * * 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
  69072. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69073. * @param name defines the name of the mesh
  69074. * @param options defines the options used to create the mesh
  69075. * @param scene defines the hosting scene
  69076. * @returns the icosahedron mesh
  69077. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69078. */
  69079. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69080. var sphere = new BABYLON.Mesh(name, scene);
  69081. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69082. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69083. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69084. vertexData.applyToMesh(sphere, options.updatable);
  69085. return sphere;
  69086. };
  69087. /**
  69088. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69089. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69090. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69091. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69092. * * 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
  69093. * * 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
  69094. * * 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
  69095. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69096. * * 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
  69097. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69098. * * 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
  69099. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69100. * * 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
  69101. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69102. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69103. * @param name defines the name of the mesh
  69104. * @param options defines the options used to create the mesh
  69105. * @param scene defines the hosting scene
  69106. * @returns the ribbon mesh
  69107. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  69108. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69109. */
  69110. MeshBuilder.CreateRibbon = function (name, options, scene) {
  69111. if (scene === void 0) { scene = null; }
  69112. var pathArray = options.pathArray;
  69113. var closeArray = options.closeArray;
  69114. var closePath = options.closePath;
  69115. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69116. var instance = options.instance;
  69117. var updatable = options.updatable;
  69118. if (instance) { // existing ribbon instance update
  69119. // positionFunction : ribbon case
  69120. // only pathArray and sideOrientation parameters are taken into account for positions update
  69121. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  69122. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  69123. var positionFunction = function (positions) {
  69124. var minlg = pathArray[0].length;
  69125. var mesh = instance;
  69126. var i = 0;
  69127. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  69128. for (var si = 1; si <= ns; ++si) {
  69129. for (var p = 0; p < pathArray.length; ++p) {
  69130. var path = pathArray[p];
  69131. var l = path.length;
  69132. minlg = (minlg < l) ? minlg : l;
  69133. for (var j = 0; j < minlg; ++j) {
  69134. var pathPoint = path[j];
  69135. positions[i] = pathPoint.x;
  69136. positions[i + 1] = pathPoint.y;
  69137. positions[i + 2] = pathPoint.z;
  69138. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69139. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69140. i += 3;
  69141. }
  69142. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  69143. var pathPoint = path[0];
  69144. positions[i] = pathPoint.x;
  69145. positions[i + 1] = pathPoint.y;
  69146. positions[i + 2] = pathPoint.z;
  69147. i += 3;
  69148. }
  69149. }
  69150. }
  69151. };
  69152. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69153. positionFunction(positions);
  69154. if (instance._boundingInfo) {
  69155. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  69156. }
  69157. else {
  69158. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  69159. }
  69160. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69161. if (options.colors) {
  69162. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69163. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  69164. var color = options.colors[c];
  69165. colors[colorIndex] = color.r;
  69166. colors[colorIndex + 1] = color.g;
  69167. colors[colorIndex + 2] = color.b;
  69168. colors[colorIndex + 3] = color.a;
  69169. }
  69170. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  69171. }
  69172. if (options.uvs) {
  69173. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69174. for (var i = 0; i < options.uvs.length; i++) {
  69175. uvs[i * 2] = options.uvs[i].x;
  69176. uvs[i * 2 + 1] = options.uvs[i].y;
  69177. }
  69178. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  69179. }
  69180. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  69181. var indices = instance.getIndices();
  69182. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69183. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  69184. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  69185. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  69186. var indexFirst = 0;
  69187. var indexLast = 0;
  69188. for (var p = 0; p < pathArray.length; p++) {
  69189. indexFirst = instance._creationDataStorage.idx[p] * 3;
  69190. if (p + 1 < pathArray.length) {
  69191. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  69192. }
  69193. else {
  69194. indexLast = normals.length - 3;
  69195. }
  69196. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  69197. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  69198. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  69199. normals[indexLast] = normals[indexFirst];
  69200. normals[indexLast + 1] = normals[indexFirst + 1];
  69201. normals[indexLast + 2] = normals[indexFirst + 2];
  69202. }
  69203. }
  69204. if (!(instance.areNormalsFrozen)) {
  69205. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  69206. }
  69207. }
  69208. return instance;
  69209. }
  69210. else { // new ribbon creation
  69211. var ribbon = new BABYLON.Mesh(name, scene);
  69212. ribbon._originalBuilderSideOrientation = sideOrientation;
  69213. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  69214. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  69215. if (closePath) {
  69216. ribbon._creationDataStorage.idx = vertexData._idx;
  69217. }
  69218. ribbon._creationDataStorage.closePath = closePath;
  69219. ribbon._creationDataStorage.closeArray = closeArray;
  69220. vertexData.applyToMesh(ribbon, updatable);
  69221. return ribbon;
  69222. }
  69223. };
  69224. /**
  69225. * Creates a cylinder or a cone mesh
  69226. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  69227. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  69228. * * 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.
  69229. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  69230. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  69231. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  69232. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  69233. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  69234. * * 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).
  69235. * * 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
  69236. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  69237. * * 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
  69238. * * 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.
  69239. * * If `enclose` is false, a ring surface is one element.
  69240. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  69241. * * 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
  69242. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69243. * * 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
  69244. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69245. * @param name defines the name of the mesh
  69246. * @param options defines the options used to create the mesh
  69247. * @param scene defines the hosting scene
  69248. * @returns the cylinder mesh
  69249. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  69250. */
  69251. MeshBuilder.CreateCylinder = function (name, options, scene) {
  69252. var cylinder = new BABYLON.Mesh(name, scene);
  69253. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69254. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  69255. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  69256. vertexData.applyToMesh(cylinder, options.updatable);
  69257. return cylinder;
  69258. };
  69259. /**
  69260. * Creates a torus mesh
  69261. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  69262. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  69263. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  69264. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69265. * * 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
  69266. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69267. * @param name defines the name of the mesh
  69268. * @param options defines the options used to create the mesh
  69269. * @param scene defines the hosting scene
  69270. * @returns the torus mesh
  69271. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  69272. */
  69273. MeshBuilder.CreateTorus = function (name, options, scene) {
  69274. var torus = new BABYLON.Mesh(name, scene);
  69275. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69276. torus._originalBuilderSideOrientation = options.sideOrientation;
  69277. var vertexData = BABYLON.VertexData.CreateTorus(options);
  69278. vertexData.applyToMesh(torus, options.updatable);
  69279. return torus;
  69280. };
  69281. /**
  69282. * Creates a torus knot mesh
  69283. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  69284. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  69285. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  69286. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  69287. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69288. * * 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
  69289. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69290. * @param name defines the name of the mesh
  69291. * @param options defines the options used to create the mesh
  69292. * @param scene defines the hosting scene
  69293. * @returns the torus knot mesh
  69294. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  69295. */
  69296. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  69297. var torusKnot = new BABYLON.Mesh(name, scene);
  69298. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69299. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  69300. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  69301. vertexData.applyToMesh(torusKnot, options.updatable);
  69302. return torusKnot;
  69303. };
  69304. /**
  69305. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  69306. * * 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
  69307. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  69308. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  69309. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  69310. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  69311. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  69312. * * 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
  69313. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  69314. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69315. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  69316. * @param name defines the name of the new line system
  69317. * @param options defines the options used to create the line system
  69318. * @param scene defines the hosting scene
  69319. * @returns a new line system mesh
  69320. */
  69321. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  69322. var instance = options.instance;
  69323. var lines = options.lines;
  69324. var colors = options.colors;
  69325. if (instance) { // lines update
  69326. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69327. var vertexColor;
  69328. var lineColors;
  69329. if (colors) {
  69330. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69331. }
  69332. var i = 0;
  69333. var c = 0;
  69334. for (var l = 0; l < lines.length; l++) {
  69335. var points = lines[l];
  69336. for (var p = 0; p < points.length; p++) {
  69337. positions[i] = points[p].x;
  69338. positions[i + 1] = points[p].y;
  69339. positions[i + 2] = points[p].z;
  69340. if (colors && vertexColor) {
  69341. lineColors = colors[l];
  69342. vertexColor[c] = lineColors[p].r;
  69343. vertexColor[c + 1] = lineColors[p].g;
  69344. vertexColor[c + 2] = lineColors[p].b;
  69345. vertexColor[c + 3] = lineColors[p].a;
  69346. c += 4;
  69347. }
  69348. i += 3;
  69349. }
  69350. }
  69351. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69352. if (colors && vertexColor) {
  69353. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  69354. }
  69355. return instance;
  69356. }
  69357. // line system creation
  69358. var useVertexColor = (colors) ? true : false;
  69359. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  69360. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  69361. vertexData.applyToMesh(lineSystem, options.updatable);
  69362. return lineSystem;
  69363. };
  69364. /**
  69365. * Creates a line mesh
  69366. * 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
  69367. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69368. * * The parameter `points` is an array successive Vector3
  69369. * * 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
  69370. * * The optional parameter `colors` is an array of successive Color4, one per line point
  69371. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  69372. * * When updating an instance, remember that only point positions can change, not the number of points
  69373. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69374. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  69375. * @param name defines the name of the new line system
  69376. * @param options defines the options used to create the line system
  69377. * @param scene defines the hosting scene
  69378. * @returns a new line mesh
  69379. */
  69380. MeshBuilder.CreateLines = function (name, options, scene) {
  69381. if (scene === void 0) { scene = null; }
  69382. var colors = (options.colors) ? [options.colors] : null;
  69383. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  69384. return lines;
  69385. };
  69386. /**
  69387. * Creates a dashed line mesh
  69388. * * 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
  69389. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69390. * * The parameter `points` is an array successive Vector3
  69391. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  69392. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  69393. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  69394. * * 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
  69395. * * When updating an instance, remember that only point positions can change, not the number of points
  69396. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69397. * @param name defines the name of the mesh
  69398. * @param options defines the options used to create the mesh
  69399. * @param scene defines the hosting scene
  69400. * @returns the dashed line mesh
  69401. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  69402. */
  69403. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  69404. if (scene === void 0) { scene = null; }
  69405. var points = options.points;
  69406. var instance = options.instance;
  69407. var gapSize = options.gapSize || 1;
  69408. var dashSize = options.dashSize || 3;
  69409. if (instance) { // dashed lines update
  69410. var positionFunction = function (positions) {
  69411. var curvect = BABYLON.Vector3.Zero();
  69412. var nbSeg = positions.length / 6;
  69413. var lg = 0;
  69414. var nb = 0;
  69415. var shft = 0;
  69416. var dashshft = 0;
  69417. var curshft = 0;
  69418. var p = 0;
  69419. var i = 0;
  69420. var j = 0;
  69421. for (i = 0; i < points.length - 1; i++) {
  69422. points[i + 1].subtractToRef(points[i], curvect);
  69423. lg += curvect.length();
  69424. }
  69425. shft = lg / nbSeg;
  69426. var dashSize = instance._creationDataStorage.dashSize;
  69427. var gapSize = instance._creationDataStorage.gapSize;
  69428. dashshft = dashSize * shft / (dashSize + gapSize);
  69429. for (i = 0; i < points.length - 1; i++) {
  69430. points[i + 1].subtractToRef(points[i], curvect);
  69431. nb = Math.floor(curvect.length() / shft);
  69432. curvect.normalize();
  69433. j = 0;
  69434. while (j < nb && p < positions.length) {
  69435. curshft = shft * j;
  69436. positions[p] = points[i].x + curshft * curvect.x;
  69437. positions[p + 1] = points[i].y + curshft * curvect.y;
  69438. positions[p + 2] = points[i].z + curshft * curvect.z;
  69439. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  69440. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  69441. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  69442. p += 6;
  69443. j++;
  69444. }
  69445. }
  69446. while (p < positions.length) {
  69447. positions[p] = points[i].x;
  69448. positions[p + 1] = points[i].y;
  69449. positions[p + 2] = points[i].z;
  69450. p += 3;
  69451. }
  69452. };
  69453. instance.updateMeshPositions(positionFunction, false);
  69454. return instance;
  69455. }
  69456. // dashed lines creation
  69457. var dashedLines = new BABYLON.LinesMesh(name, scene);
  69458. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  69459. vertexData.applyToMesh(dashedLines, options.updatable);
  69460. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  69461. dashedLines._creationDataStorage.dashSize = dashSize;
  69462. dashedLines._creationDataStorage.gapSize = gapSize;
  69463. return dashedLines;
  69464. };
  69465. /**
  69466. * 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.
  69467. * * 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.
  69468. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69469. * * 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.
  69470. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  69471. * * 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
  69472. * * 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
  69473. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  69474. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69475. * * 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
  69476. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  69477. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69478. * @param name defines the name of the mesh
  69479. * @param options defines the options used to create the mesh
  69480. * @param scene defines the hosting scene
  69481. * @returns the extruded shape mesh
  69482. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69483. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69484. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69485. */
  69486. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  69487. if (scene === void 0) { scene = null; }
  69488. var path = options.path;
  69489. var shape = options.shape;
  69490. var scale = options.scale || 1;
  69491. var rotation = options.rotation || 0;
  69492. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69493. var updatable = options.updatable;
  69494. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69495. var instance = options.instance || null;
  69496. var invertUV = options.invertUV || false;
  69497. 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);
  69498. };
  69499. /**
  69500. * Creates an custom extruded shape mesh.
  69501. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  69502. * * 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.
  69503. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69504. * * 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
  69505. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  69506. * * 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
  69507. * * It must returns a float value that will be the scale value applied to the shape on each path point
  69508. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  69509. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  69510. * * 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
  69511. * * 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
  69512. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  69513. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69514. * * 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
  69515. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69516. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69517. * @param name defines the name of the mesh
  69518. * @param options defines the options used to create the mesh
  69519. * @param scene defines the hosting scene
  69520. * @returns the custom extruded shape mesh
  69521. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  69522. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69523. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69524. */
  69525. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  69526. var path = options.path;
  69527. var shape = options.shape;
  69528. var scaleFunction = options.scaleFunction || (function () { return 1; });
  69529. var rotationFunction = options.rotationFunction || (function () { return 0; });
  69530. var ribbonCloseArray = options.ribbonCloseArray || false;
  69531. var ribbonClosePath = options.ribbonClosePath || false;
  69532. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69533. var updatable = options.updatable;
  69534. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69535. var instance = options.instance;
  69536. var invertUV = options.invertUV || false;
  69537. 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);
  69538. };
  69539. /**
  69540. * Creates lathe mesh.
  69541. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  69542. * * 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
  69543. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  69544. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  69545. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  69546. * * 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
  69547. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  69548. * * 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
  69549. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69550. * * 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
  69551. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69552. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69553. * @param name defines the name of the mesh
  69554. * @param options defines the options used to create the mesh
  69555. * @param scene defines the hosting scene
  69556. * @returns the lathe mesh
  69557. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  69558. */
  69559. MeshBuilder.CreateLathe = function (name, options, scene) {
  69560. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  69561. var closed = (options.closed === undefined) ? true : options.closed;
  69562. var shape = options.shape;
  69563. var radius = options.radius || 1;
  69564. var tessellation = options.tessellation || 64;
  69565. var clip = options.clip || 0;
  69566. var updatable = options.updatable;
  69567. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69568. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69569. var pi2 = Math.PI * 2;
  69570. var paths = new Array();
  69571. var invertUV = options.invertUV || false;
  69572. var i = 0;
  69573. var p = 0;
  69574. var step = pi2 / tessellation * arc;
  69575. var rotated;
  69576. var path = new Array();
  69577. for (i = 0; i <= tessellation - clip; i++) {
  69578. var path = [];
  69579. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  69580. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  69581. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  69582. }
  69583. for (p = 0; p < shape.length; p++) {
  69584. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  69585. path.push(rotated);
  69586. }
  69587. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  69588. 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));
  69589. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  69590. }
  69591. paths.push(path);
  69592. }
  69593. // lathe ribbon
  69594. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69595. return lathe;
  69596. };
  69597. /**
  69598. * Creates a plane mesh
  69599. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  69600. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  69601. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  69602. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69603. * * 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
  69604. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69605. * @param name defines the name of the mesh
  69606. * @param options defines the options used to create the mesh
  69607. * @param scene defines the hosting scene
  69608. * @returns the plane mesh
  69609. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69610. */
  69611. MeshBuilder.CreatePlane = function (name, options, scene) {
  69612. var plane = new BABYLON.Mesh(name, scene);
  69613. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69614. plane._originalBuilderSideOrientation = options.sideOrientation;
  69615. var vertexData = BABYLON.VertexData.CreatePlane(options);
  69616. vertexData.applyToMesh(plane, options.updatable);
  69617. if (options.sourcePlane) {
  69618. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  69619. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  69620. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  69621. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  69622. plane.rotate(vectorProduct, product);
  69623. }
  69624. }
  69625. return plane;
  69626. };
  69627. /**
  69628. * Creates a ground mesh
  69629. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  69630. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  69631. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69632. * @param name defines the name of the mesh
  69633. * @param options defines the options used to create the mesh
  69634. * @param scene defines the hosting scene
  69635. * @returns the ground mesh
  69636. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69637. */
  69638. MeshBuilder.CreateGround = function (name, options, scene) {
  69639. var ground = new BABYLON.GroundMesh(name, scene);
  69640. ground._setReady(false);
  69641. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  69642. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  69643. ground._width = options.width || 1;
  69644. ground._height = options.height || 1;
  69645. ground._maxX = ground._width / 2;
  69646. ground._maxZ = ground._height / 2;
  69647. ground._minX = -ground._maxX;
  69648. ground._minZ = -ground._maxZ;
  69649. var vertexData = BABYLON.VertexData.CreateGround(options);
  69650. vertexData.applyToMesh(ground, options.updatable);
  69651. ground._setReady(true);
  69652. return ground;
  69653. };
  69654. /**
  69655. * Creates a tiled ground mesh
  69656. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  69657. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  69658. * * 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
  69659. * * 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
  69660. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69661. * @param name defines the name of the mesh
  69662. * @param options defines the options used to create the mesh
  69663. * @param scene defines the hosting scene
  69664. * @returns the tiled ground mesh
  69665. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  69666. */
  69667. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  69668. var tiledGround = new BABYLON.Mesh(name, scene);
  69669. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  69670. vertexData.applyToMesh(tiledGround, options.updatable);
  69671. return tiledGround;
  69672. };
  69673. /**
  69674. * Creates a ground mesh from a height map
  69675. * * The parameter `url` sets the URL of the height map image resource.
  69676. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  69677. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  69678. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  69679. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  69680. * * 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.
  69681. * * 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).
  69682. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  69683. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69684. * @param name defines the name of the mesh
  69685. * @param url defines the url to the height map
  69686. * @param options defines the options used to create the mesh
  69687. * @param scene defines the hosting scene
  69688. * @returns the ground mesh
  69689. * @see http://doc.babylonjs.com/babylon101/height_map
  69690. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  69691. */
  69692. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  69693. var width = options.width || 10.0;
  69694. var height = options.height || 10.0;
  69695. var subdivisions = options.subdivisions || 1 | 0;
  69696. var minHeight = options.minHeight || 0.0;
  69697. var maxHeight = options.maxHeight || 1.0;
  69698. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  69699. var alphaFilter = options.alphaFilter || 0.0;
  69700. var updatable = options.updatable;
  69701. var onReady = options.onReady;
  69702. var ground = new BABYLON.GroundMesh(name, scene);
  69703. ground._subdivisionsX = subdivisions;
  69704. ground._subdivisionsY = subdivisions;
  69705. ground._width = width;
  69706. ground._height = height;
  69707. ground._maxX = ground._width / 2.0;
  69708. ground._maxZ = ground._height / 2.0;
  69709. ground._minX = -ground._maxX;
  69710. ground._minZ = -ground._maxZ;
  69711. ground._setReady(false);
  69712. var onload = function (img) {
  69713. // Getting height map data
  69714. var canvas = document.createElement("canvas");
  69715. var context = canvas.getContext("2d");
  69716. if (!context) {
  69717. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  69718. }
  69719. if (scene.isDisposed) {
  69720. return;
  69721. }
  69722. var bufferWidth = img.width;
  69723. var bufferHeight = img.height;
  69724. canvas.width = bufferWidth;
  69725. canvas.height = bufferHeight;
  69726. context.drawImage(img, 0, 0);
  69727. // Create VertexData from map data
  69728. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  69729. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  69730. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  69731. width: width, height: height,
  69732. subdivisions: subdivisions,
  69733. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  69734. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  69735. alphaFilter: alphaFilter
  69736. });
  69737. vertexData.applyToMesh(ground, updatable);
  69738. //execute ready callback, if set
  69739. if (onReady) {
  69740. onReady(ground);
  69741. }
  69742. ground._setReady(true);
  69743. };
  69744. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  69745. return ground;
  69746. };
  69747. /**
  69748. * Creates a polygon mesh
  69749. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  69750. * * 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
  69751. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69752. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69753. * * 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)
  69754. * * Remember you can only change the shape positions, not their number when updating a polygon
  69755. * @param name defines the name of the mesh
  69756. * @param options defines the options used to create the mesh
  69757. * @param scene defines the hosting scene
  69758. * @returns the polygon mesh
  69759. */
  69760. MeshBuilder.CreatePolygon = function (name, options, scene) {
  69761. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69762. var shape = options.shape;
  69763. var holes = options.holes || [];
  69764. var depth = options.depth || 0;
  69765. var contours = [];
  69766. var hole = [];
  69767. for (var i = 0; i < shape.length; i++) {
  69768. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  69769. }
  69770. var epsilon = 0.00000001;
  69771. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  69772. contours.pop();
  69773. }
  69774. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  69775. for (var hNb = 0; hNb < holes.length; hNb++) {
  69776. hole = [];
  69777. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  69778. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  69779. }
  69780. polygonTriangulation.addHole(hole);
  69781. }
  69782. var polygon = polygonTriangulation.build(options.updatable, depth);
  69783. polygon._originalBuilderSideOrientation = options.sideOrientation;
  69784. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  69785. vertexData.applyToMesh(polygon, options.updatable);
  69786. return polygon;
  69787. };
  69788. /**
  69789. * Creates an extruded polygon mesh, with depth in the Y direction.
  69790. * * 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)
  69791. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69792. * @param name defines the name of the mesh
  69793. * @param options defines the options used to create the mesh
  69794. * @param scene defines the hosting scene
  69795. * @returns the polygon mesh
  69796. */
  69797. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  69798. return MeshBuilder.CreatePolygon(name, options, scene);
  69799. };
  69800. /**
  69801. * Creates a tube mesh.
  69802. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69803. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  69804. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  69805. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  69806. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  69807. * * 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)
  69808. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  69809. * * 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
  69810. * * 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
  69811. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69812. * * 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
  69813. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69814. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69815. * @param name defines the name of the mesh
  69816. * @param options defines the options used to create the mesh
  69817. * @param scene defines the hosting scene
  69818. * @returns the tube mesh
  69819. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69820. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  69821. */
  69822. MeshBuilder.CreateTube = function (name, options, scene) {
  69823. var path = options.path;
  69824. var instance = options.instance;
  69825. var radius = 1.0;
  69826. if (options.radius !== undefined) {
  69827. radius = options.radius;
  69828. }
  69829. else if (instance) {
  69830. radius = instance._creationDataStorage.radius;
  69831. }
  69832. var tessellation = options.tessellation || 64 | 0;
  69833. var radiusFunction = options.radiusFunction || null;
  69834. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69835. var invertUV = options.invertUV || false;
  69836. var updatable = options.updatable;
  69837. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69838. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  69839. // tube geometry
  69840. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  69841. var tangents = path3D.getTangents();
  69842. var normals = path3D.getNormals();
  69843. var distances = path3D.getDistances();
  69844. var pi2 = Math.PI * 2;
  69845. var step = pi2 / tessellation * arc;
  69846. var returnRadius = function () { return radius; };
  69847. var radiusFunctionFinal = radiusFunction || returnRadius;
  69848. var circlePath;
  69849. var rad;
  69850. var normal;
  69851. var rotated;
  69852. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69853. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69854. for (var i = 0; i < path.length; i++) {
  69855. rad = radiusFunctionFinal(i, distances[i]); // current radius
  69856. circlePath = Array(); // current circle array
  69857. normal = normals[i]; // current normal
  69858. for (var t = 0; t < tessellation; t++) {
  69859. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  69860. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  69861. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  69862. rotated.scaleInPlace(rad).addInPlace(path[i]);
  69863. circlePath[t] = rotated;
  69864. }
  69865. circlePaths[index] = circlePath;
  69866. index++;
  69867. }
  69868. // cap
  69869. var capPath = function (nbPoints, pathIndex) {
  69870. var pointCap = Array();
  69871. for (var i = 0; i < nbPoints; i++) {
  69872. pointCap.push(path[pathIndex]);
  69873. }
  69874. return pointCap;
  69875. };
  69876. switch (cap) {
  69877. case BABYLON.Mesh.NO_CAP:
  69878. break;
  69879. case BABYLON.Mesh.CAP_START:
  69880. circlePaths[0] = capPath(tessellation, 0);
  69881. circlePaths[1] = circlePaths[2].slice(0);
  69882. break;
  69883. case BABYLON.Mesh.CAP_END:
  69884. circlePaths[index] = circlePaths[index - 1].slice(0);
  69885. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69886. break;
  69887. case BABYLON.Mesh.CAP_ALL:
  69888. circlePaths[0] = capPath(tessellation, 0);
  69889. circlePaths[1] = circlePaths[2].slice(0);
  69890. circlePaths[index] = circlePaths[index - 1].slice(0);
  69891. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69892. break;
  69893. default:
  69894. break;
  69895. }
  69896. return circlePaths;
  69897. };
  69898. var path3D;
  69899. var pathArray;
  69900. if (instance) { // tube update
  69901. var storage = instance._creationDataStorage;
  69902. var arc = options.arc || storage.arc;
  69903. path3D = storage.path3D.update(path);
  69904. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  69905. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  69906. // Update mode, no need to recreate the storage.
  69907. storage.path3D = path3D;
  69908. storage.pathArray = pathArray;
  69909. storage.arc = arc;
  69910. storage.radius = radius;
  69911. return instance;
  69912. }
  69913. // tube creation
  69914. path3D = new BABYLON.Path3D(path);
  69915. var newPathArray = new Array();
  69916. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69917. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  69918. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69919. tube._creationDataStorage.pathArray = pathArray;
  69920. tube._creationDataStorage.path3D = path3D;
  69921. tube._creationDataStorage.tessellation = tessellation;
  69922. tube._creationDataStorage.cap = cap;
  69923. tube._creationDataStorage.arc = options.arc;
  69924. tube._creationDataStorage.radius = radius;
  69925. return tube;
  69926. };
  69927. /**
  69928. * Creates a polyhedron mesh
  69929. * * 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
  69930. * * The parameter `size` (positive float, default 1) sets the polygon size
  69931. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  69932. * * 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`
  69933. * * 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
  69934. * * 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)`)
  69935. * * 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
  69936. * * 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
  69937. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69938. * * 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
  69939. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69940. * @param name defines the name of the mesh
  69941. * @param options defines the options used to create the mesh
  69942. * @param scene defines the hosting scene
  69943. * @returns the polyhedron mesh
  69944. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  69945. */
  69946. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  69947. var polyhedron = new BABYLON.Mesh(name, scene);
  69948. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69949. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  69950. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  69951. vertexData.applyToMesh(polyhedron, options.updatable);
  69952. return polyhedron;
  69953. };
  69954. /**
  69955. * Creates a decal mesh.
  69956. * 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
  69957. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  69958. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  69959. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  69960. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  69961. * @param name defines the name of the mesh
  69962. * @param sourceMesh defines the mesh where the decal must be applied
  69963. * @param options defines the options used to create the mesh
  69964. * @param scene defines the hosting scene
  69965. * @returns the decal mesh
  69966. * @see http://doc.babylonjs.com/how_to/decals
  69967. */
  69968. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  69969. var indices = sourceMesh.getIndices();
  69970. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69971. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69972. var position = options.position || BABYLON.Vector3.Zero();
  69973. var normal = options.normal || BABYLON.Vector3.Up();
  69974. var size = options.size || BABYLON.Vector3.One();
  69975. var angle = options.angle || 0;
  69976. // Getting correct rotation
  69977. if (!normal) {
  69978. var target = new BABYLON.Vector3(0, 0, 1);
  69979. var camera = sourceMesh.getScene().activeCamera;
  69980. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  69981. normal = camera.globalPosition.subtract(cameraWorldTarget);
  69982. }
  69983. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  69984. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  69985. var pitch = Math.atan2(normal.y, len);
  69986. // Matrix
  69987. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  69988. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  69989. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  69990. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  69991. var vertexData = new BABYLON.VertexData();
  69992. vertexData.indices = [];
  69993. vertexData.positions = [];
  69994. vertexData.normals = [];
  69995. vertexData.uvs = [];
  69996. var currentVertexDataIndex = 0;
  69997. var extractDecalVector3 = function (indexId) {
  69998. var result = new BABYLON.PositionNormalVertex();
  69999. if (!indices || !positions || !normals) {
  70000. return result;
  70001. }
  70002. var vertexId = indices[indexId];
  70003. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  70004. // Send vector to decal local world
  70005. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  70006. // Get normal
  70007. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  70008. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  70009. return result;
  70010. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  70011. var clip = function (vertices, axis) {
  70012. if (vertices.length === 0) {
  70013. return vertices;
  70014. }
  70015. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  70016. var clipVertices = function (v0, v1) {
  70017. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  70018. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  70019. };
  70020. var result = new Array();
  70021. for (var index = 0; index < vertices.length; index += 3) {
  70022. var v1Out;
  70023. var v2Out;
  70024. var v3Out;
  70025. var total = 0;
  70026. var nV1 = null;
  70027. var nV2 = null;
  70028. var nV3 = null;
  70029. var nV4 = null;
  70030. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  70031. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  70032. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  70033. v1Out = d1 > 0;
  70034. v2Out = d2 > 0;
  70035. v3Out = d3 > 0;
  70036. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  70037. switch (total) {
  70038. case 0:
  70039. result.push(vertices[index]);
  70040. result.push(vertices[index + 1]);
  70041. result.push(vertices[index + 2]);
  70042. break;
  70043. case 1:
  70044. if (v1Out) {
  70045. nV1 = vertices[index + 1];
  70046. nV2 = vertices[index + 2];
  70047. nV3 = clipVertices(vertices[index], nV1);
  70048. nV4 = clipVertices(vertices[index], nV2);
  70049. }
  70050. if (v2Out) {
  70051. nV1 = vertices[index];
  70052. nV2 = vertices[index + 2];
  70053. nV3 = clipVertices(vertices[index + 1], nV1);
  70054. nV4 = clipVertices(vertices[index + 1], nV2);
  70055. result.push(nV3);
  70056. result.push(nV2.clone());
  70057. result.push(nV1.clone());
  70058. result.push(nV2.clone());
  70059. result.push(nV3.clone());
  70060. result.push(nV4);
  70061. break;
  70062. }
  70063. if (v3Out) {
  70064. nV1 = vertices[index];
  70065. nV2 = vertices[index + 1];
  70066. nV3 = clipVertices(vertices[index + 2], nV1);
  70067. nV4 = clipVertices(vertices[index + 2], nV2);
  70068. }
  70069. if (nV1 && nV2 && nV3 && nV4) {
  70070. result.push(nV1.clone());
  70071. result.push(nV2.clone());
  70072. result.push(nV3);
  70073. result.push(nV4);
  70074. result.push(nV3.clone());
  70075. result.push(nV2.clone());
  70076. }
  70077. break;
  70078. case 2:
  70079. if (!v1Out) {
  70080. nV1 = vertices[index].clone();
  70081. nV2 = clipVertices(nV1, vertices[index + 1]);
  70082. nV3 = clipVertices(nV1, vertices[index + 2]);
  70083. result.push(nV1);
  70084. result.push(nV2);
  70085. result.push(nV3);
  70086. }
  70087. if (!v2Out) {
  70088. nV1 = vertices[index + 1].clone();
  70089. nV2 = clipVertices(nV1, vertices[index + 2]);
  70090. nV3 = clipVertices(nV1, vertices[index]);
  70091. result.push(nV1);
  70092. result.push(nV2);
  70093. result.push(nV3);
  70094. }
  70095. if (!v3Out) {
  70096. nV1 = vertices[index + 2].clone();
  70097. nV2 = clipVertices(nV1, vertices[index]);
  70098. nV3 = clipVertices(nV1, vertices[index + 1]);
  70099. result.push(nV1);
  70100. result.push(nV2);
  70101. result.push(nV3);
  70102. }
  70103. break;
  70104. case 3:
  70105. break;
  70106. }
  70107. }
  70108. return result;
  70109. };
  70110. for (var index = 0; index < indices.length; index += 3) {
  70111. var faceVertices = new Array();
  70112. faceVertices.push(extractDecalVector3(index));
  70113. faceVertices.push(extractDecalVector3(index + 1));
  70114. faceVertices.push(extractDecalVector3(index + 2));
  70115. // Clip
  70116. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  70117. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  70118. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  70119. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  70120. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  70121. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  70122. if (faceVertices.length === 0) {
  70123. continue;
  70124. }
  70125. // Add UVs and get back to world
  70126. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  70127. var vertex = faceVertices[vIndex];
  70128. //TODO check for Int32Array | Uint32Array | Uint16Array
  70129. vertexData.indices.push(currentVertexDataIndex);
  70130. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  70131. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  70132. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  70133. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  70134. currentVertexDataIndex++;
  70135. }
  70136. }
  70137. // Return mesh
  70138. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  70139. vertexData.applyToMesh(decal);
  70140. decal.position = position.clone();
  70141. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  70142. return decal;
  70143. };
  70144. // Privates
  70145. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  70146. // extrusion geometry
  70147. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  70148. var tangents = path3D.getTangents();
  70149. var normals = path3D.getNormals();
  70150. var binormals = path3D.getBinormals();
  70151. var distances = path3D.getDistances();
  70152. var angle = 0;
  70153. var returnScale = function () { return scale !== null ? scale : 1; };
  70154. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  70155. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  70156. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  70157. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70158. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70159. for (var i = 0; i < curve.length; i++) {
  70160. var shapePath = new Array();
  70161. var angleStep = rotate(i, distances[i]);
  70162. var scaleRatio = scl(i, distances[i]);
  70163. for (var p = 0; p < shape.length; p++) {
  70164. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  70165. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  70166. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  70167. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  70168. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  70169. shapePath[p] = rotated;
  70170. }
  70171. shapePaths[index] = shapePath;
  70172. angle += angleStep;
  70173. index++;
  70174. }
  70175. // cap
  70176. var capPath = function (shapePath) {
  70177. var pointCap = Array();
  70178. var barycenter = BABYLON.Vector3.Zero();
  70179. var i;
  70180. for (i = 0; i < shapePath.length; i++) {
  70181. barycenter.addInPlace(shapePath[i]);
  70182. }
  70183. barycenter.scaleInPlace(1.0 / shapePath.length);
  70184. for (i = 0; i < shapePath.length; i++) {
  70185. pointCap.push(barycenter);
  70186. }
  70187. return pointCap;
  70188. };
  70189. switch (cap) {
  70190. case BABYLON.Mesh.NO_CAP:
  70191. break;
  70192. case BABYLON.Mesh.CAP_START:
  70193. shapePaths[0] = capPath(shapePaths[2]);
  70194. shapePaths[1] = shapePaths[2];
  70195. break;
  70196. case BABYLON.Mesh.CAP_END:
  70197. shapePaths[index] = shapePaths[index - 1];
  70198. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70199. break;
  70200. case BABYLON.Mesh.CAP_ALL:
  70201. shapePaths[0] = capPath(shapePaths[2]);
  70202. shapePaths[1] = shapePaths[2];
  70203. shapePaths[index] = shapePaths[index - 1];
  70204. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70205. break;
  70206. default:
  70207. break;
  70208. }
  70209. return shapePaths;
  70210. };
  70211. var path3D;
  70212. var pathArray;
  70213. if (instance) { // instance update
  70214. var storage = instance._creationDataStorage;
  70215. path3D = storage.path3D.update(curve);
  70216. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  70217. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  70218. return instance;
  70219. }
  70220. // extruded shape creation
  70221. path3D = new BABYLON.Path3D(curve);
  70222. var newShapePaths = new Array();
  70223. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70224. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  70225. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  70226. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  70227. extrudedGeneric._creationDataStorage.path3D = path3D;
  70228. extrudedGeneric._creationDataStorage.cap = cap;
  70229. return extrudedGeneric;
  70230. };
  70231. return MeshBuilder;
  70232. }());
  70233. BABYLON.MeshBuilder = MeshBuilder;
  70234. })(BABYLON || (BABYLON = {}));
  70235. //# sourceMappingURL=babylon.meshBuilder.js.map
  70236. var BABYLON;
  70237. (function (BABYLON) {
  70238. /**
  70239. * Draco compression (https://google.github.io/draco/)
  70240. *
  70241. * This class wraps the Draco module.
  70242. *
  70243. * **Encoder**
  70244. *
  70245. * The encoder is not currently implemented.
  70246. *
  70247. * **Decoder**
  70248. *
  70249. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  70250. *
  70251. * To update the configuration, use the following code:
  70252. * ```javascript
  70253. * BABYLON.DracoCompression.Configuration = {
  70254. * decoder: {
  70255. * wasmUrl: "<url to the WebAssembly library>",
  70256. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  70257. * fallbackUrl: "<url to the fallback JavaScript library>",
  70258. * }
  70259. * };
  70260. * ```
  70261. *
  70262. * 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.
  70263. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  70264. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  70265. *
  70266. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  70267. * ```javascript
  70268. * var dracoCompression = new BABYLON.DracoCompression();
  70269. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  70270. * [BABYLON.VertexBuffer.PositionKind]: 0
  70271. * });
  70272. * ```
  70273. *
  70274. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  70275. */
  70276. var DracoCompression = /** @class */ (function () {
  70277. /**
  70278. * Constructor
  70279. */
  70280. function DracoCompression() {
  70281. }
  70282. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  70283. /**
  70284. * Returns true if the decoder is available.
  70285. */
  70286. get: function () {
  70287. if (typeof DracoDecoderModule !== "undefined") {
  70288. return true;
  70289. }
  70290. var decoder = DracoCompression.Configuration.decoder;
  70291. if (decoder) {
  70292. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70293. return true;
  70294. }
  70295. if (decoder.fallbackUrl) {
  70296. return true;
  70297. }
  70298. }
  70299. return false;
  70300. },
  70301. enumerable: true,
  70302. configurable: true
  70303. });
  70304. /**
  70305. * Stop all async operations and release resources.
  70306. */
  70307. DracoCompression.prototype.dispose = function () {
  70308. };
  70309. /**
  70310. * Decode Draco compressed mesh data to vertex data.
  70311. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  70312. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  70313. * @returns A promise that resolves with the decoded vertex data
  70314. */
  70315. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  70316. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  70317. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  70318. var module = wrappedModule.module;
  70319. var vertexData = new BABYLON.VertexData();
  70320. var buffer = new module.DecoderBuffer();
  70321. buffer.Init(dataView, dataView.byteLength);
  70322. var decoder = new module.Decoder();
  70323. var geometry;
  70324. var status;
  70325. try {
  70326. var type = decoder.GetEncodedGeometryType(buffer);
  70327. switch (type) {
  70328. case module.TRIANGULAR_MESH:
  70329. geometry = new module.Mesh();
  70330. status = decoder.DecodeBufferToMesh(buffer, geometry);
  70331. break;
  70332. case module.POINT_CLOUD:
  70333. geometry = new module.PointCloud();
  70334. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  70335. break;
  70336. default:
  70337. throw new Error("Invalid geometry type " + type);
  70338. }
  70339. if (!status.ok() || !geometry.ptr) {
  70340. throw new Error(status.error_msg());
  70341. }
  70342. var numPoints = geometry.num_points();
  70343. if (type === module.TRIANGULAR_MESH) {
  70344. var numFaces = geometry.num_faces();
  70345. var faceIndices = new module.DracoInt32Array();
  70346. try {
  70347. var indices = new Uint32Array(numFaces * 3);
  70348. for (var i = 0; i < numFaces; i++) {
  70349. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  70350. var offset = i * 3;
  70351. indices[offset + 0] = faceIndices.GetValue(0);
  70352. indices[offset + 1] = faceIndices.GetValue(1);
  70353. indices[offset + 2] = faceIndices.GetValue(2);
  70354. }
  70355. vertexData.indices = indices;
  70356. }
  70357. finally {
  70358. module.destroy(faceIndices);
  70359. }
  70360. }
  70361. for (var kind in attributes) {
  70362. var uniqueId = attributes[kind];
  70363. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  70364. var dracoData = new module.DracoFloat32Array();
  70365. try {
  70366. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  70367. var babylonData = new Float32Array(numPoints * attribute.num_components());
  70368. for (var i = 0; i < babylonData.length; i++) {
  70369. babylonData[i] = dracoData.GetValue(i);
  70370. }
  70371. vertexData.set(babylonData, kind);
  70372. }
  70373. finally {
  70374. module.destroy(dracoData);
  70375. }
  70376. }
  70377. }
  70378. finally {
  70379. if (geometry) {
  70380. module.destroy(geometry);
  70381. }
  70382. module.destroy(decoder);
  70383. module.destroy(buffer);
  70384. }
  70385. return vertexData;
  70386. });
  70387. };
  70388. DracoCompression._GetDecoderModule = function () {
  70389. if (!DracoCompression._DecoderModulePromise) {
  70390. var promise = null;
  70391. var config_1 = {};
  70392. if (typeof DracoDecoderModule !== "undefined") {
  70393. promise = Promise.resolve();
  70394. }
  70395. else {
  70396. var decoder = DracoCompression.Configuration.decoder;
  70397. if (decoder) {
  70398. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70399. promise = Promise.all([
  70400. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  70401. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  70402. config_1.wasmBinary = data;
  70403. })
  70404. ]);
  70405. }
  70406. else if (decoder.fallbackUrl) {
  70407. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  70408. }
  70409. }
  70410. }
  70411. if (!promise) {
  70412. throw new Error("Draco decoder module is not available");
  70413. }
  70414. DracoCompression._DecoderModulePromise = promise.then(function () {
  70415. return new Promise(function (resolve) {
  70416. config_1.onModuleLoaded = function (decoderModule) {
  70417. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  70418. resolve({ module: decoderModule });
  70419. };
  70420. DracoDecoderModule(config_1);
  70421. });
  70422. });
  70423. }
  70424. return DracoCompression._DecoderModulePromise;
  70425. };
  70426. DracoCompression._LoadScriptAsync = function (url) {
  70427. return new Promise(function (resolve, reject) {
  70428. BABYLON.Tools.LoadScript(url, function () {
  70429. resolve();
  70430. }, function (message) {
  70431. reject(new Error(message));
  70432. });
  70433. });
  70434. };
  70435. DracoCompression._LoadFileAsync = function (url) {
  70436. return new Promise(function (resolve, reject) {
  70437. BABYLON.Tools.LoadFile(url, function (data) {
  70438. resolve(data);
  70439. }, undefined, undefined, true, function (request, exception) {
  70440. reject(exception);
  70441. });
  70442. });
  70443. };
  70444. /**
  70445. * The configuration. Defaults to the following urls:
  70446. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  70447. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  70448. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70449. */
  70450. DracoCompression.Configuration = {
  70451. decoder: {
  70452. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  70453. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  70454. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70455. }
  70456. };
  70457. return DracoCompression;
  70458. }());
  70459. BABYLON.DracoCompression = DracoCompression;
  70460. })(BABYLON || (BABYLON = {}));
  70461. //# sourceMappingURL=babylon.dracoCompression.js.map
  70462. var BABYLON;
  70463. (function (BABYLON) {
  70464. // Sets the default audio engine to Babylon.js
  70465. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  70466. /**
  70467. * This represents the default audio engine used in babylon.
  70468. * It is responsible to play, synchronize and analyse sounds throughout the application.
  70469. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70470. */
  70471. var AudioEngine = /** @class */ (function () {
  70472. /**
  70473. * Instantiates a new audio engine.
  70474. *
  70475. * There should be only one per page as some browsers restrict the number
  70476. * of audio contexts you can create.
  70477. * @param hostElement defines the host element where to display the mute icon if necessary
  70478. */
  70479. function AudioEngine(hostElement) {
  70480. if (hostElement === void 0) { hostElement = null; }
  70481. var _this = this;
  70482. this._audioContext = null;
  70483. this._audioContextInitialized = false;
  70484. this._muteButton = null;
  70485. /**
  70486. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  70487. */
  70488. this.canUseWebAudio = false;
  70489. /**
  70490. * Defines if Babylon should emit a warning if WebAudio is not supported.
  70491. * @ignoreNaming
  70492. */
  70493. this.WarnedWebAudioUnsupported = false;
  70494. /**
  70495. * Gets whether or not mp3 are supported by your browser.
  70496. */
  70497. this.isMP3supported = false;
  70498. /**
  70499. * Gets whether or not ogg are supported by your browser.
  70500. */
  70501. this.isOGGsupported = false;
  70502. /**
  70503. * Gets whether audio has been unlocked on the device.
  70504. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  70505. * a user interaction has happened.
  70506. */
  70507. this.unlocked = true;
  70508. /**
  70509. * Defines if the audio engine relies on a custom unlocked button.
  70510. * In this case, the embedded button will not be displayed.
  70511. */
  70512. this.useCustomUnlockedButton = false;
  70513. /**
  70514. * Event raised when audio has been unlocked on the browser.
  70515. */
  70516. this.onAudioUnlockedObservable = new BABYLON.Observable();
  70517. /**
  70518. * Event raised when audio has been locked on the browser.
  70519. */
  70520. this.onAudioLockedObservable = new BABYLON.Observable();
  70521. this._tryToRun = false;
  70522. this._onResize = function () {
  70523. _this._moveButtonToTopLeft();
  70524. };
  70525. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  70526. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  70527. this.canUseWebAudio = true;
  70528. }
  70529. var audioElem = document.createElement('audio');
  70530. this._hostElement = hostElement;
  70531. try {
  70532. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  70533. this.isMP3supported = true;
  70534. }
  70535. }
  70536. catch (e) {
  70537. // protect error during capability check.
  70538. }
  70539. try {
  70540. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  70541. this.isOGGsupported = true;
  70542. }
  70543. }
  70544. catch (e) {
  70545. // protect error during capability check.
  70546. }
  70547. }
  70548. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  70549. /**
  70550. * Gets the current AudioContext if available.
  70551. */
  70552. get: function () {
  70553. if (!this._audioContextInitialized) {
  70554. this._initializeAudioContext();
  70555. }
  70556. else {
  70557. if (!this.unlocked && !this._muteButton) {
  70558. this._displayMuteButton();
  70559. }
  70560. }
  70561. return this._audioContext;
  70562. },
  70563. enumerable: true,
  70564. configurable: true
  70565. });
  70566. /**
  70567. * Flags the audio engine in Locked state.
  70568. * This happens due to new browser policies preventing audio to autoplay.
  70569. */
  70570. AudioEngine.prototype.lock = function () {
  70571. this._triggerSuspendedState();
  70572. };
  70573. /**
  70574. * Unlocks the audio engine once a user action has been done on the dom.
  70575. * This is helpful to resume play once browser policies have been satisfied.
  70576. */
  70577. AudioEngine.prototype.unlock = function () {
  70578. this._triggerRunningState();
  70579. };
  70580. AudioEngine.prototype._resumeAudioContext = function () {
  70581. var result;
  70582. if (this._audioContext.resume) {
  70583. result = this._audioContext.resume();
  70584. }
  70585. return result || Promise.resolve();
  70586. };
  70587. AudioEngine.prototype._initializeAudioContext = function () {
  70588. try {
  70589. if (this.canUseWebAudio) {
  70590. this._audioContext = new AudioContext();
  70591. // create a global volume gain node
  70592. this.masterGain = this._audioContext.createGain();
  70593. this.masterGain.gain.value = 1;
  70594. this.masterGain.connect(this._audioContext.destination);
  70595. this._audioContextInitialized = true;
  70596. if (this._audioContext.state === "running") {
  70597. // Do not wait for the promise to unlock.
  70598. this._triggerRunningState();
  70599. }
  70600. }
  70601. }
  70602. catch (e) {
  70603. this.canUseWebAudio = false;
  70604. BABYLON.Tools.Error("Web Audio: " + e.message);
  70605. }
  70606. };
  70607. AudioEngine.prototype._triggerRunningState = function () {
  70608. var _this = this;
  70609. if (this._tryToRun) {
  70610. return;
  70611. }
  70612. this._tryToRun = true;
  70613. this._resumeAudioContext()
  70614. .then(function () {
  70615. _this._tryToRun = false;
  70616. if (_this._muteButton) {
  70617. _this._hideMuteButton();
  70618. }
  70619. }).catch(function () {
  70620. _this._tryToRun = false;
  70621. _this.unlocked = false;
  70622. });
  70623. // Notify users that the audio stack is unlocked/unmuted
  70624. this.unlocked = true;
  70625. this.onAudioUnlockedObservable.notifyObservers(this);
  70626. };
  70627. AudioEngine.prototype._triggerSuspendedState = function () {
  70628. this.unlocked = false;
  70629. this.onAudioLockedObservable.notifyObservers(this);
  70630. this._displayMuteButton();
  70631. };
  70632. AudioEngine.prototype._displayMuteButton = function () {
  70633. var _this = this;
  70634. if (this.useCustomUnlockedButton) {
  70635. return;
  70636. }
  70637. this._muteButton = document.createElement("BUTTON");
  70638. this._muteButton.className = "babylonUnmuteIcon";
  70639. this._muteButton.id = "babylonUnmuteIconBtn";
  70640. this._muteButton.title = "Unmute";
  70641. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  70642. var style = document.createElement('style');
  70643. style.appendChild(document.createTextNode(css));
  70644. document.getElementsByTagName('head')[0].appendChild(style);
  70645. document.body.appendChild(this._muteButton);
  70646. this._moveButtonToTopLeft();
  70647. this._muteButton.addEventListener('touchend', function () {
  70648. _this._triggerRunningState();
  70649. }, true);
  70650. this._muteButton.addEventListener('click', function () {
  70651. _this._triggerRunningState();
  70652. }, true);
  70653. window.addEventListener("resize", this._onResize);
  70654. };
  70655. AudioEngine.prototype._moveButtonToTopLeft = function () {
  70656. if (this._hostElement && this._muteButton) {
  70657. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  70658. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  70659. }
  70660. };
  70661. AudioEngine.prototype._hideMuteButton = function () {
  70662. if (this._muteButton) {
  70663. document.body.removeChild(this._muteButton);
  70664. this._muteButton = null;
  70665. }
  70666. };
  70667. /**
  70668. * Destroy and release the resources associated with the audio ccontext.
  70669. */
  70670. AudioEngine.prototype.dispose = function () {
  70671. if (this.canUseWebAudio && this._audioContextInitialized) {
  70672. if (this._connectedAnalyser && this._audioContext) {
  70673. this._connectedAnalyser.stopDebugCanvas();
  70674. this._connectedAnalyser.dispose();
  70675. this.masterGain.disconnect();
  70676. this.masterGain.connect(this._audioContext.destination);
  70677. this._connectedAnalyser = null;
  70678. }
  70679. this.masterGain.gain.value = 1;
  70680. }
  70681. this.WarnedWebAudioUnsupported = false;
  70682. this._hideMuteButton();
  70683. window.removeEventListener("resize", this._onResize);
  70684. this.onAudioUnlockedObservable.clear();
  70685. this.onAudioLockedObservable.clear();
  70686. };
  70687. /**
  70688. * Gets the global volume sets on the master gain.
  70689. * @returns the global volume if set or -1 otherwise
  70690. */
  70691. AudioEngine.prototype.getGlobalVolume = function () {
  70692. if (this.canUseWebAudio && this._audioContextInitialized) {
  70693. return this.masterGain.gain.value;
  70694. }
  70695. else {
  70696. return -1;
  70697. }
  70698. };
  70699. /**
  70700. * Sets the global volume of your experience (sets on the master gain).
  70701. * @param newVolume Defines the new global volume of the application
  70702. */
  70703. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  70704. if (this.canUseWebAudio && this._audioContextInitialized) {
  70705. this.masterGain.gain.value = newVolume;
  70706. }
  70707. };
  70708. /**
  70709. * Connect the audio engine to an audio analyser allowing some amazing
  70710. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70711. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70712. * @param analyser The analyser to connect to the engine
  70713. */
  70714. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  70715. if (this._connectedAnalyser) {
  70716. this._connectedAnalyser.stopDebugCanvas();
  70717. }
  70718. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  70719. this._connectedAnalyser = analyser;
  70720. this.masterGain.disconnect();
  70721. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  70722. }
  70723. };
  70724. return AudioEngine;
  70725. }());
  70726. BABYLON.AudioEngine = AudioEngine;
  70727. })(BABYLON || (BABYLON = {}));
  70728. //# sourceMappingURL=babylon.audioEngine.js.map
  70729. var BABYLON;
  70730. (function (BABYLON) {
  70731. /**
  70732. * Defines a sound that can be played in the application.
  70733. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  70734. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70735. */
  70736. var Sound = /** @class */ (function () {
  70737. /**
  70738. * Create a sound and attach it to a scene
  70739. * @param name Name of your sound
  70740. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  70741. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  70742. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  70743. */
  70744. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  70745. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  70746. var _this = this;
  70747. /**
  70748. * Does the sound autoplay once loaded.
  70749. */
  70750. this.autoplay = false;
  70751. /**
  70752. * Does the sound loop after it finishes playing once.
  70753. */
  70754. this.loop = false;
  70755. /**
  70756. * Does the sound use a custom attenuation curve to simulate the falloff
  70757. * happening when the source gets further away from the camera.
  70758. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70759. */
  70760. this.useCustomAttenuation = false;
  70761. /**
  70762. * Is this sound currently played.
  70763. */
  70764. this.isPlaying = false;
  70765. /**
  70766. * Is this sound currently paused.
  70767. */
  70768. this.isPaused = false;
  70769. /**
  70770. * Does this sound enables spatial sound.
  70771. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70772. */
  70773. this.spatialSound = false;
  70774. /**
  70775. * Define the reference distance the sound should be heard perfectly.
  70776. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70777. */
  70778. this.refDistance = 1;
  70779. /**
  70780. * Define the roll off factor of spatial sounds.
  70781. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70782. */
  70783. this.rolloffFactor = 1;
  70784. /**
  70785. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  70786. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70787. */
  70788. this.maxDistance = 100;
  70789. /**
  70790. * Define the distance attenuation model the sound will follow.
  70791. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70792. */
  70793. this.distanceModel = "linear";
  70794. /**
  70795. * Observable event when the current playing sound finishes.
  70796. */
  70797. this.onEndedObservable = new BABYLON.Observable();
  70798. this._panningModel = "equalpower";
  70799. this._playbackRate = 1;
  70800. this._streaming = false;
  70801. this._startTime = 0;
  70802. this._startOffset = 0;
  70803. this._position = BABYLON.Vector3.Zero();
  70804. /** @hidden */
  70805. this._positionInEmitterSpace = false;
  70806. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  70807. this._volume = 1;
  70808. this._isReadyToPlay = false;
  70809. this._isDirectional = false;
  70810. // Used if you'd like to create a directional sound.
  70811. // If not set, the sound will be omnidirectional
  70812. this._coneInnerAngle = 360;
  70813. this._coneOuterAngle = 360;
  70814. this._coneOuterGain = 0;
  70815. this._isOutputConnected = false;
  70816. this._urlType = "Unknown";
  70817. this.name = name;
  70818. this._scene = scene;
  70819. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70820. if (!compo) {
  70821. compo = new BABYLON.AudioSceneComponent(scene);
  70822. scene._addComponent(compo);
  70823. }
  70824. this._readyToPlayCallback = readyToPlayCallback;
  70825. // Default custom attenuation function is a linear attenuation
  70826. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  70827. if (currentDistance < maxDistance) {
  70828. return currentVolume * (1 - currentDistance / maxDistance);
  70829. }
  70830. else {
  70831. return 0;
  70832. }
  70833. };
  70834. if (options) {
  70835. this.autoplay = options.autoplay || false;
  70836. this.loop = options.loop || false;
  70837. // if volume === 0, we need another way to check this option
  70838. if (options.volume !== undefined) {
  70839. this._volume = options.volume;
  70840. }
  70841. this.spatialSound = options.spatialSound || false;
  70842. this.maxDistance = options.maxDistance || 100;
  70843. this.useCustomAttenuation = options.useCustomAttenuation || false;
  70844. this.rolloffFactor = options.rolloffFactor || 1;
  70845. this.refDistance = options.refDistance || 1;
  70846. this.distanceModel = options.distanceModel || "linear";
  70847. this._playbackRate = options.playbackRate || 1;
  70848. this._streaming = options.streaming || false;
  70849. }
  70850. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70851. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  70852. this._soundGain.gain.value = this._volume;
  70853. this._inputAudioNode = this._soundGain;
  70854. this._outputAudioNode = this._soundGain;
  70855. if (this.spatialSound) {
  70856. this._createSpatialParameters();
  70857. }
  70858. this._scene.mainSoundTrack.AddSound(this);
  70859. var validParameter = true;
  70860. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  70861. if (urlOrArrayBuffer) {
  70862. try {
  70863. if (typeof (urlOrArrayBuffer) === "string") {
  70864. this._urlType = "String";
  70865. }
  70866. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  70867. this._urlType = "ArrayBuffer";
  70868. }
  70869. else if (urlOrArrayBuffer instanceof MediaStream) {
  70870. this._urlType = "MediaStream";
  70871. }
  70872. else if (Array.isArray(urlOrArrayBuffer)) {
  70873. this._urlType = "Array";
  70874. }
  70875. var urls = [];
  70876. var codecSupportedFound = false;
  70877. switch (this._urlType) {
  70878. case "MediaStream":
  70879. this._streaming = true;
  70880. this._isReadyToPlay = true;
  70881. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  70882. if (this.autoplay) {
  70883. this.play();
  70884. }
  70885. if (this._readyToPlayCallback) {
  70886. this._readyToPlayCallback();
  70887. }
  70888. break;
  70889. case "ArrayBuffer":
  70890. if (urlOrArrayBuffer.byteLength > 0) {
  70891. codecSupportedFound = true;
  70892. this._soundLoaded(urlOrArrayBuffer);
  70893. }
  70894. break;
  70895. case "String":
  70896. urls.push(urlOrArrayBuffer);
  70897. case "Array":
  70898. if (urls.length === 0) {
  70899. urls = urlOrArrayBuffer;
  70900. }
  70901. // If we found a supported format, we load it immediately and stop the loop
  70902. for (var i = 0; i < urls.length; i++) {
  70903. var url = urls[i];
  70904. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  70905. codecSupportedFound = true;
  70906. }
  70907. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  70908. codecSupportedFound = true;
  70909. }
  70910. if (url.indexOf(".wav", url.length - 4) !== -1) {
  70911. codecSupportedFound = true;
  70912. }
  70913. if (url.indexOf("blob:") !== -1) {
  70914. codecSupportedFound = true;
  70915. }
  70916. if (codecSupportedFound) {
  70917. // Loading sound using XHR2
  70918. if (!this._streaming) {
  70919. this._scene._loadFile(url, function (data) {
  70920. _this._soundLoaded(data);
  70921. }, undefined, true, true, function (exception) {
  70922. if (exception) {
  70923. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  70924. }
  70925. BABYLON.Tools.Error("Sound creation aborted.");
  70926. _this._scene.mainSoundTrack.RemoveSound(_this);
  70927. });
  70928. }
  70929. // Streaming sound using HTML5 Audio tag
  70930. else {
  70931. this._htmlAudioElement = new Audio(url);
  70932. this._htmlAudioElement.controls = false;
  70933. this._htmlAudioElement.loop = this.loop;
  70934. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  70935. this._htmlAudioElement.preload = "auto";
  70936. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  70937. _this._isReadyToPlay = true;
  70938. if (_this.autoplay) {
  70939. _this.play();
  70940. }
  70941. if (_this._readyToPlayCallback) {
  70942. _this._readyToPlayCallback();
  70943. }
  70944. });
  70945. document.body.appendChild(this._htmlAudioElement);
  70946. this._htmlAudioElement.load();
  70947. }
  70948. break;
  70949. }
  70950. }
  70951. break;
  70952. default:
  70953. validParameter = false;
  70954. break;
  70955. }
  70956. if (!validParameter) {
  70957. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  70958. }
  70959. else {
  70960. if (!codecSupportedFound) {
  70961. this._isReadyToPlay = true;
  70962. // Simulating a ready to play event to avoid breaking code path
  70963. if (this._readyToPlayCallback) {
  70964. window.setTimeout(function () {
  70965. if (_this._readyToPlayCallback) {
  70966. _this._readyToPlayCallback();
  70967. }
  70968. }, 1000);
  70969. }
  70970. }
  70971. }
  70972. }
  70973. catch (ex) {
  70974. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  70975. this._scene.mainSoundTrack.RemoveSound(this);
  70976. }
  70977. }
  70978. }
  70979. else {
  70980. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  70981. this._scene.mainSoundTrack.AddSound(this);
  70982. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  70983. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  70984. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  70985. }
  70986. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  70987. if (this._readyToPlayCallback) {
  70988. window.setTimeout(function () {
  70989. if (_this._readyToPlayCallback) {
  70990. _this._readyToPlayCallback();
  70991. }
  70992. }, 1000);
  70993. }
  70994. }
  70995. }
  70996. /**
  70997. * Release the sound and its associated resources
  70998. */
  70999. Sound.prototype.dispose = function () {
  71000. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71001. if (this.isPlaying) {
  71002. this.stop();
  71003. }
  71004. this._isReadyToPlay = false;
  71005. if (this.soundTrackId === -1) {
  71006. this._scene.mainSoundTrack.RemoveSound(this);
  71007. }
  71008. else if (this._scene.soundTracks) {
  71009. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  71010. }
  71011. if (this._soundGain) {
  71012. this._soundGain.disconnect();
  71013. this._soundGain = null;
  71014. }
  71015. if (this._soundPanner) {
  71016. this._soundPanner.disconnect();
  71017. this._soundPanner = null;
  71018. }
  71019. if (this._soundSource) {
  71020. this._soundSource.disconnect();
  71021. this._soundSource = null;
  71022. }
  71023. this._audioBuffer = null;
  71024. if (this._htmlAudioElement) {
  71025. this._htmlAudioElement.pause();
  71026. this._htmlAudioElement.src = "";
  71027. document.body.removeChild(this._htmlAudioElement);
  71028. }
  71029. if (this._streamingSource) {
  71030. this._streamingSource.disconnect();
  71031. }
  71032. if (this._connectedMesh && this._registerFunc) {
  71033. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71034. this._connectedMesh = null;
  71035. }
  71036. }
  71037. };
  71038. /**
  71039. * Gets if the sounds is ready to be played or not.
  71040. * @returns true if ready, otherwise false
  71041. */
  71042. Sound.prototype.isReady = function () {
  71043. return this._isReadyToPlay;
  71044. };
  71045. Sound.prototype._soundLoaded = function (audioData) {
  71046. var _this = this;
  71047. if (!BABYLON.Engine.audioEngine.audioContext) {
  71048. return;
  71049. }
  71050. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  71051. _this._audioBuffer = buffer;
  71052. _this._isReadyToPlay = true;
  71053. if (_this.autoplay) {
  71054. _this.play();
  71055. }
  71056. if (_this._readyToPlayCallback) {
  71057. _this._readyToPlayCallback();
  71058. }
  71059. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71060. };
  71061. /**
  71062. * Sets the data of the sound from an audiobuffer
  71063. * @param audioBuffer The audioBuffer containing the data
  71064. */
  71065. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71067. this._audioBuffer = audioBuffer;
  71068. this._isReadyToPlay = true;
  71069. }
  71070. };
  71071. /**
  71072. * Updates the current sounds options such as maxdistance, loop...
  71073. * @param options A JSON object containing values named as the object properties
  71074. */
  71075. Sound.prototype.updateOptions = function (options) {
  71076. if (options) {
  71077. this.loop = options.loop || this.loop;
  71078. this.maxDistance = options.maxDistance || this.maxDistance;
  71079. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71080. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71081. this.refDistance = options.refDistance || this.refDistance;
  71082. this.distanceModel = options.distanceModel || this.distanceModel;
  71083. this._playbackRate = options.playbackRate || this._playbackRate;
  71084. this._updateSpatialParameters();
  71085. if (this.isPlaying) {
  71086. if (this._streaming && this._htmlAudioElement) {
  71087. this._htmlAudioElement.playbackRate = this._playbackRate;
  71088. }
  71089. else {
  71090. if (this._soundSource) {
  71091. this._soundSource.playbackRate.value = this._playbackRate;
  71092. }
  71093. }
  71094. }
  71095. }
  71096. };
  71097. Sound.prototype._createSpatialParameters = function () {
  71098. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71099. if (this._scene.headphone) {
  71100. this._panningModel = "HRTF";
  71101. }
  71102. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71103. this._updateSpatialParameters();
  71104. this._soundPanner.connect(this._outputAudioNode);
  71105. this._inputAudioNode = this._soundPanner;
  71106. }
  71107. };
  71108. Sound.prototype._updateSpatialParameters = function () {
  71109. if (this.spatialSound && this._soundPanner) {
  71110. if (this.useCustomAttenuation) {
  71111. // Tricks to disable in a way embedded Web Audio attenuation
  71112. this._soundPanner.distanceModel = "linear";
  71113. this._soundPanner.maxDistance = Number.MAX_VALUE;
  71114. this._soundPanner.refDistance = 1;
  71115. this._soundPanner.rolloffFactor = 1;
  71116. this._soundPanner.panningModel = this._panningModel;
  71117. }
  71118. else {
  71119. this._soundPanner.distanceModel = this.distanceModel;
  71120. this._soundPanner.maxDistance = this.maxDistance;
  71121. this._soundPanner.refDistance = this.refDistance;
  71122. this._soundPanner.rolloffFactor = this.rolloffFactor;
  71123. this._soundPanner.panningModel = this._panningModel;
  71124. }
  71125. }
  71126. };
  71127. /**
  71128. * Switch the panning model to HRTF:
  71129. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71130. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71131. */
  71132. Sound.prototype.switchPanningModelToHRTF = function () {
  71133. this._panningModel = "HRTF";
  71134. this._switchPanningModel();
  71135. };
  71136. /**
  71137. * Switch the panning model to Equal Power:
  71138. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71139. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71140. */
  71141. Sound.prototype.switchPanningModelToEqualPower = function () {
  71142. this._panningModel = "equalpower";
  71143. this._switchPanningModel();
  71144. };
  71145. Sound.prototype._switchPanningModel = function () {
  71146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71147. this._soundPanner.panningModel = this._panningModel;
  71148. }
  71149. };
  71150. /**
  71151. * Connect this sound to a sound track audio node like gain...
  71152. * @param soundTrackAudioNode the sound track audio node to connect to
  71153. */
  71154. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  71155. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71156. if (this._isOutputConnected) {
  71157. this._outputAudioNode.disconnect();
  71158. }
  71159. this._outputAudioNode.connect(soundTrackAudioNode);
  71160. this._isOutputConnected = true;
  71161. }
  71162. };
  71163. /**
  71164. * Transform this sound into a directional source
  71165. * @param coneInnerAngle Size of the inner cone in degree
  71166. * @param coneOuterAngle Size of the outer cone in degree
  71167. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  71168. */
  71169. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  71170. if (coneOuterAngle < coneInnerAngle) {
  71171. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  71172. return;
  71173. }
  71174. this._coneInnerAngle = coneInnerAngle;
  71175. this._coneOuterAngle = coneOuterAngle;
  71176. this._coneOuterGain = coneOuterGain;
  71177. this._isDirectional = true;
  71178. if (this.isPlaying && this.loop) {
  71179. this.stop();
  71180. this.play();
  71181. }
  71182. };
  71183. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  71184. /**
  71185. * Gets or sets the inner angle for the directional cone.
  71186. */
  71187. get: function () {
  71188. return this._coneInnerAngle;
  71189. },
  71190. /**
  71191. * Gets or sets the inner angle for the directional cone.
  71192. */
  71193. set: function (value) {
  71194. if (value != this._coneInnerAngle) {
  71195. if (this._coneOuterAngle < value) {
  71196. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71197. return;
  71198. }
  71199. this._coneInnerAngle = value;
  71200. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71201. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71202. }
  71203. }
  71204. },
  71205. enumerable: true,
  71206. configurable: true
  71207. });
  71208. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  71209. /**
  71210. * Gets or sets the outer angle for the directional cone.
  71211. */
  71212. get: function () {
  71213. return this._coneOuterAngle;
  71214. },
  71215. /**
  71216. * Gets or sets the outer angle for the directional cone.
  71217. */
  71218. set: function (value) {
  71219. if (value != this._coneOuterAngle) {
  71220. if (value < this._coneInnerAngle) {
  71221. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71222. return;
  71223. }
  71224. this._coneOuterAngle = value;
  71225. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71226. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71227. }
  71228. }
  71229. },
  71230. enumerable: true,
  71231. configurable: true
  71232. });
  71233. /**
  71234. * Sets the position of the emitter if spatial sound is enabled
  71235. * @param newPosition Defines the new posisiton
  71236. */
  71237. Sound.prototype.setPosition = function (newPosition) {
  71238. this._position = newPosition;
  71239. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71240. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71241. }
  71242. };
  71243. /**
  71244. * Sets the local direction of the emitter if spatial sound is enabled
  71245. * @param newLocalDirection Defines the new local direction
  71246. */
  71247. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  71248. this._localDirection = newLocalDirection;
  71249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  71250. this._updateDirection();
  71251. }
  71252. };
  71253. Sound.prototype._updateDirection = function () {
  71254. if (!this._connectedMesh || !this._soundPanner) {
  71255. return;
  71256. }
  71257. var mat = this._connectedMesh.getWorldMatrix();
  71258. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  71259. direction.normalize();
  71260. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  71261. };
  71262. /** @hidden */
  71263. Sound.prototype.updateDistanceFromListener = function () {
  71264. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  71265. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  71266. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  71267. }
  71268. };
  71269. /**
  71270. * Sets a new custom attenuation function for the sound.
  71271. * @param callback Defines the function used for the attenuation
  71272. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71273. */
  71274. Sound.prototype.setAttenuationFunction = function (callback) {
  71275. this._customAttenuationFunction = callback;
  71276. };
  71277. /**
  71278. * Play the sound
  71279. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  71280. * @param offset (optional) Start the sound setting it at a specific time
  71281. */
  71282. Sound.prototype.play = function (time, offset) {
  71283. var _this = this;
  71284. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  71285. try {
  71286. if (this._startOffset < 0) {
  71287. time = -this._startOffset;
  71288. this._startOffset = 0;
  71289. }
  71290. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71291. if (!this._soundSource || !this._streamingSource) {
  71292. if (this.spatialSound && this._soundPanner) {
  71293. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71294. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71295. }
  71296. if (this._isDirectional) {
  71297. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71298. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71299. this._soundPanner.coneOuterGain = this._coneOuterGain;
  71300. if (this._connectedMesh) {
  71301. this._updateDirection();
  71302. }
  71303. else {
  71304. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  71305. }
  71306. }
  71307. }
  71308. }
  71309. if (this._streaming) {
  71310. if (!this._streamingSource) {
  71311. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  71312. this._htmlAudioElement.onended = function () { _this._onended(); };
  71313. this._htmlAudioElement.playbackRate = this._playbackRate;
  71314. }
  71315. this._streamingSource.disconnect();
  71316. this._streamingSource.connect(this._inputAudioNode);
  71317. if (this._htmlAudioElement) {
  71318. // required to manage properly the new suspended default state of Chrome
  71319. // When the option 'streaming: true' is used, we need first to wait for
  71320. // the audio engine to be unlocked by a user gesture before trying to play
  71321. // an HTML Audio elememt
  71322. var tryToPlay = function () {
  71323. if (BABYLON.Engine.audioEngine.unlocked) {
  71324. var playPromise = _this._htmlAudioElement.play();
  71325. // In browsers that don’t yet support this functionality,
  71326. // playPromise won’t be defined.
  71327. if (playPromise !== undefined) {
  71328. playPromise.catch(function (error) {
  71329. // Automatic playback failed.
  71330. // Waiting for the audio engine to be unlocked by user click on unmute
  71331. BABYLON.Engine.audioEngine.lock();
  71332. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71333. });
  71334. }
  71335. }
  71336. else {
  71337. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71338. }
  71339. };
  71340. tryToPlay();
  71341. }
  71342. }
  71343. else {
  71344. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  71345. this._soundSource.buffer = this._audioBuffer;
  71346. this._soundSource.connect(this._inputAudioNode);
  71347. this._soundSource.loop = this.loop;
  71348. this._soundSource.playbackRate.value = this._playbackRate;
  71349. this._soundSource.onended = function () { _this._onended(); };
  71350. if (this._soundSource.buffer) {
  71351. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  71352. }
  71353. }
  71354. this._startTime = startTime;
  71355. this.isPlaying = true;
  71356. this.isPaused = false;
  71357. }
  71358. catch (ex) {
  71359. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  71360. }
  71361. }
  71362. };
  71363. Sound.prototype._onended = function () {
  71364. this.isPlaying = false;
  71365. if (this.onended) {
  71366. this.onended();
  71367. }
  71368. this.onEndedObservable.notifyObservers(this);
  71369. };
  71370. /**
  71371. * Stop the sound
  71372. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  71373. */
  71374. Sound.prototype.stop = function (time) {
  71375. if (this.isPlaying) {
  71376. if (this._streaming) {
  71377. if (this._htmlAudioElement) {
  71378. this._htmlAudioElement.pause();
  71379. // Test needed for Firefox or it will generate an Invalid State Error
  71380. if (this._htmlAudioElement.currentTime > 0) {
  71381. this._htmlAudioElement.currentTime = 0;
  71382. }
  71383. }
  71384. else {
  71385. this._streamingSource.disconnect();
  71386. }
  71387. }
  71388. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  71389. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71390. this._soundSource.stop(stopTime);
  71391. this._soundSource.onended = function () { };
  71392. if (!this.isPaused) {
  71393. this._startOffset = 0;
  71394. }
  71395. }
  71396. this.isPlaying = false;
  71397. }
  71398. };
  71399. /**
  71400. * Put the sound in pause
  71401. */
  71402. Sound.prototype.pause = function () {
  71403. if (this.isPlaying) {
  71404. this.isPaused = true;
  71405. if (this._streaming) {
  71406. if (this._htmlAudioElement) {
  71407. this._htmlAudioElement.pause();
  71408. }
  71409. else {
  71410. this._streamingSource.disconnect();
  71411. }
  71412. }
  71413. else if (BABYLON.Engine.audioEngine.audioContext) {
  71414. this.stop(0);
  71415. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  71416. }
  71417. }
  71418. };
  71419. /**
  71420. * Sets a dedicated volume for this sounds
  71421. * @param newVolume Define the new volume of the sound
  71422. * @param time Define in how long the sound should be at this value
  71423. */
  71424. Sound.prototype.setVolume = function (newVolume, time) {
  71425. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  71426. if (time && BABYLON.Engine.audioEngine.audioContext) {
  71427. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  71428. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  71429. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  71430. }
  71431. else {
  71432. this._soundGain.gain.value = newVolume;
  71433. }
  71434. }
  71435. this._volume = newVolume;
  71436. };
  71437. /**
  71438. * Set the sound play back rate
  71439. * @param newPlaybackRate Define the playback rate the sound should be played at
  71440. */
  71441. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  71442. this._playbackRate = newPlaybackRate;
  71443. if (this.isPlaying) {
  71444. if (this._streaming && this._htmlAudioElement) {
  71445. this._htmlAudioElement.playbackRate = this._playbackRate;
  71446. }
  71447. else if (this._soundSource) {
  71448. this._soundSource.playbackRate.value = this._playbackRate;
  71449. }
  71450. }
  71451. };
  71452. /**
  71453. * Gets the volume of the sound.
  71454. * @returns the volume of the sound
  71455. */
  71456. Sound.prototype.getVolume = function () {
  71457. return this._volume;
  71458. };
  71459. /**
  71460. * Attach the sound to a dedicated mesh
  71461. * @param meshToConnectTo The mesh to connect the sound with
  71462. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71463. */
  71464. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  71465. var _this = this;
  71466. if (this._connectedMesh && this._registerFunc) {
  71467. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71468. this._registerFunc = null;
  71469. }
  71470. this._connectedMesh = meshToConnectTo;
  71471. if (!this.spatialSound) {
  71472. this.spatialSound = true;
  71473. this._createSpatialParameters();
  71474. if (this.isPlaying && this.loop) {
  71475. this.stop();
  71476. this.play();
  71477. }
  71478. }
  71479. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  71480. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  71481. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  71482. };
  71483. /**
  71484. * Detach the sound from the previously attached mesh
  71485. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71486. */
  71487. Sound.prototype.detachFromMesh = function () {
  71488. if (this._connectedMesh && this._registerFunc) {
  71489. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71490. this._registerFunc = null;
  71491. this._connectedMesh = null;
  71492. }
  71493. };
  71494. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  71495. if (!node.getBoundingInfo) {
  71496. return;
  71497. }
  71498. var mesh = node;
  71499. if (this._positionInEmitterSpace) {
  71500. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  71501. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  71502. }
  71503. else {
  71504. var boundingInfo = mesh.getBoundingInfo();
  71505. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  71506. }
  71507. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  71508. this._updateDirection();
  71509. }
  71510. };
  71511. /**
  71512. * Clone the current sound in the scene.
  71513. * @returns the new sound clone
  71514. */
  71515. Sound.prototype.clone = function () {
  71516. var _this = this;
  71517. if (!this._streaming) {
  71518. var setBufferAndRun = function () {
  71519. if (_this._isReadyToPlay) {
  71520. clonedSound._audioBuffer = _this.getAudioBuffer();
  71521. clonedSound._isReadyToPlay = true;
  71522. if (clonedSound.autoplay) {
  71523. clonedSound.play();
  71524. }
  71525. }
  71526. else {
  71527. window.setTimeout(setBufferAndRun, 300);
  71528. }
  71529. };
  71530. var currentOptions = {
  71531. autoplay: this.autoplay, loop: this.loop,
  71532. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  71533. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  71534. refDistance: this.refDistance, distanceModel: this.distanceModel
  71535. };
  71536. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  71537. if (this.useCustomAttenuation) {
  71538. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  71539. }
  71540. clonedSound.setPosition(this._position);
  71541. clonedSound.setPlaybackRate(this._playbackRate);
  71542. setBufferAndRun();
  71543. return clonedSound;
  71544. }
  71545. // Can't clone a streaming sound
  71546. else {
  71547. return null;
  71548. }
  71549. };
  71550. /**
  71551. * Gets the current underlying audio buffer containing the data
  71552. * @returns the audio buffer
  71553. */
  71554. Sound.prototype.getAudioBuffer = function () {
  71555. return this._audioBuffer;
  71556. };
  71557. /**
  71558. * Serializes the Sound in a JSON representation
  71559. * @returns the JSON representation of the sound
  71560. */
  71561. Sound.prototype.serialize = function () {
  71562. var serializationObject = {
  71563. name: this.name,
  71564. url: this.name,
  71565. autoplay: this.autoplay,
  71566. loop: this.loop,
  71567. volume: this._volume,
  71568. spatialSound: this.spatialSound,
  71569. maxDistance: this.maxDistance,
  71570. rolloffFactor: this.rolloffFactor,
  71571. refDistance: this.refDistance,
  71572. distanceModel: this.distanceModel,
  71573. playbackRate: this._playbackRate,
  71574. panningModel: this._panningModel,
  71575. soundTrackId: this.soundTrackId
  71576. };
  71577. if (this.spatialSound) {
  71578. if (this._connectedMesh) {
  71579. serializationObject.connectedMeshId = this._connectedMesh.id;
  71580. }
  71581. serializationObject.position = this._position.asArray();
  71582. serializationObject.refDistance = this.refDistance;
  71583. serializationObject.distanceModel = this.distanceModel;
  71584. serializationObject.isDirectional = this._isDirectional;
  71585. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  71586. serializationObject.coneInnerAngle = this._coneInnerAngle;
  71587. serializationObject.coneOuterAngle = this._coneOuterAngle;
  71588. serializationObject.coneOuterGain = this._coneOuterGain;
  71589. }
  71590. return serializationObject;
  71591. };
  71592. /**
  71593. * Parse a JSON representation of a sound to innstantiate in a given scene
  71594. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  71595. * @param scene Define the scene the new parsed sound should be created in
  71596. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  71597. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  71598. * @returns the newly parsed sound
  71599. */
  71600. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  71601. var soundName = parsedSound.name;
  71602. var soundUrl;
  71603. if (parsedSound.url) {
  71604. soundUrl = rootUrl + parsedSound.url;
  71605. }
  71606. else {
  71607. soundUrl = rootUrl + soundName;
  71608. }
  71609. var options = {
  71610. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  71611. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  71612. rolloffFactor: parsedSound.rolloffFactor,
  71613. refDistance: parsedSound.refDistance,
  71614. distanceModel: parsedSound.distanceModel,
  71615. playbackRate: parsedSound.playbackRate
  71616. };
  71617. var newSound;
  71618. if (!sourceSound) {
  71619. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  71620. scene._addPendingData(newSound);
  71621. }
  71622. else {
  71623. var setBufferAndRun = function () {
  71624. if (sourceSound._isReadyToPlay) {
  71625. newSound._audioBuffer = sourceSound.getAudioBuffer();
  71626. newSound._isReadyToPlay = true;
  71627. if (newSound.autoplay) {
  71628. newSound.play();
  71629. }
  71630. }
  71631. else {
  71632. window.setTimeout(setBufferAndRun, 300);
  71633. }
  71634. };
  71635. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  71636. setBufferAndRun();
  71637. }
  71638. if (parsedSound.position) {
  71639. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  71640. newSound.setPosition(soundPosition);
  71641. }
  71642. if (parsedSound.isDirectional) {
  71643. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  71644. if (parsedSound.localDirectionToMesh) {
  71645. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  71646. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  71647. }
  71648. }
  71649. if (parsedSound.connectedMeshId) {
  71650. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  71651. if (connectedMesh) {
  71652. newSound.attachToMesh(connectedMesh);
  71653. }
  71654. }
  71655. return newSound;
  71656. };
  71657. return Sound;
  71658. }());
  71659. BABYLON.Sound = Sound;
  71660. })(BABYLON || (BABYLON = {}));
  71661. //# sourceMappingURL=babylon.sound.js.map
  71662. var BABYLON;
  71663. (function (BABYLON) {
  71664. /**
  71665. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  71666. * It will be also used in a future release to apply effects on a specific track.
  71667. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71668. */
  71669. var SoundTrack = /** @class */ (function () {
  71670. /**
  71671. * Creates a new sound track.
  71672. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71673. * @param scene Define the scene the sound track belongs to
  71674. * @param options
  71675. */
  71676. function SoundTrack(scene, options) {
  71677. if (options === void 0) { options = {}; }
  71678. /**
  71679. * The unique identifier of the sound track in the scene.
  71680. */
  71681. this.id = -1;
  71682. this._isMainTrack = false;
  71683. this._isInitialized = false;
  71684. this._scene = scene;
  71685. this.soundCollection = new Array();
  71686. this._options = options;
  71687. if (!this._isMainTrack && this._scene.soundTracks) {
  71688. this._scene.soundTracks.push(this);
  71689. this.id = this._scene.soundTracks.length - 1;
  71690. }
  71691. }
  71692. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  71693. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71694. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  71695. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  71696. if (this._options) {
  71697. if (this._options.volume) {
  71698. this._outputAudioNode.gain.value = this._options.volume;
  71699. }
  71700. if (this._options.mainTrack) {
  71701. this._isMainTrack = this._options.mainTrack;
  71702. }
  71703. }
  71704. this._isInitialized = true;
  71705. }
  71706. };
  71707. /**
  71708. * Release the sound track and its associated resources
  71709. */
  71710. SoundTrack.prototype.dispose = function () {
  71711. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  71712. if (this._connectedAnalyser) {
  71713. this._connectedAnalyser.stopDebugCanvas();
  71714. }
  71715. while (this.soundCollection.length) {
  71716. this.soundCollection[0].dispose();
  71717. }
  71718. if (this._outputAudioNode) {
  71719. this._outputAudioNode.disconnect();
  71720. }
  71721. this._outputAudioNode = null;
  71722. }
  71723. };
  71724. /**
  71725. * Adds a sound to this sound track
  71726. * @param sound define the cound to add
  71727. * @ignoreNaming
  71728. */
  71729. SoundTrack.prototype.AddSound = function (sound) {
  71730. if (!this._isInitialized) {
  71731. this._initializeSoundTrackAudioGraph();
  71732. }
  71733. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71734. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  71735. }
  71736. if (sound.soundTrackId) {
  71737. if (sound.soundTrackId === -1) {
  71738. this._scene.mainSoundTrack.RemoveSound(sound);
  71739. }
  71740. else if (this._scene.soundTracks) {
  71741. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  71742. }
  71743. }
  71744. this.soundCollection.push(sound);
  71745. sound.soundTrackId = this.id;
  71746. };
  71747. /**
  71748. * Removes a sound to this sound track
  71749. * @param sound define the cound to remove
  71750. * @ignoreNaming
  71751. */
  71752. SoundTrack.prototype.RemoveSound = function (sound) {
  71753. var index = this.soundCollection.indexOf(sound);
  71754. if (index !== -1) {
  71755. this.soundCollection.splice(index, 1);
  71756. }
  71757. };
  71758. /**
  71759. * Set a global volume for the full sound track.
  71760. * @param newVolume Define the new volume of the sound track
  71761. */
  71762. SoundTrack.prototype.setVolume = function (newVolume) {
  71763. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71764. this._outputAudioNode.gain.value = newVolume;
  71765. }
  71766. };
  71767. /**
  71768. * Switch the panning model to HRTF:
  71769. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71770. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71771. */
  71772. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  71773. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71774. for (var i = 0; i < this.soundCollection.length; i++) {
  71775. this.soundCollection[i].switchPanningModelToHRTF();
  71776. }
  71777. }
  71778. };
  71779. /**
  71780. * Switch the panning model to Equal Power:
  71781. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71782. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71783. */
  71784. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  71785. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71786. for (var i = 0; i < this.soundCollection.length; i++) {
  71787. this.soundCollection[i].switchPanningModelToEqualPower();
  71788. }
  71789. }
  71790. };
  71791. /**
  71792. * Connect the sound track to an audio analyser allowing some amazing
  71793. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71794. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71795. * @param analyser The analyser to connect to the engine
  71796. */
  71797. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  71798. if (this._connectedAnalyser) {
  71799. this._connectedAnalyser.stopDebugCanvas();
  71800. }
  71801. this._connectedAnalyser = analyser;
  71802. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71803. this._outputAudioNode.disconnect();
  71804. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  71805. }
  71806. };
  71807. return SoundTrack;
  71808. }());
  71809. BABYLON.SoundTrack = SoundTrack;
  71810. })(BABYLON || (BABYLON = {}));
  71811. //# sourceMappingURL=babylon.soundtrack.js.map
  71812. var BABYLON;
  71813. (function (BABYLON) {
  71814. /**
  71815. * Class used to work with sound analyzer using fast fourier transform (FFT)
  71816. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71817. */
  71818. var Analyser = /** @class */ (function () {
  71819. /**
  71820. * Creates a new analyser
  71821. * @param scene defines hosting scene
  71822. */
  71823. function Analyser(scene) {
  71824. /**
  71825. * Gets or sets the smoothing
  71826. * @ignorenaming
  71827. */
  71828. this.SMOOTHING = 0.75;
  71829. /**
  71830. * Gets or sets the FFT table size
  71831. * @ignorenaming
  71832. */
  71833. this.FFT_SIZE = 512;
  71834. /**
  71835. * Gets or sets the bar graph amplitude
  71836. * @ignorenaming
  71837. */
  71838. this.BARGRAPHAMPLITUDE = 256;
  71839. /**
  71840. * Gets or sets the position of the debug canvas
  71841. * @ignorenaming
  71842. */
  71843. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  71844. /**
  71845. * Gets or sets the debug canvas size
  71846. * @ignorenaming
  71847. */
  71848. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  71849. this._scene = scene;
  71850. this._audioEngine = BABYLON.Engine.audioEngine;
  71851. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  71852. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  71853. this._webAudioAnalyser.minDecibels = -140;
  71854. this._webAudioAnalyser.maxDecibels = 0;
  71855. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71856. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71857. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  71858. }
  71859. }
  71860. /**
  71861. * Get the number of data values you will have to play with for the visualization
  71862. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  71863. * @returns a number
  71864. */
  71865. Analyser.prototype.getFrequencyBinCount = function () {
  71866. if (this._audioEngine.canUseWebAudio) {
  71867. return this._webAudioAnalyser.frequencyBinCount;
  71868. }
  71869. else {
  71870. return 0;
  71871. }
  71872. };
  71873. /**
  71874. * Gets the current frequency data as a byte array
  71875. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71876. * @returns a Uint8Array
  71877. */
  71878. Analyser.prototype.getByteFrequencyData = function () {
  71879. if (this._audioEngine.canUseWebAudio) {
  71880. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71881. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71882. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  71883. }
  71884. return this._byteFreqs;
  71885. };
  71886. /**
  71887. * Gets the current waveform as a byte array
  71888. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  71889. * @returns a Uint8Array
  71890. */
  71891. Analyser.prototype.getByteTimeDomainData = function () {
  71892. if (this._audioEngine.canUseWebAudio) {
  71893. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71894. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71895. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  71896. }
  71897. return this._byteTime;
  71898. };
  71899. /**
  71900. * Gets the current frequency data as a float array
  71901. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71902. * @returns a Float32Array
  71903. */
  71904. Analyser.prototype.getFloatFrequencyData = function () {
  71905. if (this._audioEngine.canUseWebAudio) {
  71906. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71907. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71908. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  71909. }
  71910. return this._floatFreqs;
  71911. };
  71912. /**
  71913. * Renders the debug canvas
  71914. */
  71915. Analyser.prototype.drawDebugCanvas = function () {
  71916. var _this = this;
  71917. if (this._audioEngine.canUseWebAudio) {
  71918. if (!this._debugCanvas) {
  71919. this._debugCanvas = document.createElement("canvas");
  71920. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  71921. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  71922. this._debugCanvas.style.position = "absolute";
  71923. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  71924. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  71925. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  71926. document.body.appendChild(this._debugCanvas);
  71927. this._registerFunc = function () {
  71928. _this.drawDebugCanvas();
  71929. };
  71930. this._scene.registerBeforeRender(this._registerFunc);
  71931. }
  71932. if (this._registerFunc && this._debugCanvasContext) {
  71933. var workingArray = this.getByteFrequencyData();
  71934. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  71935. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  71936. // Draw the frequency domain chart.
  71937. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  71938. var value = workingArray[i];
  71939. var percent = value / this.BARGRAPHAMPLITUDE;
  71940. var height = this.DEBUGCANVASSIZE.height * percent;
  71941. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  71942. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  71943. var hue = i / this.getFrequencyBinCount() * 360;
  71944. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  71945. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  71946. }
  71947. }
  71948. }
  71949. };
  71950. /**
  71951. * Stops rendering the debug canvas and removes it
  71952. */
  71953. Analyser.prototype.stopDebugCanvas = function () {
  71954. if (this._debugCanvas) {
  71955. if (this._registerFunc) {
  71956. this._scene.unregisterBeforeRender(this._registerFunc);
  71957. this._registerFunc = null;
  71958. }
  71959. document.body.removeChild(this._debugCanvas);
  71960. this._debugCanvas = null;
  71961. this._debugCanvasContext = null;
  71962. }
  71963. };
  71964. /**
  71965. * Connects two audio nodes
  71966. * @param inputAudioNode defines first node to connect
  71967. * @param outputAudioNode defines second node to connect
  71968. */
  71969. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  71970. if (this._audioEngine.canUseWebAudio) {
  71971. inputAudioNode.connect(this._webAudioAnalyser);
  71972. this._webAudioAnalyser.connect(outputAudioNode);
  71973. }
  71974. };
  71975. /**
  71976. * Releases all associated resources
  71977. */
  71978. Analyser.prototype.dispose = function () {
  71979. if (this._audioEngine.canUseWebAudio) {
  71980. this._webAudioAnalyser.disconnect();
  71981. }
  71982. };
  71983. return Analyser;
  71984. }());
  71985. BABYLON.Analyser = Analyser;
  71986. })(BABYLON || (BABYLON = {}));
  71987. //# sourceMappingURL=babylon.analyser.js.map
  71988. var BABYLON;
  71989. (function (BABYLON) {
  71990. /**
  71991. * Wraps one or more Sound objects and selects one with random weight for playback.
  71992. */
  71993. var WeightedSound = /** @class */ (function () {
  71994. /**
  71995. * Creates a new WeightedSound from the list of sounds given.
  71996. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  71997. * @param sounds Array of Sounds that will be selected from.
  71998. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  71999. */
  72000. function WeightedSound(loop, sounds, weights) {
  72001. var _this = this;
  72002. /** When true a Sound will be selected and played when the current playing Sound completes. */
  72003. this.loop = false;
  72004. this._coneInnerAngle = 360;
  72005. this._coneOuterAngle = 360;
  72006. this._volume = 1;
  72007. /** A Sound is currently playing. */
  72008. this.isPlaying = false;
  72009. /** A Sound is currently paused. */
  72010. this.isPaused = false;
  72011. this._sounds = [];
  72012. this._weights = [];
  72013. if (sounds.length !== weights.length) {
  72014. throw new Error('Sounds length does not equal weights length');
  72015. }
  72016. this.loop = loop;
  72017. this._weights = weights;
  72018. // Normalize the weights
  72019. var weightSum = 0;
  72020. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  72021. var weight = weights_1[_i];
  72022. weightSum += weight;
  72023. }
  72024. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  72025. for (var i = 0; i < this._weights.length; i++) {
  72026. this._weights[i] *= invWeightSum;
  72027. }
  72028. this._sounds = sounds;
  72029. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  72030. var sound = _b[_a];
  72031. sound.onEndedObservable.add(function () { _this._onended(); });
  72032. }
  72033. }
  72034. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  72035. /**
  72036. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  72037. */
  72038. get: function () {
  72039. return this._coneInnerAngle;
  72040. },
  72041. /**
  72042. * The size of cone in degress for a directional sound in which there will be no attenuation.
  72043. */
  72044. set: function (value) {
  72045. if (value !== this._coneInnerAngle) {
  72046. if (this._coneOuterAngle < value) {
  72047. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72048. return;
  72049. }
  72050. this._coneInnerAngle = value;
  72051. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72052. var sound = _a[_i];
  72053. sound.directionalConeInnerAngle = value;
  72054. }
  72055. }
  72056. },
  72057. enumerable: true,
  72058. configurable: true
  72059. });
  72060. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72061. /**
  72062. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72063. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72064. */
  72065. get: function () {
  72066. return this._coneOuterAngle;
  72067. },
  72068. /**
  72069. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72070. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72071. */
  72072. set: function (value) {
  72073. if (value !== this._coneOuterAngle) {
  72074. if (value < this._coneInnerAngle) {
  72075. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72076. return;
  72077. }
  72078. this._coneOuterAngle = value;
  72079. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72080. var sound = _a[_i];
  72081. sound.directionalConeOuterAngle = value;
  72082. }
  72083. }
  72084. },
  72085. enumerable: true,
  72086. configurable: true
  72087. });
  72088. Object.defineProperty(WeightedSound.prototype, "volume", {
  72089. /**
  72090. * Playback volume.
  72091. */
  72092. get: function () {
  72093. return this._volume;
  72094. },
  72095. /**
  72096. * Playback volume.
  72097. */
  72098. set: function (value) {
  72099. if (value !== this._volume) {
  72100. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72101. var sound = _a[_i];
  72102. sound.setVolume(value);
  72103. }
  72104. }
  72105. },
  72106. enumerable: true,
  72107. configurable: true
  72108. });
  72109. WeightedSound.prototype._onended = function () {
  72110. if (this._currentIndex !== undefined) {
  72111. this._sounds[this._currentIndex].autoplay = false;
  72112. }
  72113. if (this.loop && this.isPlaying) {
  72114. this.play();
  72115. }
  72116. else {
  72117. this.isPlaying = false;
  72118. }
  72119. };
  72120. /**
  72121. * Suspend playback
  72122. */
  72123. WeightedSound.prototype.pause = function () {
  72124. this.isPaused = true;
  72125. if (this._currentIndex !== undefined) {
  72126. this._sounds[this._currentIndex].pause();
  72127. }
  72128. };
  72129. /**
  72130. * Stop playback
  72131. */
  72132. WeightedSound.prototype.stop = function () {
  72133. this.isPlaying = false;
  72134. if (this._currentIndex !== undefined) {
  72135. this._sounds[this._currentIndex].stop();
  72136. }
  72137. };
  72138. /**
  72139. * Start playback.
  72140. * @param startOffset Position the clip head at a specific time in seconds.
  72141. */
  72142. WeightedSound.prototype.play = function (startOffset) {
  72143. if (!this.isPaused) {
  72144. this.stop();
  72145. var randomValue = Math.random();
  72146. var total = 0;
  72147. for (var i = 0; i < this._weights.length; i++) {
  72148. total += this._weights[i];
  72149. if (randomValue <= total) {
  72150. this._currentIndex = i;
  72151. break;
  72152. }
  72153. }
  72154. }
  72155. var sound = this._sounds[this._currentIndex];
  72156. if (sound.isReady()) {
  72157. sound.play(0, this.isPaused ? undefined : startOffset);
  72158. }
  72159. else {
  72160. sound.autoplay = true;
  72161. }
  72162. this.isPlaying = true;
  72163. this.isPaused = false;
  72164. };
  72165. return WeightedSound;
  72166. }());
  72167. BABYLON.WeightedSound = WeightedSound;
  72168. })(BABYLON || (BABYLON = {}));
  72169. //# sourceMappingURL=babylon.weightedsound.js.map
  72170. var BABYLON;
  72171. (function (BABYLON) {
  72172. // Adds the parser to the scene parsers.
  72173. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  72174. // TODO: add sound
  72175. var loadedSounds = [];
  72176. var loadedSound;
  72177. container.sounds = container.sounds || [];
  72178. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72179. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72180. var parsedSound = parsedData.sounds[index];
  72181. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72182. if (!parsedSound.url) {
  72183. parsedSound.url = parsedSound.name;
  72184. }
  72185. if (!loadedSounds[parsedSound.url]) {
  72186. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72187. loadedSounds[parsedSound.url] = loadedSound;
  72188. container.sounds.push(loadedSound);
  72189. }
  72190. else {
  72191. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72192. }
  72193. }
  72194. else {
  72195. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72196. }
  72197. }
  72198. }
  72199. loadedSounds = [];
  72200. });
  72201. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  72202. get: function () {
  72203. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72204. if (!compo) {
  72205. compo = new AudioSceneComponent(this);
  72206. this._addComponent(compo);
  72207. }
  72208. if (!this._mainSoundTrack) {
  72209. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  72210. }
  72211. return this._mainSoundTrack;
  72212. },
  72213. enumerable: true,
  72214. configurable: true
  72215. });
  72216. BABYLON.Scene.prototype.getSoundByName = function (name) {
  72217. var index;
  72218. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  72219. if (this.mainSoundTrack.soundCollection[index].name === name) {
  72220. return this.mainSoundTrack.soundCollection[index];
  72221. }
  72222. }
  72223. if (this.soundTracks) {
  72224. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  72225. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  72226. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  72227. return this.soundTracks[sdIndex].soundCollection[index];
  72228. }
  72229. }
  72230. }
  72231. }
  72232. return null;
  72233. };
  72234. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  72235. get: function () {
  72236. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72237. if (!compo) {
  72238. compo = new AudioSceneComponent(this);
  72239. this._addComponent(compo);
  72240. }
  72241. return compo.audioEnabled;
  72242. },
  72243. set: function (value) {
  72244. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72245. if (!compo) {
  72246. compo = new AudioSceneComponent(this);
  72247. this._addComponent(compo);
  72248. }
  72249. if (value) {
  72250. compo.enableAudio();
  72251. }
  72252. else {
  72253. compo.disableAudio();
  72254. }
  72255. },
  72256. enumerable: true,
  72257. configurable: true
  72258. });
  72259. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  72260. get: function () {
  72261. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72262. if (!compo) {
  72263. compo = new AudioSceneComponent(this);
  72264. this._addComponent(compo);
  72265. }
  72266. return compo.headphone;
  72267. },
  72268. set: function (value) {
  72269. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72270. if (!compo) {
  72271. compo = new AudioSceneComponent(this);
  72272. this._addComponent(compo);
  72273. }
  72274. if (value) {
  72275. compo.switchAudioModeForHeadphones();
  72276. }
  72277. else {
  72278. compo.switchAudioModeForNormalSpeakers();
  72279. }
  72280. },
  72281. enumerable: true,
  72282. configurable: true
  72283. });
  72284. /**
  72285. * Defines the sound scene component responsible to manage any sounds
  72286. * in a given scene.
  72287. */
  72288. var AudioSceneComponent = /** @class */ (function () {
  72289. /**
  72290. * Creates a new instance of the component for the given scene
  72291. * @param scene Defines the scene to register the component in
  72292. */
  72293. function AudioSceneComponent(scene) {
  72294. /**
  72295. * The component name helpfull to identify the component in the list of scene components.
  72296. */
  72297. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  72298. this._audioEnabled = true;
  72299. this._headphone = false;
  72300. this.scene = scene;
  72301. scene.soundTracks = new Array();
  72302. scene.sounds = new Array();
  72303. }
  72304. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  72305. /**
  72306. * Gets whether audio is enabled or not.
  72307. * Please use related enable/disable method to switch state.
  72308. */
  72309. get: function () {
  72310. return this._audioEnabled;
  72311. },
  72312. enumerable: true,
  72313. configurable: true
  72314. });
  72315. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  72316. /**
  72317. * Gets whether audio is outputing to headphone or not.
  72318. * Please use the according Switch methods to change output.
  72319. */
  72320. get: function () {
  72321. return this._headphone;
  72322. },
  72323. enumerable: true,
  72324. configurable: true
  72325. });
  72326. /**
  72327. * Registers the component in a given scene
  72328. */
  72329. AudioSceneComponent.prototype.register = function () {
  72330. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  72331. };
  72332. /**
  72333. * Rebuilds the elements related to this component in case of
  72334. * context lost for instance.
  72335. */
  72336. AudioSceneComponent.prototype.rebuild = function () {
  72337. // Nothing to do here. (Not rendering related)
  72338. };
  72339. /**
  72340. * Serializes the component data to the specified json object
  72341. * @param serializationObject The object to serialize to
  72342. */
  72343. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  72344. serializationObject.sounds = [];
  72345. if (this.scene.soundTracks) {
  72346. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  72347. var soundtrack = this.scene.soundTracks[index];
  72348. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72349. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72350. }
  72351. }
  72352. }
  72353. };
  72354. /**
  72355. * Adds all the element from the container to the scene
  72356. * @param container the container holding the elements
  72357. */
  72358. AudioSceneComponent.prototype.addFromContainer = function (container) {
  72359. var _this = this;
  72360. if (!container.sounds) {
  72361. return;
  72362. }
  72363. container.sounds.forEach(function (sound) {
  72364. sound.play();
  72365. sound.autoplay = true;
  72366. _this.scene.mainSoundTrack.AddSound(sound);
  72367. });
  72368. };
  72369. /**
  72370. * Removes all the elements in the container from the scene
  72371. * @param container contains the elements to remove
  72372. */
  72373. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  72374. var _this = this;
  72375. if (!container.sounds) {
  72376. return;
  72377. }
  72378. container.sounds.forEach(function (sound) {
  72379. sound.stop();
  72380. sound.autoplay = false;
  72381. _this.scene.mainSoundTrack.RemoveSound(sound);
  72382. });
  72383. };
  72384. /**
  72385. * Disposes the component and the associated ressources.
  72386. */
  72387. AudioSceneComponent.prototype.dispose = function () {
  72388. var scene = this.scene;
  72389. if (scene._mainSoundTrack) {
  72390. scene.mainSoundTrack.dispose();
  72391. }
  72392. if (scene.soundTracks) {
  72393. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  72394. scene.soundTracks[scIndex].dispose();
  72395. }
  72396. }
  72397. };
  72398. /**
  72399. * Disables audio in the associated scene.
  72400. */
  72401. AudioSceneComponent.prototype.disableAudio = function () {
  72402. var scene = this.scene;
  72403. this._audioEnabled = false;
  72404. var i;
  72405. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72406. scene.mainSoundTrack.soundCollection[i].pause();
  72407. }
  72408. if (scene.soundTracks) {
  72409. for (i = 0; i < scene.soundTracks.length; i++) {
  72410. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72411. scene.soundTracks[i].soundCollection[j].pause();
  72412. }
  72413. }
  72414. }
  72415. };
  72416. /**
  72417. * Enables audio in the associated scene.
  72418. */
  72419. AudioSceneComponent.prototype.enableAudio = function () {
  72420. var scene = this.scene;
  72421. this._audioEnabled = true;
  72422. var i;
  72423. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72424. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  72425. scene.mainSoundTrack.soundCollection[i].play();
  72426. }
  72427. }
  72428. if (scene.soundTracks) {
  72429. for (i = 0; i < scene.soundTracks.length; i++) {
  72430. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72431. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  72432. scene.soundTracks[i].soundCollection[j].play();
  72433. }
  72434. }
  72435. }
  72436. }
  72437. };
  72438. /**
  72439. * Switch audio to headphone output.
  72440. */
  72441. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  72442. var scene = this.scene;
  72443. this._headphone = true;
  72444. scene.mainSoundTrack.switchPanningModelToHRTF();
  72445. if (scene.soundTracks) {
  72446. for (var i = 0; i < scene.soundTracks.length; i++) {
  72447. scene.soundTracks[i].switchPanningModelToHRTF();
  72448. }
  72449. }
  72450. };
  72451. /**
  72452. * Switch audio to normal speakers.
  72453. */
  72454. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  72455. var scene = this.scene;
  72456. this._headphone = false;
  72457. scene.mainSoundTrack.switchPanningModelToEqualPower();
  72458. if (scene.soundTracks) {
  72459. for (var i = 0; i < scene.soundTracks.length; i++) {
  72460. scene.soundTracks[i].switchPanningModelToEqualPower();
  72461. }
  72462. }
  72463. };
  72464. AudioSceneComponent.prototype._afterRender = function () {
  72465. var scene = this.scene;
  72466. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  72467. return;
  72468. }
  72469. var listeningCamera;
  72470. var audioEngine = BABYLON.Engine.audioEngine;
  72471. if (scene.activeCameras.length > 0) {
  72472. listeningCamera = scene.activeCameras[0];
  72473. }
  72474. else {
  72475. listeningCamera = scene.activeCamera;
  72476. }
  72477. if (listeningCamera && audioEngine.audioContext) {
  72478. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  72479. // for VR cameras
  72480. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  72481. listeningCamera = listeningCamera.rigCameras[0];
  72482. }
  72483. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  72484. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  72485. cameraDirection.normalize();
  72486. // To avoid some errors on GearVR
  72487. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  72488. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  72489. }
  72490. var i;
  72491. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72492. var sound = scene.mainSoundTrack.soundCollection[i];
  72493. if (sound.useCustomAttenuation) {
  72494. sound.updateDistanceFromListener();
  72495. }
  72496. }
  72497. if (scene.soundTracks) {
  72498. for (i = 0; i < scene.soundTracks.length; i++) {
  72499. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72500. sound = scene.soundTracks[i].soundCollection[j];
  72501. if (sound.useCustomAttenuation) {
  72502. sound.updateDistanceFromListener();
  72503. }
  72504. }
  72505. }
  72506. }
  72507. }
  72508. };
  72509. return AudioSceneComponent;
  72510. }());
  72511. BABYLON.AudioSceneComponent = AudioSceneComponent;
  72512. })(BABYLON || (BABYLON = {}));
  72513. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  72514. var BABYLON;
  72515. (function (BABYLON) {
  72516. /**
  72517. * This defines an action helpful to play a defined sound on a triggered action.
  72518. */
  72519. var PlaySoundAction = /** @class */ (function (_super) {
  72520. __extends(PlaySoundAction, _super);
  72521. /**
  72522. * Instantiate the action
  72523. * @param triggerOptions defines the trigger options
  72524. * @param sound defines the sound to play
  72525. * @param condition defines the trigger related conditions
  72526. */
  72527. function PlaySoundAction(triggerOptions, sound, condition) {
  72528. var _this = _super.call(this, triggerOptions, condition) || this;
  72529. _this._sound = sound;
  72530. return _this;
  72531. }
  72532. /** @hidden */
  72533. PlaySoundAction.prototype._prepare = function () {
  72534. };
  72535. /**
  72536. * Execute the action and play the sound.
  72537. */
  72538. PlaySoundAction.prototype.execute = function () {
  72539. if (this._sound !== undefined) {
  72540. this._sound.play();
  72541. }
  72542. };
  72543. /**
  72544. * Serializes the actions and its related information.
  72545. * @param parent defines the object to serialize in
  72546. * @returns the serialized object
  72547. */
  72548. PlaySoundAction.prototype.serialize = function (parent) {
  72549. return _super.prototype._serialize.call(this, {
  72550. name: "PlaySoundAction",
  72551. properties: [{ name: "sound", value: this._sound.name }]
  72552. }, parent);
  72553. };
  72554. return PlaySoundAction;
  72555. }(BABYLON.Action));
  72556. BABYLON.PlaySoundAction = PlaySoundAction;
  72557. /**
  72558. * This defines an action helpful to stop a defined sound on a triggered action.
  72559. */
  72560. var StopSoundAction = /** @class */ (function (_super) {
  72561. __extends(StopSoundAction, _super);
  72562. /**
  72563. * Instantiate the action
  72564. * @param triggerOptions defines the trigger options
  72565. * @param sound defines the sound to stop
  72566. * @param condition defines the trigger related conditions
  72567. */
  72568. function StopSoundAction(triggerOptions, sound, condition) {
  72569. var _this = _super.call(this, triggerOptions, condition) || this;
  72570. _this._sound = sound;
  72571. return _this;
  72572. }
  72573. /** @hidden */
  72574. StopSoundAction.prototype._prepare = function () {
  72575. };
  72576. /**
  72577. * Execute the action and stop the sound.
  72578. */
  72579. StopSoundAction.prototype.execute = function () {
  72580. if (this._sound !== undefined) {
  72581. this._sound.stop();
  72582. }
  72583. };
  72584. /**
  72585. * Serializes the actions and its related information.
  72586. * @param parent defines the object to serialize in
  72587. * @returns the serialized object
  72588. */
  72589. StopSoundAction.prototype.serialize = function (parent) {
  72590. return _super.prototype._serialize.call(this, {
  72591. name: "StopSoundAction",
  72592. properties: [{ name: "sound", value: this._sound.name }]
  72593. }, parent);
  72594. };
  72595. return StopSoundAction;
  72596. }(BABYLON.Action));
  72597. BABYLON.StopSoundAction = StopSoundAction;
  72598. })(BABYLON || (BABYLON = {}));
  72599. //# sourceMappingURL=babylon.directAudioActions.js.map
  72600. var BABYLON;
  72601. (function (BABYLON) {
  72602. /**
  72603. * Class for creating a cube texture
  72604. */
  72605. var CubeTexture = /** @class */ (function (_super) {
  72606. __extends(CubeTexture, _super);
  72607. /**
  72608. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  72609. * as prefiltered data.
  72610. * @param rootUrl defines the url of the texture or the root name of the six images
  72611. * @param scene defines the scene the texture is attached to
  72612. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  72613. * @param noMipmap defines if mipmaps should be created or not
  72614. * @param files defines the six files to load for the different faces
  72615. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  72616. * @param onError defines a callback triggered in case of error during load
  72617. * @param format defines the internal format to use for the texture once loaded
  72618. * @param prefiltered defines whether or not the texture is created from prefiltered data
  72619. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  72620. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72621. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72622. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72623. * @return the cube texture
  72624. */
  72625. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  72626. if (extensions === void 0) { extensions = null; }
  72627. if (noMipmap === void 0) { noMipmap = false; }
  72628. if (files === void 0) { files = null; }
  72629. if (onLoad === void 0) { onLoad = null; }
  72630. if (onError === void 0) { onError = null; }
  72631. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72632. if (prefiltered === void 0) { prefiltered = false; }
  72633. if (forcedExtension === void 0) { forcedExtension = null; }
  72634. if (createPolynomials === void 0) { createPolynomials = false; }
  72635. if (lodScale === void 0) { lodScale = 0.8; }
  72636. if (lodOffset === void 0) { lodOffset = 0; }
  72637. var _this = _super.call(this, scene) || this;
  72638. /**
  72639. * Gets or sets the center of the bounding box associated with the cube texture.
  72640. * It must define where the camera used to render the texture was set
  72641. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72642. */
  72643. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72644. _this._rotationY = 0;
  72645. /** @hidden */
  72646. _this._prefiltered = false;
  72647. _this.name = rootUrl;
  72648. _this.url = rootUrl;
  72649. _this._noMipmap = noMipmap;
  72650. _this.hasAlpha = false;
  72651. _this._format = format;
  72652. _this.isCube = true;
  72653. _this._textureMatrix = BABYLON.Matrix.Identity();
  72654. _this._createPolynomials = createPolynomials;
  72655. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72656. if (!rootUrl && !files) {
  72657. return _this;
  72658. }
  72659. var lastDot = rootUrl.lastIndexOf(".");
  72660. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  72661. var isDDS = (extension === ".dds");
  72662. var isEnv = (extension === ".env");
  72663. if (isEnv) {
  72664. _this.gammaSpace = false;
  72665. _this._prefiltered = false;
  72666. }
  72667. else {
  72668. _this._prefiltered = prefiltered;
  72669. if (prefiltered) {
  72670. _this.gammaSpace = false;
  72671. }
  72672. }
  72673. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  72674. if (!files) {
  72675. if (!isEnv && !isDDS && !extensions) {
  72676. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  72677. }
  72678. files = [];
  72679. if (extensions) {
  72680. for (var index = 0; index < extensions.length; index++) {
  72681. files.push(rootUrl + extensions[index]);
  72682. }
  72683. }
  72684. }
  72685. _this._files = files;
  72686. if (!_this._texture) {
  72687. if (!scene.useDelayedTextureLoading) {
  72688. if (prefiltered) {
  72689. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  72690. }
  72691. else {
  72692. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  72693. }
  72694. }
  72695. else {
  72696. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72697. }
  72698. }
  72699. else if (onLoad) {
  72700. if (_this._texture.isReady) {
  72701. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  72702. }
  72703. else {
  72704. _this._texture.onLoadedObservable.add(onLoad);
  72705. }
  72706. }
  72707. return _this;
  72708. }
  72709. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  72710. /**
  72711. * Returns the bounding box size
  72712. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72713. */
  72714. get: function () {
  72715. return this._boundingBoxSize;
  72716. },
  72717. /**
  72718. * Gets or sets the size of the bounding box associated with the cube texture
  72719. * When defined, the cubemap will switch to local mode
  72720. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72721. * @example https://www.babylonjs-playground.com/#RNASML
  72722. */
  72723. set: function (value) {
  72724. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72725. return;
  72726. }
  72727. this._boundingBoxSize = value;
  72728. var scene = this.getScene();
  72729. if (scene) {
  72730. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72731. }
  72732. },
  72733. enumerable: true,
  72734. configurable: true
  72735. });
  72736. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  72737. /**
  72738. * Gets texture matrix rotation angle around Y axis radians.
  72739. */
  72740. get: function () {
  72741. return this._rotationY;
  72742. },
  72743. /**
  72744. * Sets texture matrix rotation angle around Y axis in radians.
  72745. */
  72746. set: function (value) {
  72747. this._rotationY = value;
  72748. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  72749. },
  72750. enumerable: true,
  72751. configurable: true
  72752. });
  72753. /**
  72754. * Creates a cube texture from an array of image urls
  72755. * @param files defines an array of image urls
  72756. * @param scene defines the hosting scene
  72757. * @param noMipmap specifies if mip maps are not used
  72758. * @returns a cube texture
  72759. */
  72760. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  72761. var rootUrlKey = "";
  72762. files.forEach(function (url) { return rootUrlKey += url; });
  72763. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  72764. };
  72765. /**
  72766. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  72767. * @param url defines the url of the prefiltered texture
  72768. * @param scene defines the scene the texture is attached to
  72769. * @param forcedExtension defines the extension of the file if different from the url
  72770. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72771. * @return the prefiltered texture
  72772. */
  72773. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  72774. if (forcedExtension === void 0) { forcedExtension = null; }
  72775. if (createPolynomials === void 0) { createPolynomials = true; }
  72776. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  72777. };
  72778. /**
  72779. * Delays loading of the cube texture
  72780. */
  72781. CubeTexture.prototype.delayLoad = function () {
  72782. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72783. return;
  72784. }
  72785. var scene = this.getScene();
  72786. if (!scene) {
  72787. return;
  72788. }
  72789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72790. this._texture = this._getFromCache(this.url, this._noMipmap);
  72791. if (!this._texture) {
  72792. if (this._prefiltered) {
  72793. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  72794. }
  72795. else {
  72796. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  72797. }
  72798. }
  72799. };
  72800. /**
  72801. * Returns the reflection texture matrix
  72802. * @returns the reflection texture matrix
  72803. */
  72804. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  72805. return this._textureMatrix;
  72806. };
  72807. /**
  72808. * Sets the reflection texture matrix
  72809. * @param value Reflection texture matrix
  72810. */
  72811. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72812. this._textureMatrix = value;
  72813. };
  72814. /**
  72815. * Parses text to create a cube texture
  72816. * @param parsedTexture define the serialized text to read from
  72817. * @param scene defines the hosting scene
  72818. * @param rootUrl defines the root url of the cube texture
  72819. * @returns a cube texture
  72820. */
  72821. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72822. var texture = BABYLON.SerializationHelper.Parse(function () {
  72823. var prefiltered = false;
  72824. if (parsedTexture.prefiltered) {
  72825. prefiltered = parsedTexture.prefiltered;
  72826. }
  72827. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  72828. }, parsedTexture, scene);
  72829. // Local Cubemaps
  72830. if (parsedTexture.boundingBoxPosition) {
  72831. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72832. }
  72833. if (parsedTexture.boundingBoxSize) {
  72834. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72835. }
  72836. // Animations
  72837. if (parsedTexture.animations) {
  72838. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  72839. var parsedAnimation = parsedTexture.animations[animationIndex];
  72840. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  72841. }
  72842. }
  72843. return texture;
  72844. };
  72845. /**
  72846. * Makes a clone, or deep copy, of the cube texture
  72847. * @returns a new cube texture
  72848. */
  72849. CubeTexture.prototype.clone = function () {
  72850. var _this = this;
  72851. return BABYLON.SerializationHelper.Clone(function () {
  72852. var scene = _this.getScene();
  72853. if (!scene) {
  72854. return _this;
  72855. }
  72856. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  72857. }, this);
  72858. };
  72859. __decorate([
  72860. BABYLON.serialize("rotationY")
  72861. ], CubeTexture.prototype, "rotationY", null);
  72862. return CubeTexture;
  72863. }(BABYLON.BaseTexture));
  72864. BABYLON.CubeTexture = CubeTexture;
  72865. })(BABYLON || (BABYLON = {}));
  72866. //# sourceMappingURL=babylon.cubeTexture.js.map
  72867. var BABYLON;
  72868. (function (BABYLON) {
  72869. /**
  72870. * Raw cube texture where the raw buffers are passed in
  72871. */
  72872. var RawCubeTexture = /** @class */ (function (_super) {
  72873. __extends(RawCubeTexture, _super);
  72874. /**
  72875. * Creates a cube texture where the raw buffers are passed in.
  72876. * @param scene defines the scene the texture is attached to
  72877. * @param data defines the array of data to use to create each face
  72878. * @param size defines the size of the textures
  72879. * @param format defines the format of the data
  72880. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  72881. * @param generateMipMaps defines if the engine should generate the mip levels
  72882. * @param invertY defines if data must be stored with Y axis inverted
  72883. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  72884. * @param compression defines the compression used (null by default)
  72885. */
  72886. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  72887. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72888. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72889. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72890. if (invertY === void 0) { invertY = false; }
  72891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72892. if (compression === void 0) { compression = null; }
  72893. var _this = _super.call(this, "", scene) || this;
  72894. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  72895. return _this;
  72896. }
  72897. /**
  72898. * Updates the raw cube texture.
  72899. * @param data defines the data to store
  72900. * @param format defines the data format
  72901. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  72902. * @param invertY defines if data must be stored with Y axis inverted
  72903. * @param compression defines the compression used (null by default)
  72904. * @param level defines which level of the texture to update
  72905. */
  72906. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  72907. if (compression === void 0) { compression = null; }
  72908. if (level === void 0) { level = 0; }
  72909. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  72910. };
  72911. /**
  72912. * Updates a raw cube texture with RGBD encoded data.
  72913. * @param data defines the array of data [mipmap][face] to use to create each face
  72914. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  72915. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72916. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72917. * @returns a promsie that resolves when the operation is complete
  72918. */
  72919. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  72920. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  72921. if (lodScale === void 0) { lodScale = 0.8; }
  72922. if (lodOffset === void 0) { lodOffset = 0; }
  72923. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  72924. };
  72925. /**
  72926. * Clones the raw cube texture.
  72927. * @return a new cube texture
  72928. */
  72929. RawCubeTexture.prototype.clone = function () {
  72930. var _this = this;
  72931. return BABYLON.SerializationHelper.Clone(function () {
  72932. var scene = _this.getScene();
  72933. var internalTexture = _this._texture;
  72934. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  72935. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  72936. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  72937. }
  72938. return texture;
  72939. }, this);
  72940. };
  72941. /** @hidden */
  72942. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  72943. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  72944. internalTexture._bufferViewArrayArray = data;
  72945. internalTexture._lodGenerationScale = lodScale;
  72946. internalTexture._lodGenerationOffset = lodOffset;
  72947. internalTexture._sphericalPolynomial = sphericalPolynomial;
  72948. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  72949. internalTexture.isReady = true;
  72950. });
  72951. };
  72952. return RawCubeTexture;
  72953. }(BABYLON.CubeTexture));
  72954. BABYLON.RawCubeTexture = RawCubeTexture;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  72957. var BABYLON;
  72958. (function (BABYLON) {
  72959. /**
  72960. * This Helps creating a texture that will be created from a camera in your scene.
  72961. * It is basically a dynamic texture that could be used to create special effects for instance.
  72962. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  72963. */
  72964. var RenderTargetTexture = /** @class */ (function (_super) {
  72965. __extends(RenderTargetTexture, _super);
  72966. /**
  72967. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  72968. * or used a shadow, depth texture...
  72969. * @param name The friendly name of the texture
  72970. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  72971. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  72972. * @param generateMipMaps True if mip maps need to be generated after render.
  72973. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  72974. * @param type The type of the buffer in the RTT (int, half float, float...)
  72975. * @param isCube True if a cube texture needs to be created
  72976. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  72977. * @param generateDepthBuffer True to generate a depth buffer
  72978. * @param generateStencilBuffer True to generate a stencil buffer
  72979. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  72980. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  72981. * @param delayAllocation if the texture allocation should be delayed (default: false)
  72982. */
  72983. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) {
  72984. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  72985. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72986. if (isCube === void 0) { isCube = false; }
  72987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72988. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72989. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  72990. if (isMulti === void 0) { isMulti = false; }
  72991. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72992. if (delayAllocation === void 0) { delayAllocation = false; }
  72993. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72994. _this.isCube = isCube;
  72995. /**
  72996. * Define if particles should be rendered in your texture.
  72997. */
  72998. _this.renderParticles = true;
  72999. /**
  73000. * Define if sprites should be rendered in your texture.
  73001. */
  73002. _this.renderSprites = false;
  73003. /**
  73004. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  73005. */
  73006. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  73007. /**
  73008. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  73009. */
  73010. _this.ignoreCameraViewport = false;
  73011. /**
  73012. * An event triggered when the texture is unbind.
  73013. */
  73014. _this.onBeforeBindObservable = new BABYLON.Observable();
  73015. /**
  73016. * An event triggered when the texture is unbind.
  73017. */
  73018. _this.onAfterUnbindObservable = new BABYLON.Observable();
  73019. /**
  73020. * An event triggered before rendering the texture
  73021. */
  73022. _this.onBeforeRenderObservable = new BABYLON.Observable();
  73023. /**
  73024. * An event triggered after rendering the texture
  73025. */
  73026. _this.onAfterRenderObservable = new BABYLON.Observable();
  73027. /**
  73028. * An event triggered after the texture clear
  73029. */
  73030. _this.onClearObservable = new BABYLON.Observable();
  73031. _this._currentRefreshId = -1;
  73032. _this._refreshRate = 1;
  73033. _this._samples = 1;
  73034. /**
  73035. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  73036. * It must define where the camera used to render the texture is set
  73037. */
  73038. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73039. scene = _this.getScene();
  73040. if (!scene) {
  73041. return _this;
  73042. }
  73043. _this.renderList = new Array();
  73044. _this._engine = scene.getEngine();
  73045. _this.name = name;
  73046. _this.isRenderTarget = true;
  73047. _this._initialSizeParameter = size;
  73048. _this._processSizeParameter(size);
  73049. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  73050. });
  73051. _this._generateMipMaps = generateMipMaps ? true : false;
  73052. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73053. // Rendering groups
  73054. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73055. _this._renderingManager._useSceneAutoClearSetup = true;
  73056. if (isMulti) {
  73057. return _this;
  73058. }
  73059. _this._renderTargetOptions = {
  73060. generateMipMaps: generateMipMaps,
  73061. type: type,
  73062. format: format,
  73063. samplingMode: samplingMode,
  73064. generateDepthBuffer: generateDepthBuffer,
  73065. generateStencilBuffer: generateStencilBuffer
  73066. };
  73067. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  73068. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73069. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73070. }
  73071. if (!delayAllocation) {
  73072. if (isCube) {
  73073. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  73074. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  73075. _this._textureMatrix = BABYLON.Matrix.Identity();
  73076. }
  73077. else {
  73078. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  73079. }
  73080. }
  73081. return _this;
  73082. }
  73083. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  73084. /**
  73085. * Use this list to define the list of mesh you want to render.
  73086. */
  73087. get: function () {
  73088. return this._renderList;
  73089. },
  73090. set: function (value) {
  73091. this._renderList = value;
  73092. if (this._renderList) {
  73093. this._hookArray(this._renderList);
  73094. }
  73095. },
  73096. enumerable: true,
  73097. configurable: true
  73098. });
  73099. RenderTargetTexture.prototype._hookArray = function (array) {
  73100. var _this = this;
  73101. var oldPush = array.push;
  73102. array.push = function () {
  73103. var items = [];
  73104. for (var _i = 0; _i < arguments.length; _i++) {
  73105. items[_i] = arguments[_i];
  73106. }
  73107. var wasEmpty = array.length === 0;
  73108. var result = oldPush.apply(array, items);
  73109. if (wasEmpty) {
  73110. _this.getScene().meshes.forEach(function (mesh) {
  73111. mesh._markSubMeshesAsLightDirty();
  73112. });
  73113. }
  73114. return result;
  73115. };
  73116. var oldSplice = array.splice;
  73117. array.splice = function (index, deleteCount) {
  73118. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73119. if (array.length === 0) {
  73120. _this.getScene().meshes.forEach(function (mesh) {
  73121. mesh._markSubMeshesAsLightDirty();
  73122. });
  73123. }
  73124. return deleted;
  73125. };
  73126. };
  73127. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  73128. /**
  73129. * Set a after unbind callback in the texture.
  73130. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  73131. */
  73132. set: function (callback) {
  73133. if (this._onAfterUnbindObserver) {
  73134. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  73135. }
  73136. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  73137. },
  73138. enumerable: true,
  73139. configurable: true
  73140. });
  73141. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  73142. /**
  73143. * Set a before render callback in the texture.
  73144. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  73145. */
  73146. set: function (callback) {
  73147. if (this._onBeforeRenderObserver) {
  73148. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73149. }
  73150. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73151. },
  73152. enumerable: true,
  73153. configurable: true
  73154. });
  73155. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  73156. /**
  73157. * Set a after render callback in the texture.
  73158. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  73159. */
  73160. set: function (callback) {
  73161. if (this._onAfterRenderObserver) {
  73162. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73163. }
  73164. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73165. },
  73166. enumerable: true,
  73167. configurable: true
  73168. });
  73169. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  73170. /**
  73171. * Set a clear callback in the texture.
  73172. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  73173. */
  73174. set: function (callback) {
  73175. if (this._onClearObserver) {
  73176. this.onClearObservable.remove(this._onClearObserver);
  73177. }
  73178. this._onClearObserver = this.onClearObservable.add(callback);
  73179. },
  73180. enumerable: true,
  73181. configurable: true
  73182. });
  73183. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  73184. /**
  73185. * Gets render target creation options that were used.
  73186. */
  73187. get: function () {
  73188. return this._renderTargetOptions;
  73189. },
  73190. enumerable: true,
  73191. configurable: true
  73192. });
  73193. RenderTargetTexture.prototype._onRatioRescale = function () {
  73194. if (this._sizeRatio) {
  73195. this.resize(this._initialSizeParameter);
  73196. }
  73197. };
  73198. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  73199. get: function () {
  73200. return this._boundingBoxSize;
  73201. },
  73202. /**
  73203. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  73204. * When defined, the cubemap will switch to local mode
  73205. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73206. * @example https://www.babylonjs-playground.com/#RNASML
  73207. */
  73208. set: function (value) {
  73209. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73210. return;
  73211. }
  73212. this._boundingBoxSize = value;
  73213. var scene = this.getScene();
  73214. if (scene) {
  73215. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73216. }
  73217. },
  73218. enumerable: true,
  73219. configurable: true
  73220. });
  73221. /**
  73222. * Creates a depth stencil texture.
  73223. * This is only available in WebGL 2 or with the depth texture extension available.
  73224. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  73225. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  73226. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  73227. */
  73228. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  73229. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  73230. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  73231. if (generateStencil === void 0) { generateStencil = false; }
  73232. if (!this.getScene()) {
  73233. return;
  73234. }
  73235. var engine = this.getScene().getEngine();
  73236. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  73237. bilinearFiltering: bilinearFiltering,
  73238. comparisonFunction: comparisonFunction,
  73239. generateStencil: generateStencil,
  73240. isCube: this.isCube
  73241. });
  73242. engine.setFrameBufferDepthStencilTexture(this);
  73243. };
  73244. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  73245. if (size.ratio) {
  73246. this._sizeRatio = size.ratio;
  73247. this._size = {
  73248. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  73249. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  73250. };
  73251. }
  73252. else {
  73253. this._size = size;
  73254. }
  73255. };
  73256. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  73257. /**
  73258. * Define the number of samples to use in case of MSAA.
  73259. * It defaults to one meaning no MSAA has been enabled.
  73260. */
  73261. get: function () {
  73262. return this._samples;
  73263. },
  73264. set: function (value) {
  73265. if (this._samples === value) {
  73266. return;
  73267. }
  73268. var scene = this.getScene();
  73269. if (!scene) {
  73270. return;
  73271. }
  73272. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  73273. },
  73274. enumerable: true,
  73275. configurable: true
  73276. });
  73277. /**
  73278. * Resets the refresh counter of the texture and start bak from scratch.
  73279. * Could be usefull to regenerate the texture if it is setup to render only once.
  73280. */
  73281. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  73282. this._currentRefreshId = -1;
  73283. };
  73284. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  73285. /**
  73286. * Define the refresh rate of the texture or the rendering frequency.
  73287. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73288. */
  73289. get: function () {
  73290. return this._refreshRate;
  73291. },
  73292. set: function (value) {
  73293. this._refreshRate = value;
  73294. this.resetRefreshCounter();
  73295. },
  73296. enumerable: true,
  73297. configurable: true
  73298. });
  73299. /**
  73300. * Adds a post process to the render target rendering passes.
  73301. * @param postProcess define the post process to add
  73302. */
  73303. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  73304. if (!this._postProcessManager) {
  73305. var scene = this.getScene();
  73306. if (!scene) {
  73307. return;
  73308. }
  73309. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  73310. this._postProcesses = new Array();
  73311. }
  73312. this._postProcesses.push(postProcess);
  73313. this._postProcesses[0].autoClear = false;
  73314. };
  73315. /**
  73316. * Clear all the post processes attached to the render target
  73317. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  73318. */
  73319. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  73320. if (dispose === void 0) { dispose = false; }
  73321. if (!this._postProcesses) {
  73322. return;
  73323. }
  73324. if (dispose) {
  73325. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  73326. var postProcess = _a[_i];
  73327. postProcess.dispose();
  73328. }
  73329. }
  73330. this._postProcesses = [];
  73331. };
  73332. /**
  73333. * Remove one of the post process from the list of attached post processes to the texture
  73334. * @param postProcess define the post process to remove from the list
  73335. */
  73336. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  73337. if (!this._postProcesses) {
  73338. return;
  73339. }
  73340. var index = this._postProcesses.indexOf(postProcess);
  73341. if (index === -1) {
  73342. return;
  73343. }
  73344. this._postProcesses.splice(index, 1);
  73345. if (this._postProcesses.length > 0) {
  73346. this._postProcesses[0].autoClear = false;
  73347. }
  73348. };
  73349. /** @hidden */
  73350. RenderTargetTexture.prototype._shouldRender = function () {
  73351. if (this._currentRefreshId === -1) { // At least render once
  73352. this._currentRefreshId = 1;
  73353. return true;
  73354. }
  73355. if (this.refreshRate === this._currentRefreshId) {
  73356. this._currentRefreshId = 1;
  73357. return true;
  73358. }
  73359. this._currentRefreshId++;
  73360. return false;
  73361. };
  73362. /**
  73363. * Gets the actual render size of the texture.
  73364. * @returns the width of the render size
  73365. */
  73366. RenderTargetTexture.prototype.getRenderSize = function () {
  73367. return this.getRenderWidth();
  73368. };
  73369. /**
  73370. * Gets the actual render width of the texture.
  73371. * @returns the width of the render size
  73372. */
  73373. RenderTargetTexture.prototype.getRenderWidth = function () {
  73374. if (this._size.width) {
  73375. return this._size.width;
  73376. }
  73377. return this._size;
  73378. };
  73379. /**
  73380. * Gets the actual render height of the texture.
  73381. * @returns the height of the render size
  73382. */
  73383. RenderTargetTexture.prototype.getRenderHeight = function () {
  73384. if (this._size.width) {
  73385. return this._size.height;
  73386. }
  73387. return this._size;
  73388. };
  73389. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  73390. /**
  73391. * Get if the texture can be rescaled or not.
  73392. */
  73393. get: function () {
  73394. return true;
  73395. },
  73396. enumerable: true,
  73397. configurable: true
  73398. });
  73399. /**
  73400. * Resize the texture using a ratio.
  73401. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  73402. */
  73403. RenderTargetTexture.prototype.scale = function (ratio) {
  73404. var newSize = this.getRenderSize() * ratio;
  73405. this.resize(newSize);
  73406. };
  73407. /**
  73408. * Get the texture reflection matrix used to rotate/transform the reflection.
  73409. * @returns the reflection matrix
  73410. */
  73411. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  73412. if (this.isCube) {
  73413. return this._textureMatrix;
  73414. }
  73415. return _super.prototype.getReflectionTextureMatrix.call(this);
  73416. };
  73417. /**
  73418. * Resize the texture to a new desired size.
  73419. * Be carrefull as it will recreate all the data in the new texture.
  73420. * @param size Define the new size. It can be:
  73421. * - a number for squared texture,
  73422. * - an object containing { width: number, height: number }
  73423. * - or an object containing a ratio { ratio: number }
  73424. */
  73425. RenderTargetTexture.prototype.resize = function (size) {
  73426. this.releaseInternalTexture();
  73427. var scene = this.getScene();
  73428. if (!scene) {
  73429. return;
  73430. }
  73431. this._processSizeParameter(size);
  73432. if (this.isCube) {
  73433. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  73434. }
  73435. else {
  73436. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  73437. }
  73438. };
  73439. /**
  73440. * Renders all the objects from the render list into the texture.
  73441. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  73442. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  73443. */
  73444. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  73445. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  73446. if (dumpForDebug === void 0) { dumpForDebug = false; }
  73447. var scene = this.getScene();
  73448. if (!scene) {
  73449. return;
  73450. }
  73451. var engine = scene.getEngine();
  73452. if (this.useCameraPostProcesses !== undefined) {
  73453. useCameraPostProcess = this.useCameraPostProcesses;
  73454. }
  73455. if (this._waitingRenderList) {
  73456. this.renderList = [];
  73457. for (var index = 0; index < this._waitingRenderList.length; index++) {
  73458. var id = this._waitingRenderList[index];
  73459. var mesh_1 = scene.getMeshByID(id);
  73460. if (mesh_1) {
  73461. this.renderList.push(mesh_1);
  73462. }
  73463. }
  73464. delete this._waitingRenderList;
  73465. }
  73466. // Is predicate defined?
  73467. if (this.renderListPredicate) {
  73468. if (this.renderList) {
  73469. this.renderList.length = 0; // Clear previous renderList
  73470. }
  73471. else {
  73472. this.renderList = [];
  73473. }
  73474. var scene = this.getScene();
  73475. if (!scene) {
  73476. return;
  73477. }
  73478. var sceneMeshes = scene.meshes;
  73479. for (var index = 0; index < sceneMeshes.length; index++) {
  73480. var mesh = sceneMeshes[index];
  73481. if (this.renderListPredicate(mesh)) {
  73482. this.renderList.push(mesh);
  73483. }
  73484. }
  73485. }
  73486. this.onBeforeBindObservable.notifyObservers(this);
  73487. // Set custom projection.
  73488. // Needs to be before binding to prevent changing the aspect ratio.
  73489. var camera;
  73490. if (this.activeCamera) {
  73491. camera = this.activeCamera;
  73492. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73493. if (this.activeCamera !== scene.activeCamera) {
  73494. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  73495. }
  73496. }
  73497. else {
  73498. camera = scene.activeCamera;
  73499. if (camera) {
  73500. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73501. }
  73502. }
  73503. // Prepare renderingManager
  73504. this._renderingManager.reset();
  73505. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  73506. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  73507. var sceneRenderId = scene.getRenderId();
  73508. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  73509. var mesh = currentRenderList[meshIndex];
  73510. if (mesh) {
  73511. if (!mesh.isReady(this.refreshRate === 0)) {
  73512. this.resetRefreshCounter();
  73513. continue;
  73514. }
  73515. mesh._preActivateForIntermediateRendering(sceneRenderId);
  73516. var isMasked = void 0;
  73517. if (!this.renderList && camera) {
  73518. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  73519. }
  73520. else {
  73521. isMasked = false;
  73522. }
  73523. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  73524. mesh._activate(sceneRenderId);
  73525. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  73526. var subMesh = mesh.subMeshes[subIndex];
  73527. scene._activeIndices.addCount(subMesh.indexCount, false);
  73528. this._renderingManager.dispatch(subMesh, mesh);
  73529. }
  73530. }
  73531. }
  73532. }
  73533. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  73534. var particleSystem = scene.particleSystems[particleIndex];
  73535. var emitter = particleSystem.emitter;
  73536. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  73537. continue;
  73538. }
  73539. if (currentRenderList.indexOf(emitter) >= 0) {
  73540. this._renderingManager.dispatchParticles(particleSystem);
  73541. }
  73542. }
  73543. if (this.isCube) {
  73544. for (var face = 0; face < 6; face++) {
  73545. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73546. scene.incrementRenderId();
  73547. scene.resetCachedMaterial();
  73548. }
  73549. }
  73550. else {
  73551. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73552. }
  73553. this.onAfterUnbindObservable.notifyObservers(this);
  73554. if (scene.activeCamera) {
  73555. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  73556. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  73557. }
  73558. engine.setViewport(scene.activeCamera.viewport);
  73559. }
  73560. scene.resetCachedMaterial();
  73561. };
  73562. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  73563. var minimum = 128;
  73564. var x = renderDimension * scale;
  73565. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  73566. // Ensure we don't exceed the render dimension (while staying POT)
  73567. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  73568. };
  73569. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73570. var _this = this;
  73571. if (!this._texture) {
  73572. return;
  73573. }
  73574. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  73575. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73576. });
  73577. };
  73578. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  73579. var scene = this.getScene();
  73580. if (!scene) {
  73581. return;
  73582. }
  73583. var engine = scene.getEngine();
  73584. if (!this._texture) {
  73585. return;
  73586. }
  73587. // Bind
  73588. if (this._postProcessManager) {
  73589. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  73590. }
  73591. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  73592. if (this._texture) {
  73593. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  73594. }
  73595. }
  73596. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  73597. // Clear
  73598. if (this.onClearObservable.hasObservers()) {
  73599. this.onClearObservable.notifyObservers(engine);
  73600. }
  73601. else {
  73602. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  73603. }
  73604. if (!this._doNotChangeAspectRatio) {
  73605. scene.updateTransformMatrix(true);
  73606. }
  73607. // Render
  73608. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  73609. if (this._postProcessManager) {
  73610. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  73611. }
  73612. else if (useCameraPostProcess) {
  73613. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  73614. }
  73615. if (!this._doNotChangeAspectRatio) {
  73616. scene.updateTransformMatrix(true);
  73617. }
  73618. // Dump ?
  73619. if (dumpForDebug) {
  73620. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  73621. }
  73622. // Unbind
  73623. if (!this.isCube || faceIndex === 5) {
  73624. if (this.isCube) {
  73625. if (faceIndex === 5) {
  73626. engine.generateMipMapsForCubemap(this._texture);
  73627. }
  73628. }
  73629. this.unbindFrameBuffer(engine, faceIndex);
  73630. }
  73631. else {
  73632. this.onAfterRenderObservable.notifyObservers(faceIndex);
  73633. }
  73634. };
  73635. /**
  73636. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  73637. * This allowed control for front to back rendering or reversly depending of the special needs.
  73638. *
  73639. * @param renderingGroupId The rendering group id corresponding to its index
  73640. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  73641. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  73642. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  73643. */
  73644. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  73645. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  73646. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  73647. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  73648. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  73649. };
  73650. /**
  73651. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73652. *
  73653. * @param renderingGroupId The rendering group id corresponding to its index
  73654. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73655. */
  73656. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73657. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73658. this._renderingManager._useSceneAutoClearSetup = false;
  73659. };
  73660. /**
  73661. * Clones the texture.
  73662. * @returns the cloned texture
  73663. */
  73664. RenderTargetTexture.prototype.clone = function () {
  73665. var textureSize = this.getSize();
  73666. 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);
  73667. // Base texture
  73668. newTexture.hasAlpha = this.hasAlpha;
  73669. newTexture.level = this.level;
  73670. // RenderTarget Texture
  73671. newTexture.coordinatesMode = this.coordinatesMode;
  73672. if (this.renderList) {
  73673. newTexture.renderList = this.renderList.slice(0);
  73674. }
  73675. return newTexture;
  73676. };
  73677. /**
  73678. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  73679. * @returns The JSON representation of the texture
  73680. */
  73681. RenderTargetTexture.prototype.serialize = function () {
  73682. if (!this.name) {
  73683. return null;
  73684. }
  73685. var serializationObject = _super.prototype.serialize.call(this);
  73686. serializationObject.renderTargetSize = this.getRenderSize();
  73687. serializationObject.renderList = [];
  73688. if (this.renderList) {
  73689. for (var index = 0; index < this.renderList.length; index++) {
  73690. serializationObject.renderList.push(this.renderList[index].id);
  73691. }
  73692. }
  73693. return serializationObject;
  73694. };
  73695. /**
  73696. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  73697. */
  73698. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  73699. var objBuffer = this.getInternalTexture();
  73700. var scene = this.getScene();
  73701. if (objBuffer && scene) {
  73702. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  73703. }
  73704. };
  73705. /**
  73706. * Dispose the texture and release its associated resources.
  73707. */
  73708. RenderTargetTexture.prototype.dispose = function () {
  73709. if (this._postProcessManager) {
  73710. this._postProcessManager.dispose();
  73711. this._postProcessManager = null;
  73712. }
  73713. this.clearPostProcesses(true);
  73714. if (this._resizeObserver) {
  73715. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  73716. this._resizeObserver = null;
  73717. }
  73718. this.renderList = null;
  73719. // Remove from custom render targets
  73720. var scene = this.getScene();
  73721. if (!scene) {
  73722. return;
  73723. }
  73724. var index = scene.customRenderTargets.indexOf(this);
  73725. if (index >= 0) {
  73726. scene.customRenderTargets.splice(index, 1);
  73727. }
  73728. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  73729. var camera = _a[_i];
  73730. index = camera.customRenderTargets.indexOf(this);
  73731. if (index >= 0) {
  73732. camera.customRenderTargets.splice(index, 1);
  73733. }
  73734. }
  73735. _super.prototype.dispose.call(this);
  73736. };
  73737. /** @hidden */
  73738. RenderTargetTexture.prototype._rebuild = function () {
  73739. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73740. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73741. }
  73742. if (this._postProcessManager) {
  73743. this._postProcessManager._rebuild();
  73744. }
  73745. };
  73746. /**
  73747. * Clear the info related to rendering groups preventing retention point in material dispose.
  73748. */
  73749. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  73750. if (this._renderingManager) {
  73751. this._renderingManager.freeRenderingGroups();
  73752. }
  73753. };
  73754. /**
  73755. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  73756. */
  73757. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  73758. /**
  73759. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  73760. */
  73761. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  73762. /**
  73763. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  73764. * the central point of your effect and can save a lot of performances.
  73765. */
  73766. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  73767. return RenderTargetTexture;
  73768. }(BABYLON.Texture));
  73769. BABYLON.RenderTargetTexture = RenderTargetTexture;
  73770. })(BABYLON || (BABYLON = {}));
  73771. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  73772. var BABYLON;
  73773. (function (BABYLON) {
  73774. /**
  73775. * A multi render target, like a render target provides the ability to render to a texture.
  73776. * Unlike the render target, it can render to several draw buffers in one draw.
  73777. * This is specially interesting in deferred rendering or for any effects requiring more than
  73778. * just one color from a single pass.
  73779. */
  73780. var MultiRenderTarget = /** @class */ (function (_super) {
  73781. __extends(MultiRenderTarget, _super);
  73782. /**
  73783. * Instantiate a new multi render target texture.
  73784. * A multi render target, like a render target provides the ability to render to a texture.
  73785. * Unlike the render target, it can render to several draw buffers in one draw.
  73786. * This is specially interesting in deferred rendering or for any effects requiring more than
  73787. * just one color from a single pass.
  73788. * @param name Define the name of the texture
  73789. * @param size Define the size of the buffers to render to
  73790. * @param count Define the number of target we are rendering into
  73791. * @param scene Define the scene the texture belongs to
  73792. * @param options Define the options used to create the multi render target
  73793. */
  73794. function MultiRenderTarget(name, size, count, scene, options) {
  73795. var _this = this;
  73796. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  73797. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  73798. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  73799. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  73800. _this._engine = scene.getEngine();
  73801. if (!_this.isSupported) {
  73802. _this.dispose();
  73803. return;
  73804. }
  73805. var types = [];
  73806. var samplingModes = [];
  73807. for (var i = 0; i < count; i++) {
  73808. if (options && options.types && options.types[i] !== undefined) {
  73809. types.push(options.types[i]);
  73810. }
  73811. else {
  73812. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73813. }
  73814. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  73815. samplingModes.push(options.samplingModes[i]);
  73816. }
  73817. else {
  73818. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73819. }
  73820. }
  73821. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73822. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  73823. _this._size = size;
  73824. _this._multiRenderTargetOptions = {
  73825. samplingModes: samplingModes,
  73826. generateMipMaps: generateMipMaps,
  73827. generateDepthBuffer: generateDepthBuffer,
  73828. generateStencilBuffer: generateStencilBuffer,
  73829. generateDepthTexture: generateDepthTexture,
  73830. types: types,
  73831. textureCount: count
  73832. };
  73833. _this._createInternalTextures();
  73834. _this._createTextures();
  73835. return _this;
  73836. }
  73837. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  73838. /**
  73839. * Get if draw buffers are currently supported by the used hardware and browser.
  73840. */
  73841. get: function () {
  73842. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  73843. },
  73844. enumerable: true,
  73845. configurable: true
  73846. });
  73847. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  73848. /**
  73849. * Get the list of textures generated by the multi render target.
  73850. */
  73851. get: function () {
  73852. return this._textures;
  73853. },
  73854. enumerable: true,
  73855. configurable: true
  73856. });
  73857. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  73858. /**
  73859. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  73860. */
  73861. get: function () {
  73862. return this._textures[this._textures.length - 1];
  73863. },
  73864. enumerable: true,
  73865. configurable: true
  73866. });
  73867. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  73868. /**
  73869. * Set the wrapping mode on U of all the textures we are rendering to.
  73870. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73871. */
  73872. set: function (wrap) {
  73873. if (this._textures) {
  73874. for (var i = 0; i < this._textures.length; i++) {
  73875. this._textures[i].wrapU = wrap;
  73876. }
  73877. }
  73878. },
  73879. enumerable: true,
  73880. configurable: true
  73881. });
  73882. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  73883. /**
  73884. * Set the wrapping mode on V of all the textures we are rendering to.
  73885. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73886. */
  73887. set: function (wrap) {
  73888. if (this._textures) {
  73889. for (var i = 0; i < this._textures.length; i++) {
  73890. this._textures[i].wrapV = wrap;
  73891. }
  73892. }
  73893. },
  73894. enumerable: true,
  73895. configurable: true
  73896. });
  73897. /** @hidden */
  73898. MultiRenderTarget.prototype._rebuild = function () {
  73899. this.releaseInternalTextures();
  73900. this._createInternalTextures();
  73901. for (var i = 0; i < this._internalTextures.length; i++) {
  73902. var texture = this._textures[i];
  73903. texture._texture = this._internalTextures[i];
  73904. }
  73905. // Keeps references to frame buffer and stencil/depth buffer
  73906. this._texture = this._internalTextures[0];
  73907. };
  73908. MultiRenderTarget.prototype._createInternalTextures = function () {
  73909. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  73910. };
  73911. MultiRenderTarget.prototype._createTextures = function () {
  73912. this._textures = [];
  73913. for (var i = 0; i < this._internalTextures.length; i++) {
  73914. var texture = new BABYLON.Texture(null, this.getScene());
  73915. texture._texture = this._internalTextures[i];
  73916. this._textures.push(texture);
  73917. }
  73918. // Keeps references to frame buffer and stencil/depth buffer
  73919. this._texture = this._internalTextures[0];
  73920. };
  73921. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  73922. /**
  73923. * Define the number of samples used if MSAA is enabled.
  73924. */
  73925. get: function () {
  73926. return this._samples;
  73927. },
  73928. set: function (value) {
  73929. if (this._samples === value) {
  73930. return;
  73931. }
  73932. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  73933. },
  73934. enumerable: true,
  73935. configurable: true
  73936. });
  73937. /**
  73938. * Resize all the textures in the multi render target.
  73939. * Be carrefull as it will recreate all the data in the new texture.
  73940. * @param size Define the new size
  73941. */
  73942. MultiRenderTarget.prototype.resize = function (size) {
  73943. this.releaseInternalTextures();
  73944. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  73945. this._createInternalTextures();
  73946. };
  73947. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73948. var _this = this;
  73949. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  73950. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73951. });
  73952. };
  73953. /**
  73954. * Dispose the render targets and their associated resources
  73955. */
  73956. MultiRenderTarget.prototype.dispose = function () {
  73957. this.releaseInternalTextures();
  73958. _super.prototype.dispose.call(this);
  73959. };
  73960. /**
  73961. * Release all the underlying texture used as draw buffers.
  73962. */
  73963. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  73964. if (!this._internalTextures) {
  73965. return;
  73966. }
  73967. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  73968. if (this._internalTextures[i] !== undefined) {
  73969. this._internalTextures[i].dispose();
  73970. this._internalTextures.splice(i, 1);
  73971. }
  73972. }
  73973. };
  73974. return MultiRenderTarget;
  73975. }(BABYLON.RenderTargetTexture));
  73976. BABYLON.MultiRenderTarget = MultiRenderTarget;
  73977. })(BABYLON || (BABYLON = {}));
  73978. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  73979. var BABYLON;
  73980. (function (BABYLON) {
  73981. /**
  73982. * Mirror texture can be used to simulate the view from a mirror in a scene.
  73983. * It will dynamically be rendered every frame to adapt to the camera point of view.
  73984. * You can then easily use it as a reflectionTexture on a flat surface.
  73985. * In case the surface is not a plane, please consider relying on reflection probes.
  73986. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73987. */
  73988. var MirrorTexture = /** @class */ (function (_super) {
  73989. __extends(MirrorTexture, _super);
  73990. /**
  73991. * Instantiates a Mirror Texture.
  73992. * Mirror texture can be used to simulate the view from a mirror in a scene.
  73993. * It will dynamically be rendered every frame to adapt to the camera point of view.
  73994. * You can then easily use it as a reflectionTexture on a flat surface.
  73995. * In case the surface is not a plane, please consider relying on reflection probes.
  73996. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  73997. * @param name
  73998. * @param size
  73999. * @param scene
  74000. * @param generateMipMaps
  74001. * @param type
  74002. * @param samplingMode
  74003. * @param generateDepthBuffer
  74004. */
  74005. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  74006. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74008. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  74009. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  74010. _this.scene = scene;
  74011. /**
  74012. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  74013. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  74014. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74015. */
  74016. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  74017. _this._transformMatrix = BABYLON.Matrix.Zero();
  74018. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  74019. _this._adaptiveBlurKernel = 0;
  74020. _this._blurKernelX = 0;
  74021. _this._blurKernelY = 0;
  74022. _this._blurRatio = 1.0;
  74023. _this.ignoreCameraViewport = true;
  74024. _this._updateGammaSpace();
  74025. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74026. _this._updateGammaSpace;
  74027. });
  74028. _this.onBeforeRenderObservable.add(function () {
  74029. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  74030. _this._savedViewMatrix = scene.getViewMatrix();
  74031. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  74032. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  74033. scene.clipPlane = _this.mirrorPlane;
  74034. scene.getEngine().cullBackFaces = false;
  74035. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  74036. });
  74037. _this.onAfterRenderObservable.add(function () {
  74038. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  74039. scene.getEngine().cullBackFaces = true;
  74040. scene._mirroredCameraPosition = null;
  74041. delete scene.clipPlane;
  74042. });
  74043. return _this;
  74044. }
  74045. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  74046. get: function () {
  74047. return this._blurRatio;
  74048. },
  74049. /**
  74050. * Define the blur ratio used to blur the reflection if needed.
  74051. */
  74052. set: function (value) {
  74053. if (this._blurRatio === value) {
  74054. return;
  74055. }
  74056. this._blurRatio = value;
  74057. this._preparePostProcesses();
  74058. },
  74059. enumerable: true,
  74060. configurable: true
  74061. });
  74062. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  74063. /**
  74064. * Define the adaptive blur kernel used to blur the reflection if needed.
  74065. * This will autocompute the closest best match for the `blurKernel`
  74066. */
  74067. set: function (value) {
  74068. this._adaptiveBlurKernel = value;
  74069. this._autoComputeBlurKernel();
  74070. },
  74071. enumerable: true,
  74072. configurable: true
  74073. });
  74074. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  74075. /**
  74076. * Define the blur kernel used to blur the reflection if needed.
  74077. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74078. */
  74079. set: function (value) {
  74080. this.blurKernelX = value;
  74081. this.blurKernelY = value;
  74082. },
  74083. enumerable: true,
  74084. configurable: true
  74085. });
  74086. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  74087. get: function () {
  74088. return this._blurKernelX;
  74089. },
  74090. /**
  74091. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  74092. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74093. */
  74094. set: function (value) {
  74095. if (this._blurKernelX === value) {
  74096. return;
  74097. }
  74098. this._blurKernelX = value;
  74099. this._preparePostProcesses();
  74100. },
  74101. enumerable: true,
  74102. configurable: true
  74103. });
  74104. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  74105. get: function () {
  74106. return this._blurKernelY;
  74107. },
  74108. /**
  74109. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  74110. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74111. */
  74112. set: function (value) {
  74113. if (this._blurKernelY === value) {
  74114. return;
  74115. }
  74116. this._blurKernelY = value;
  74117. this._preparePostProcesses();
  74118. },
  74119. enumerable: true,
  74120. configurable: true
  74121. });
  74122. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  74123. var engine = this.getScene().getEngine();
  74124. var dw = this.getRenderWidth() / engine.getRenderWidth();
  74125. var dh = this.getRenderHeight() / engine.getRenderHeight();
  74126. this.blurKernelX = this._adaptiveBlurKernel * dw;
  74127. this.blurKernelY = this._adaptiveBlurKernel * dh;
  74128. };
  74129. MirrorTexture.prototype._onRatioRescale = function () {
  74130. if (this._sizeRatio) {
  74131. this.resize(this._initialSizeParameter);
  74132. if (!this._adaptiveBlurKernel) {
  74133. this._preparePostProcesses();
  74134. }
  74135. }
  74136. if (this._adaptiveBlurKernel) {
  74137. this._autoComputeBlurKernel();
  74138. }
  74139. };
  74140. MirrorTexture.prototype._updateGammaSpace = function () {
  74141. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  74142. };
  74143. MirrorTexture.prototype._preparePostProcesses = function () {
  74144. this.clearPostProcesses(true);
  74145. if (this._blurKernelX && this._blurKernelY) {
  74146. var engine = this.getScene().getEngine();
  74147. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74148. 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);
  74149. this._blurX.autoClear = false;
  74150. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  74151. this._blurX.inputTexture = this._texture;
  74152. }
  74153. else {
  74154. this._blurX.alwaysForcePOT = true;
  74155. }
  74156. 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);
  74157. this._blurY.autoClear = false;
  74158. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  74159. this.addPostProcess(this._blurX);
  74160. this.addPostProcess(this._blurY);
  74161. }
  74162. else {
  74163. if (this._blurY) {
  74164. this.removePostProcess(this._blurY);
  74165. this._blurY.dispose();
  74166. this._blurY = null;
  74167. }
  74168. if (this._blurX) {
  74169. this.removePostProcess(this._blurX);
  74170. this._blurX.dispose();
  74171. this._blurX = null;
  74172. }
  74173. }
  74174. };
  74175. /**
  74176. * Clone the mirror texture.
  74177. * @returns the cloned texture
  74178. */
  74179. MirrorTexture.prototype.clone = function () {
  74180. var scene = this.getScene();
  74181. if (!scene) {
  74182. return this;
  74183. }
  74184. var textureSize = this.getSize();
  74185. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  74186. // Base texture
  74187. newTexture.hasAlpha = this.hasAlpha;
  74188. newTexture.level = this.level;
  74189. // Mirror Texture
  74190. newTexture.mirrorPlane = this.mirrorPlane.clone();
  74191. if (this.renderList) {
  74192. newTexture.renderList = this.renderList.slice(0);
  74193. }
  74194. return newTexture;
  74195. };
  74196. /**
  74197. * Serialize the texture to a JSON representation you could use in Parse later on
  74198. * @returns the serialized JSON representation
  74199. */
  74200. MirrorTexture.prototype.serialize = function () {
  74201. if (!this.name) {
  74202. return null;
  74203. }
  74204. var serializationObject = _super.prototype.serialize.call(this);
  74205. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  74206. return serializationObject;
  74207. };
  74208. /**
  74209. * Dispose the texture and release its associated resources.
  74210. */
  74211. MirrorTexture.prototype.dispose = function () {
  74212. _super.prototype.dispose.call(this);
  74213. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  74214. };
  74215. return MirrorTexture;
  74216. }(BABYLON.RenderTargetTexture));
  74217. BABYLON.MirrorTexture = MirrorTexture;
  74218. })(BABYLON || (BABYLON = {}));
  74219. //# sourceMappingURL=babylon.mirrorTexture.js.map
  74220. var BABYLON;
  74221. (function (BABYLON) {
  74222. /**
  74223. * Creates a refraction texture used by refraction channel of the standard material.
  74224. * It is like a mirror but to see through a material.
  74225. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74226. */
  74227. var RefractionTexture = /** @class */ (function (_super) {
  74228. __extends(RefractionTexture, _super);
  74229. /**
  74230. * Creates a refraction texture used by refraction channel of the standard material.
  74231. * It is like a mirror but to see through a material.
  74232. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74233. * @param name Define the texture name
  74234. * @param size Define the size of the underlying texture
  74235. * @param scene Define the scene the refraction belongs to
  74236. * @param generateMipMaps Define if we need to generate mips level for the refraction
  74237. */
  74238. function RefractionTexture(name, size, scene, generateMipMaps) {
  74239. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  74240. /**
  74241. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  74242. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  74243. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74244. */
  74245. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  74246. /**
  74247. * Define how deep under the surface we should see.
  74248. */
  74249. _this.depth = 2.0;
  74250. _this.onBeforeRenderObservable.add(function () {
  74251. scene.clipPlane = _this.refractionPlane;
  74252. });
  74253. _this.onAfterRenderObservable.add(function () {
  74254. delete scene.clipPlane;
  74255. });
  74256. return _this;
  74257. }
  74258. /**
  74259. * Clone the refraction texture.
  74260. * @returns the cloned texture
  74261. */
  74262. RefractionTexture.prototype.clone = function () {
  74263. var scene = this.getScene();
  74264. if (!scene) {
  74265. return this;
  74266. }
  74267. var textureSize = this.getSize();
  74268. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  74269. // Base texture
  74270. newTexture.hasAlpha = this.hasAlpha;
  74271. newTexture.level = this.level;
  74272. // Refraction Texture
  74273. newTexture.refractionPlane = this.refractionPlane.clone();
  74274. if (this.renderList) {
  74275. newTexture.renderList = this.renderList.slice(0);
  74276. }
  74277. newTexture.depth = this.depth;
  74278. return newTexture;
  74279. };
  74280. /**
  74281. * Serialize the texture to a JSON representation you could use in Parse later on
  74282. * @returns the serialized JSON representation
  74283. */
  74284. RefractionTexture.prototype.serialize = function () {
  74285. if (!this.name) {
  74286. return null;
  74287. }
  74288. var serializationObject = _super.prototype.serialize.call(this);
  74289. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  74290. serializationObject.depth = this.depth;
  74291. return serializationObject;
  74292. };
  74293. return RefractionTexture;
  74294. }(BABYLON.RenderTargetTexture));
  74295. BABYLON.RefractionTexture = RefractionTexture;
  74296. })(BABYLON || (BABYLON = {}));
  74297. //# sourceMappingURL=babylon.refractionTexture.js.map
  74298. var BABYLON;
  74299. (function (BABYLON) {
  74300. /**
  74301. * A class extending Texture allowing drawing on a texture
  74302. * @see http://doc.babylonjs.com/how_to/dynamictexture
  74303. */
  74304. var DynamicTexture = /** @class */ (function (_super) {
  74305. __extends(DynamicTexture, _super);
  74306. /**
  74307. * Creates a DynamicTexture
  74308. * @param name defines the name of the texture
  74309. * @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
  74310. * @param scene defines the scene where you want the texture
  74311. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  74312. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  74313. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  74314. */
  74315. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  74316. if (scene === void 0) { scene = null; }
  74317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74318. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  74319. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  74320. _this.name = name;
  74321. _this._engine = _this.getScene().getEngine();
  74322. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74323. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74324. _this._generateMipMaps = generateMipMaps;
  74325. if (options.getContext) {
  74326. _this._canvas = options;
  74327. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74328. }
  74329. else {
  74330. _this._canvas = document.createElement("canvas");
  74331. if (options.width || options.width === 0) {
  74332. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74333. }
  74334. else {
  74335. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  74336. }
  74337. }
  74338. var textureSize = _this.getSize();
  74339. _this._canvas.width = textureSize.width;
  74340. _this._canvas.height = textureSize.height;
  74341. _this._context = _this._canvas.getContext("2d");
  74342. return _this;
  74343. }
  74344. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  74345. /**
  74346. * Gets the current state of canRescale
  74347. */
  74348. get: function () {
  74349. return true;
  74350. },
  74351. enumerable: true,
  74352. configurable: true
  74353. });
  74354. DynamicTexture.prototype._recreate = function (textureSize) {
  74355. this._canvas.width = textureSize.width;
  74356. this._canvas.height = textureSize.height;
  74357. this.releaseInternalTexture();
  74358. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  74359. };
  74360. /**
  74361. * Scales the texture
  74362. * @param ratio the scale factor to apply to both width and height
  74363. */
  74364. DynamicTexture.prototype.scale = function (ratio) {
  74365. var textureSize = this.getSize();
  74366. textureSize.width *= ratio;
  74367. textureSize.height *= ratio;
  74368. this._recreate(textureSize);
  74369. };
  74370. /**
  74371. * Resizes the texture
  74372. * @param width the new width
  74373. * @param height the new height
  74374. */
  74375. DynamicTexture.prototype.scaleTo = function (width, height) {
  74376. var textureSize = this.getSize();
  74377. textureSize.width = width;
  74378. textureSize.height = height;
  74379. this._recreate(textureSize);
  74380. };
  74381. /**
  74382. * Gets the context of the canvas used by the texture
  74383. * @returns the canvas context of the dynamic texture
  74384. */
  74385. DynamicTexture.prototype.getContext = function () {
  74386. return this._context;
  74387. };
  74388. /**
  74389. * Clears the texture
  74390. */
  74391. DynamicTexture.prototype.clear = function () {
  74392. var size = this.getSize();
  74393. this._context.fillRect(0, 0, size.width, size.height);
  74394. };
  74395. /**
  74396. * Updates the texture
  74397. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74398. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  74399. */
  74400. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  74401. if (premulAlpha === void 0) { premulAlpha = false; }
  74402. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  74403. };
  74404. /**
  74405. * Draws text onto the texture
  74406. * @param text defines the text to be drawn
  74407. * @param x defines the placement of the text from the left
  74408. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  74409. * @param font defines the font to be used with font-style, font-size, font-name
  74410. * @param color defines the color used for the text
  74411. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  74412. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74413. * @param update defines whether texture is immediately update (default is true)
  74414. */
  74415. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  74416. if (update === void 0) { update = true; }
  74417. var size = this.getSize();
  74418. if (clearColor) {
  74419. this._context.fillStyle = clearColor;
  74420. this._context.fillRect(0, 0, size.width, size.height);
  74421. }
  74422. this._context.font = font;
  74423. if (x === null || x === undefined) {
  74424. var textSize = this._context.measureText(text);
  74425. x = (size.width - textSize.width) / 2;
  74426. }
  74427. if (y === null || y === undefined) {
  74428. var fontSize = parseInt((font.replace(/\D/g, '')));
  74429. y = (size.height / 2) + (fontSize / 3.65);
  74430. }
  74431. this._context.fillStyle = color;
  74432. this._context.fillText(text, x, y);
  74433. if (update) {
  74434. this.update(invertY);
  74435. }
  74436. };
  74437. /**
  74438. * Clones the texture
  74439. * @returns the clone of the texture.
  74440. */
  74441. DynamicTexture.prototype.clone = function () {
  74442. var scene = this.getScene();
  74443. if (!scene) {
  74444. return this;
  74445. }
  74446. var textureSize = this.getSize();
  74447. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  74448. // Base texture
  74449. newTexture.hasAlpha = this.hasAlpha;
  74450. newTexture.level = this.level;
  74451. // Dynamic Texture
  74452. newTexture.wrapU = this.wrapU;
  74453. newTexture.wrapV = this.wrapV;
  74454. return newTexture;
  74455. };
  74456. /**
  74457. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  74458. * @returns a serialized dynamic texture object
  74459. */
  74460. DynamicTexture.prototype.serialize = function () {
  74461. var scene = this.getScene();
  74462. if (scene && !scene.isReady()) {
  74463. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  74464. }
  74465. var serializationObject = _super.prototype.serialize.call(this);
  74466. serializationObject.base64String = this._canvas.toDataURL();
  74467. serializationObject.invertY = this._invertY;
  74468. serializationObject.samplingMode = this.samplingMode;
  74469. return serializationObject;
  74470. };
  74471. /** @hidden */
  74472. DynamicTexture.prototype._rebuild = function () {
  74473. this.update();
  74474. };
  74475. return DynamicTexture;
  74476. }(BABYLON.Texture));
  74477. BABYLON.DynamicTexture = DynamicTexture;
  74478. })(BABYLON || (BABYLON = {}));
  74479. //# sourceMappingURL=babylon.dynamicTexture.js.map
  74480. var BABYLON;
  74481. (function (BABYLON) {
  74482. /**
  74483. * If you want to display a video in your scene, this is the special texture for that.
  74484. * This special texture works similar to other textures, with the exception of a few parameters.
  74485. * @see https://doc.babylonjs.com/how_to/video_texture
  74486. */
  74487. var VideoTexture = /** @class */ (function (_super) {
  74488. __extends(VideoTexture, _super);
  74489. /**
  74490. * Creates a video texture.
  74491. * If you want to display a video in your scene, this is the special texture for that.
  74492. * This special texture works similar to other textures, with the exception of a few parameters.
  74493. * @see https://doc.babylonjs.com/how_to/video_texture
  74494. * @param name optional name, will detect from video source, if not defined
  74495. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  74496. * @param scene is obviously the current scene.
  74497. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  74498. * @param invertY is false by default but can be used to invert video on Y axis
  74499. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  74500. * @param settings allows finer control over video usage
  74501. */
  74502. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  74503. if (generateMipMaps === void 0) { generateMipMaps = false; }
  74504. if (invertY === void 0) { invertY = false; }
  74505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74506. if (settings === void 0) { settings = {
  74507. autoPlay: true,
  74508. loop: true,
  74509. autoUpdateTexture: true,
  74510. }; }
  74511. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74512. _this._onUserActionRequestedObservable = null;
  74513. _this._stillImageCaptured = false;
  74514. _this._poster = false;
  74515. _this._createInternalTexture = function () {
  74516. if (_this._texture != null) {
  74517. if (_this._poster) {
  74518. _this._texture.dispose();
  74519. _this._poster = false;
  74520. }
  74521. else {
  74522. return;
  74523. }
  74524. }
  74525. if (!_this._engine.needPOTTextures ||
  74526. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  74527. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74528. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74529. }
  74530. else {
  74531. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74532. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74533. _this._generateMipMaps = false;
  74534. }
  74535. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  74536. if (!_this.video.autoplay) {
  74537. var oldHandler_1 = _this.video.onplaying;
  74538. var error_1 = false;
  74539. _this.video.onplaying = function () {
  74540. _this.video.onplaying = oldHandler_1;
  74541. _this._texture.isReady = true;
  74542. _this._updateInternalTexture();
  74543. if (!error_1) {
  74544. _this.video.pause();
  74545. }
  74546. if (_this.onLoadObservable.hasObservers()) {
  74547. _this.onLoadObservable.notifyObservers(_this);
  74548. }
  74549. };
  74550. var playing = _this.video.play();
  74551. if (playing) {
  74552. playing.then(function () {
  74553. // Everything is good.
  74554. })
  74555. .catch(function () {
  74556. error_1 = true;
  74557. // On Chrome for instance, new policies might prevent playing without user interaction.
  74558. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  74559. _this._onUserActionRequestedObservable.notifyObservers(_this);
  74560. }
  74561. });
  74562. }
  74563. else {
  74564. _this.video.onplaying = oldHandler_1;
  74565. _this._texture.isReady = true;
  74566. _this._updateInternalTexture();
  74567. if (_this.onLoadObservable.hasObservers()) {
  74568. _this.onLoadObservable.notifyObservers(_this);
  74569. }
  74570. }
  74571. }
  74572. else {
  74573. _this._texture.isReady = true;
  74574. _this._updateInternalTexture();
  74575. if (_this.onLoadObservable.hasObservers()) {
  74576. _this.onLoadObservable.notifyObservers(_this);
  74577. }
  74578. }
  74579. };
  74580. _this.reset = function () {
  74581. if (_this._texture == null) {
  74582. return;
  74583. }
  74584. if (!_this._poster) {
  74585. _this._texture.dispose();
  74586. _this._texture = null;
  74587. }
  74588. };
  74589. _this._updateInternalTexture = function (e) {
  74590. if (_this._texture == null || !_this._texture.isReady) {
  74591. return;
  74592. }
  74593. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  74594. return;
  74595. }
  74596. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  74597. };
  74598. _this._engine = _this.getScene().getEngine();
  74599. _this._generateMipMaps = generateMipMaps;
  74600. _this._samplingMode = samplingMode;
  74601. _this.autoUpdateTexture = settings.autoUpdateTexture;
  74602. _this.name = name || _this._getName(src);
  74603. _this.video = _this._getVideo(src);
  74604. if (settings.poster) {
  74605. _this.video.poster = settings.poster;
  74606. }
  74607. if (settings.autoPlay !== undefined) {
  74608. _this.video.autoplay = settings.autoPlay;
  74609. }
  74610. if (settings.loop !== undefined) {
  74611. _this.video.loop = settings.loop;
  74612. }
  74613. _this.video.setAttribute("playsinline", "");
  74614. _this.video.addEventListener("canplay", _this._createInternalTexture);
  74615. _this.video.addEventListener("paused", _this._updateInternalTexture);
  74616. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  74617. _this.video.addEventListener("emptied", _this.reset);
  74618. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  74619. _this._createInternalTexture();
  74620. }
  74621. if (settings.poster) {
  74622. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  74623. _this._poster = true;
  74624. }
  74625. return _this;
  74626. }
  74627. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  74628. /**
  74629. * Event triggerd when a dom action is required by the user to play the video.
  74630. * This happens due to recent changes in browser policies preventing video to auto start.
  74631. */
  74632. get: function () {
  74633. if (!this._onUserActionRequestedObservable) {
  74634. this._onUserActionRequestedObservable = new BABYLON.Observable();
  74635. }
  74636. return this._onUserActionRequestedObservable;
  74637. },
  74638. enumerable: true,
  74639. configurable: true
  74640. });
  74641. VideoTexture.prototype._getName = function (src) {
  74642. if (src instanceof HTMLVideoElement) {
  74643. return src.currentSrc;
  74644. }
  74645. if (typeof src === "object") {
  74646. return src.toString();
  74647. }
  74648. return src;
  74649. };
  74650. VideoTexture.prototype._getVideo = function (src) {
  74651. if (src instanceof HTMLVideoElement) {
  74652. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  74653. return src;
  74654. }
  74655. var video = document.createElement("video");
  74656. if (typeof src === "string") {
  74657. BABYLON.Tools.SetCorsBehavior(src, video);
  74658. video.src = src;
  74659. }
  74660. else {
  74661. BABYLON.Tools.SetCorsBehavior(src[0], video);
  74662. src.forEach(function (url) {
  74663. var source = document.createElement("source");
  74664. source.src = url;
  74665. video.appendChild(source);
  74666. });
  74667. }
  74668. return video;
  74669. };
  74670. /**
  74671. * @hidden Internal method to initiate `update`.
  74672. */
  74673. VideoTexture.prototype._rebuild = function () {
  74674. this.update();
  74675. };
  74676. /**
  74677. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  74678. */
  74679. VideoTexture.prototype.update = function () {
  74680. if (!this.autoUpdateTexture) {
  74681. // Expecting user to call `updateTexture` manually
  74682. return;
  74683. }
  74684. this.updateTexture(true);
  74685. };
  74686. /**
  74687. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  74688. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  74689. */
  74690. VideoTexture.prototype.updateTexture = function (isVisible) {
  74691. if (!isVisible) {
  74692. return;
  74693. }
  74694. if (this.video.paused && this._stillImageCaptured) {
  74695. return;
  74696. }
  74697. this._stillImageCaptured = true;
  74698. this._updateInternalTexture();
  74699. };
  74700. /**
  74701. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  74702. * @param url New url.
  74703. */
  74704. VideoTexture.prototype.updateURL = function (url) {
  74705. this.video.src = url;
  74706. };
  74707. /**
  74708. * Dispose the texture and release its associated resources.
  74709. */
  74710. VideoTexture.prototype.dispose = function () {
  74711. _super.prototype.dispose.call(this);
  74712. if (this._onUserActionRequestedObservable) {
  74713. this._onUserActionRequestedObservable.clear();
  74714. this._onUserActionRequestedObservable = null;
  74715. }
  74716. this.video.removeEventListener("canplay", this._createInternalTexture);
  74717. this.video.removeEventListener("paused", this._updateInternalTexture);
  74718. this.video.removeEventListener("seeked", this._updateInternalTexture);
  74719. this.video.removeEventListener("emptied", this.reset);
  74720. this.video.pause();
  74721. };
  74722. /**
  74723. * Creates a video texture straight from your WebCam video feed.
  74724. * @param scene Define the scene the texture should be created in
  74725. * @param onReady Define a callback to triggered once the texture will be ready
  74726. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  74727. */
  74728. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  74729. var video = document.createElement("video");
  74730. video.setAttribute('autoplay', '');
  74731. video.setAttribute('muted', '');
  74732. video.setAttribute('playsinline', '');
  74733. var constraintsDeviceId;
  74734. if (constraints && constraints.deviceId) {
  74735. constraintsDeviceId = {
  74736. exact: constraints.deviceId,
  74737. };
  74738. }
  74739. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  74740. if (navigator.mediaDevices) {
  74741. navigator.mediaDevices.getUserMedia({ video: constraints })
  74742. .then(function (stream) {
  74743. if (video.mozSrcObject !== undefined) {
  74744. // hack for Firefox < 19
  74745. video.mozSrcObject = stream;
  74746. }
  74747. else {
  74748. video.srcObject = stream;
  74749. }
  74750. var onPlaying = function () {
  74751. if (onReady) {
  74752. onReady(new VideoTexture("video", video, scene, true, true));
  74753. }
  74754. video.removeEventListener("playing", onPlaying);
  74755. };
  74756. video.addEventListener("playing", onPlaying);
  74757. video.play();
  74758. })
  74759. .catch(function (err) {
  74760. BABYLON.Tools.Error(err.name);
  74761. });
  74762. }
  74763. else {
  74764. navigator.getUserMedia =
  74765. navigator.getUserMedia ||
  74766. navigator.webkitGetUserMedia ||
  74767. navigator.mozGetUserMedia ||
  74768. navigator.msGetUserMedia;
  74769. if (navigator.getUserMedia) {
  74770. navigator.getUserMedia({
  74771. video: {
  74772. deviceId: constraintsDeviceId,
  74773. width: {
  74774. min: (constraints && constraints.minWidth) || 256,
  74775. max: (constraints && constraints.maxWidth) || 640,
  74776. },
  74777. height: {
  74778. min: (constraints && constraints.minHeight) || 256,
  74779. max: (constraints && constraints.maxHeight) || 480,
  74780. },
  74781. },
  74782. }, function (stream) {
  74783. if (video.mozSrcObject !== undefined) {
  74784. // hack for Firefox < 19
  74785. video.mozSrcObject = stream;
  74786. }
  74787. else {
  74788. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  74789. }
  74790. video.play();
  74791. if (onReady) {
  74792. onReady(new VideoTexture("video", video, scene, true, true));
  74793. }
  74794. }, function (e) {
  74795. BABYLON.Tools.Error(e.name);
  74796. });
  74797. }
  74798. }
  74799. };
  74800. return VideoTexture;
  74801. }(BABYLON.Texture));
  74802. BABYLON.VideoTexture = VideoTexture;
  74803. })(BABYLON || (BABYLON = {}));
  74804. //# sourceMappingURL=babylon.videoTexture.js.map
  74805. var BABYLON;
  74806. (function (BABYLON) {
  74807. /**
  74808. * Raw texture can help creating a texture directly from an array of data.
  74809. * This can be super useful if you either get the data from an uncompressed source or
  74810. * if you wish to create your texture pixel by pixel.
  74811. */
  74812. var RawTexture = /** @class */ (function (_super) {
  74813. __extends(RawTexture, _super);
  74814. /**
  74815. * Instantiates a new RawTexture.
  74816. * Raw texture can help creating a texture directly from an array of data.
  74817. * This can be super useful if you either get the data from an uncompressed source or
  74818. * if you wish to create your texture pixel by pixel.
  74819. * @param data define the array of data to use to create the texture
  74820. * @param width define the width of the texture
  74821. * @param height define the height of the texture
  74822. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74823. * @param scene define the scene the texture belongs to
  74824. * @param generateMipMaps define whether mip maps should be generated or not
  74825. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74826. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74827. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74828. */
  74829. function RawTexture(data, width, height,
  74830. /**
  74831. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74832. */
  74833. format, scene, generateMipMaps, invertY, samplingMode, type) {
  74834. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74835. if (invertY === void 0) { invertY = false; }
  74836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74837. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74838. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74839. _this.format = format;
  74840. _this._engine = scene.getEngine();
  74841. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  74842. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74843. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74844. return _this;
  74845. }
  74846. /**
  74847. * Updates the texture underlying data.
  74848. * @param data Define the new data of the texture
  74849. */
  74850. RawTexture.prototype.update = function (data) {
  74851. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74852. };
  74853. /**
  74854. * Creates a luminance texture from some data.
  74855. * @param data Define the texture data
  74856. * @param width Define the width of the texture
  74857. * @param height Define the height of the texture
  74858. * @param scene Define the scene the texture belongs to
  74859. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74860. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74861. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74862. * @returns the luminance texture
  74863. */
  74864. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74865. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74866. if (invertY === void 0) { invertY = false; }
  74867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74868. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  74869. };
  74870. /**
  74871. * Creates a luminance alpha texture from some data.
  74872. * @param data Define the texture data
  74873. * @param width Define the width of the texture
  74874. * @param height Define the height of the texture
  74875. * @param scene Define the scene the texture belongs to
  74876. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74877. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74878. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74879. * @returns the luminance alpha texture
  74880. */
  74881. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74882. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74883. if (invertY === void 0) { invertY = false; }
  74884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74885. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74886. };
  74887. /**
  74888. * Creates an alpha texture from some data.
  74889. * @param data Define the texture data
  74890. * @param width Define the width of the texture
  74891. * @param height Define the height of the texture
  74892. * @param scene Define the scene the texture belongs to
  74893. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74894. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74895. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74896. * @returns the alpha texture
  74897. */
  74898. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74899. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74900. if (invertY === void 0) { invertY = false; }
  74901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74902. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74903. };
  74904. /**
  74905. * Creates a RGB texture from some data.
  74906. * @param data Define the texture data
  74907. * @param width Define the width of the texture
  74908. * @param height Define the height of the texture
  74909. * @param scene Define the scene the texture belongs to
  74910. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74911. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74912. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74913. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74914. * @returns the RGB alpha texture
  74915. */
  74916. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74917. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74918. if (invertY === void 0) { invertY = false; }
  74919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74920. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74921. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  74922. };
  74923. /**
  74924. * Creates a RGBA texture from some data.
  74925. * @param data Define the texture data
  74926. * @param width Define the width of the texture
  74927. * @param height Define the height of the texture
  74928. * @param scene Define the scene the texture belongs to
  74929. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74930. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74931. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74932. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74933. * @returns the RGBA texture
  74934. */
  74935. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74936. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74937. if (invertY === void 0) { invertY = false; }
  74938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74939. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74940. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  74941. };
  74942. /**
  74943. * Creates a R texture from some data.
  74944. * @param data Define the texture data
  74945. * @param width Define the width of the texture
  74946. * @param height Define the height of the texture
  74947. * @param scene Define the scene the texture belongs to
  74948. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74949. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74950. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74951. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74952. * @returns the R texture
  74953. */
  74954. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74955. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74956. if (invertY === void 0) { invertY = false; }
  74957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74958. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74959. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  74960. };
  74961. return RawTexture;
  74962. }(BABYLON.Texture));
  74963. BABYLON.RawTexture = RawTexture;
  74964. })(BABYLON || (BABYLON = {}));
  74965. //# sourceMappingURL=babylon.rawTexture.js.map
  74966. var BABYLON;
  74967. (function (BABYLON) {
  74968. /**
  74969. * Class used to store 3D textures containing user data
  74970. */
  74971. var RawTexture3D = /** @class */ (function (_super) {
  74972. __extends(RawTexture3D, _super);
  74973. /**
  74974. * Create a new RawTexture3D
  74975. * @param data defines the data of the texture
  74976. * @param width defines the width of the texture
  74977. * @param height defines the height of the texture
  74978. * @param depth defines the depth of the texture
  74979. * @param format defines the texture format to use
  74980. * @param scene defines the hosting scene
  74981. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  74982. * @param invertY defines if texture must be stored with Y axis inverted
  74983. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  74984. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  74985. */
  74986. function RawTexture3D(data, width, height, depth,
  74987. /** Gets or sets the texture format to use */
  74988. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  74989. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74990. if (invertY === void 0) { invertY = false; }
  74991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74992. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74993. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74994. _this.format = format;
  74995. _this._engine = scene.getEngine();
  74996. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  74997. _this.is3D = true;
  74998. return _this;
  74999. }
  75000. /**
  75001. * Update the texture with new data
  75002. * @param data defines the data to store in the texture
  75003. */
  75004. RawTexture3D.prototype.update = function (data) {
  75005. if (!this._texture) {
  75006. return;
  75007. }
  75008. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75009. };
  75010. return RawTexture3D;
  75011. }(BABYLON.Texture));
  75012. BABYLON.RawTexture3D = RawTexture3D;
  75013. })(BABYLON || (BABYLON = {}));
  75014. //# sourceMappingURL=babylon.rawTexture3D.js.map
  75015. var BABYLON;
  75016. (function (BABYLON) {
  75017. /**
  75018. * PostProcessManager is used to manage one or more post processes or post process pipelines
  75019. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75020. */
  75021. var PostProcessManager = /** @class */ (function () {
  75022. /**
  75023. * Creates a new instance PostProcess
  75024. * @param scene The scene that the post process is associated with.
  75025. */
  75026. function PostProcessManager(scene) {
  75027. this._vertexBuffers = {};
  75028. this._scene = scene;
  75029. }
  75030. PostProcessManager.prototype._prepareBuffers = function () {
  75031. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  75032. return;
  75033. }
  75034. // VBO
  75035. var vertices = [];
  75036. vertices.push(1, 1);
  75037. vertices.push(-1, 1);
  75038. vertices.push(-1, -1);
  75039. vertices.push(1, -1);
  75040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75041. this._buildIndexBuffer();
  75042. };
  75043. PostProcessManager.prototype._buildIndexBuffer = function () {
  75044. // Indices
  75045. var indices = [];
  75046. indices.push(0);
  75047. indices.push(1);
  75048. indices.push(2);
  75049. indices.push(0);
  75050. indices.push(2);
  75051. indices.push(3);
  75052. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  75053. };
  75054. /**
  75055. * Rebuilds the vertex buffers of the manager.
  75056. * @hidden
  75057. */
  75058. PostProcessManager.prototype._rebuild = function () {
  75059. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75060. if (!vb) {
  75061. return;
  75062. }
  75063. vb._rebuild();
  75064. this._buildIndexBuffer();
  75065. };
  75066. // Methods
  75067. /**
  75068. * Prepares a frame to be run through a post process.
  75069. * @param sourceTexture The input texture to the post procesess. (default: null)
  75070. * @param postProcesses An array of post processes to be run. (default: null)
  75071. * @returns True if the post processes were able to be run.
  75072. * @hidden
  75073. */
  75074. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  75075. if (sourceTexture === void 0) { sourceTexture = null; }
  75076. if (postProcesses === void 0) { postProcesses = null; }
  75077. var camera = this._scene.activeCamera;
  75078. if (!camera) {
  75079. return false;
  75080. }
  75081. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75082. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75083. return false;
  75084. }
  75085. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  75086. return true;
  75087. };
  75088. /**
  75089. * Manually render a set of post processes to a texture.
  75090. * @param postProcesses An array of post processes to be run.
  75091. * @param targetTexture The target texture to render to.
  75092. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  75093. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  75094. * @param lodLevel defines which lod of the texture to render to
  75095. */
  75096. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  75097. if (targetTexture === void 0) { targetTexture = null; }
  75098. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75099. if (faceIndex === void 0) { faceIndex = 0; }
  75100. if (lodLevel === void 0) { lodLevel = 0; }
  75101. var engine = this._scene.getEngine();
  75102. for (var index = 0; index < postProcesses.length; index++) {
  75103. if (index < postProcesses.length - 1) {
  75104. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  75105. }
  75106. else {
  75107. if (targetTexture) {
  75108. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  75109. }
  75110. else {
  75111. engine.restoreDefaultFramebuffer();
  75112. }
  75113. }
  75114. var pp = postProcesses[index];
  75115. var effect = pp.apply();
  75116. if (effect) {
  75117. pp.onBeforeRenderObservable.notifyObservers(effect);
  75118. // VBOs
  75119. this._prepareBuffers();
  75120. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75121. // Draw order
  75122. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75123. pp.onAfterRenderObservable.notifyObservers(effect);
  75124. }
  75125. }
  75126. // Restore depth buffer
  75127. engine.setDepthBuffer(true);
  75128. engine.setDepthWrite(true);
  75129. };
  75130. /**
  75131. * Finalize the result of the output of the postprocesses.
  75132. * @param doNotPresent If true the result will not be displayed to the screen.
  75133. * @param targetTexture The target texture to render to.
  75134. * @param faceIndex The index of the face to bind the target texture to.
  75135. * @param postProcesses The array of post processes to render.
  75136. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  75137. * @hidden
  75138. */
  75139. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  75140. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75141. var camera = this._scene.activeCamera;
  75142. if (!camera) {
  75143. return;
  75144. }
  75145. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75146. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75147. return;
  75148. }
  75149. var engine = this._scene.getEngine();
  75150. for (var index = 0, len = postProcesses.length; index < len; index++) {
  75151. var pp = postProcesses[index];
  75152. if (index < len - 1) {
  75153. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  75154. }
  75155. else {
  75156. if (targetTexture) {
  75157. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  75158. pp._outputTexture = targetTexture;
  75159. }
  75160. else {
  75161. engine.restoreDefaultFramebuffer();
  75162. pp._outputTexture = null;
  75163. }
  75164. }
  75165. if (doNotPresent) {
  75166. break;
  75167. }
  75168. var effect = pp.apply();
  75169. if (effect) {
  75170. pp.onBeforeRenderObservable.notifyObservers(effect);
  75171. // VBOs
  75172. this._prepareBuffers();
  75173. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75174. // Draw order
  75175. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75176. pp.onAfterRenderObservable.notifyObservers(effect);
  75177. }
  75178. }
  75179. // Restore states
  75180. engine.setDepthBuffer(true);
  75181. engine.setDepthWrite(true);
  75182. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75183. };
  75184. /**
  75185. * Disposes of the post process manager.
  75186. */
  75187. PostProcessManager.prototype.dispose = function () {
  75188. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75189. if (buffer) {
  75190. buffer.dispose();
  75191. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75192. }
  75193. if (this._indexBuffer) {
  75194. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75195. this._indexBuffer = null;
  75196. }
  75197. };
  75198. return PostProcessManager;
  75199. }());
  75200. BABYLON.PostProcessManager = PostProcessManager;
  75201. })(BABYLON || (BABYLON = {}));
  75202. //# sourceMappingURL=babylon.postProcessManager.js.map
  75203. var BABYLON;
  75204. (function (BABYLON) {
  75205. /**
  75206. * PostProcess can be used to apply a shader to a texture after it has been rendered
  75207. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75208. */
  75209. var PostProcess = /** @class */ (function () {
  75210. /**
  75211. * Creates a new instance PostProcess
  75212. * @param name The name of the PostProcess.
  75213. * @param fragmentUrl The url of the fragment shader to be used.
  75214. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  75215. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  75216. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75217. * @param camera The camera to apply the render pass to.
  75218. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75219. * @param engine The engine which the post process will be applied. (default: current engine)
  75220. * @param reusable If the post process can be reused on the same frame. (default: false)
  75221. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  75222. * @param textureType Type of textures used when performing the post process. (default: 0)
  75223. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  75224. * @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
  75225. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  75226. */
  75227. function PostProcess(
  75228. /** Name of the PostProcess. */
  75229. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  75230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  75231. if (defines === void 0) { defines = null; }
  75232. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75233. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  75234. if (blockCompilation === void 0) { blockCompilation = false; }
  75235. this.name = name;
  75236. /**
  75237. * Width of the texture to apply the post process on
  75238. */
  75239. this.width = -1;
  75240. /**
  75241. * Height of the texture to apply the post process on
  75242. */
  75243. this.height = -1;
  75244. /**
  75245. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  75246. * @hidden
  75247. */
  75248. this._outputTexture = null;
  75249. /**
  75250. * If the buffer needs to be cleared before applying the post process. (default: true)
  75251. * Should be set to false if shader will overwrite all previous pixels.
  75252. */
  75253. this.autoClear = true;
  75254. /**
  75255. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  75256. */
  75257. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  75258. /**
  75259. * Animations to be used for the post processing
  75260. */
  75261. this.animations = new Array();
  75262. /**
  75263. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  75264. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  75265. */
  75266. this.enablePixelPerfectMode = false;
  75267. /**
  75268. * Force the postprocess to be applied without taking in account viewport
  75269. */
  75270. this.forceFullscreenViewport = true;
  75271. /**
  75272. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  75273. *
  75274. * | Value | Type | Description |
  75275. * | ----- | ----------------------------------- | ----------- |
  75276. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  75277. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  75278. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  75279. *
  75280. */
  75281. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  75282. /**
  75283. * Force textures to be a power of two (default: false)
  75284. */
  75285. this.alwaysForcePOT = false;
  75286. this._samples = 1;
  75287. /**
  75288. * Modify the scale of the post process to be the same as the viewport (default: false)
  75289. */
  75290. this.adaptScaleToCurrentViewport = false;
  75291. this._reusable = false;
  75292. /**
  75293. * Smart array of input and output textures for the post process.
  75294. * @hidden
  75295. */
  75296. this._textures = new BABYLON.SmartArray(2);
  75297. /**
  75298. * The index in _textures that corresponds to the output texture.
  75299. * @hidden
  75300. */
  75301. this._currentRenderTextureInd = 0;
  75302. this._scaleRatio = new BABYLON.Vector2(1, 1);
  75303. this._texelSize = BABYLON.Vector2.Zero();
  75304. // Events
  75305. /**
  75306. * An event triggered when the postprocess is activated.
  75307. */
  75308. this.onActivateObservable = new BABYLON.Observable();
  75309. /**
  75310. * An event triggered when the postprocess changes its size.
  75311. */
  75312. this.onSizeChangedObservable = new BABYLON.Observable();
  75313. /**
  75314. * An event triggered when the postprocess applies its effect.
  75315. */
  75316. this.onApplyObservable = new BABYLON.Observable();
  75317. /**
  75318. * An event triggered before rendering the postprocess
  75319. */
  75320. this.onBeforeRenderObservable = new BABYLON.Observable();
  75321. /**
  75322. * An event triggered after rendering the postprocess
  75323. */
  75324. this.onAfterRenderObservable = new BABYLON.Observable();
  75325. if (camera != null) {
  75326. this._camera = camera;
  75327. this._scene = camera.getScene();
  75328. camera.attachPostProcess(this);
  75329. this._engine = this._scene.getEngine();
  75330. this._scene.postProcesses.push(this);
  75331. }
  75332. else if (engine) {
  75333. this._engine = engine;
  75334. this._engine.postProcesses.push(this);
  75335. }
  75336. this._options = options;
  75337. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  75338. this._reusable = reusable || false;
  75339. this._textureType = textureType;
  75340. this._samplers = samplers || [];
  75341. this._samplers.push("textureSampler");
  75342. this._fragmentUrl = fragmentUrl;
  75343. this._vertexUrl = vertexUrl;
  75344. this._parameters = parameters || [];
  75345. this._parameters.push("scale");
  75346. this._indexParameters = indexParameters;
  75347. if (!blockCompilation) {
  75348. this.updateEffect(defines);
  75349. }
  75350. }
  75351. Object.defineProperty(PostProcess.prototype, "samples", {
  75352. /**
  75353. * Number of sample textures (default: 1)
  75354. */
  75355. get: function () {
  75356. return this._samples;
  75357. },
  75358. set: function (n) {
  75359. var _this = this;
  75360. this._samples = n;
  75361. this._textures.forEach(function (texture) {
  75362. if (texture.samples !== _this._samples) {
  75363. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  75364. }
  75365. });
  75366. },
  75367. enumerable: true,
  75368. configurable: true
  75369. });
  75370. Object.defineProperty(PostProcess.prototype, "onActivate", {
  75371. /**
  75372. * A function that is added to the onActivateObservable
  75373. */
  75374. set: function (callback) {
  75375. if (this._onActivateObserver) {
  75376. this.onActivateObservable.remove(this._onActivateObserver);
  75377. }
  75378. if (callback) {
  75379. this._onActivateObserver = this.onActivateObservable.add(callback);
  75380. }
  75381. },
  75382. enumerable: true,
  75383. configurable: true
  75384. });
  75385. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  75386. /**
  75387. * A function that is added to the onSizeChangedObservable
  75388. */
  75389. set: function (callback) {
  75390. if (this._onSizeChangedObserver) {
  75391. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  75392. }
  75393. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  75394. },
  75395. enumerable: true,
  75396. configurable: true
  75397. });
  75398. Object.defineProperty(PostProcess.prototype, "onApply", {
  75399. /**
  75400. * A function that is added to the onApplyObservable
  75401. */
  75402. set: function (callback) {
  75403. if (this._onApplyObserver) {
  75404. this.onApplyObservable.remove(this._onApplyObserver);
  75405. }
  75406. this._onApplyObserver = this.onApplyObservable.add(callback);
  75407. },
  75408. enumerable: true,
  75409. configurable: true
  75410. });
  75411. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  75412. /**
  75413. * A function that is added to the onBeforeRenderObservable
  75414. */
  75415. set: function (callback) {
  75416. if (this._onBeforeRenderObserver) {
  75417. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75418. }
  75419. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75420. },
  75421. enumerable: true,
  75422. configurable: true
  75423. });
  75424. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  75425. /**
  75426. * A function that is added to the onAfterRenderObservable
  75427. */
  75428. set: function (callback) {
  75429. if (this._onAfterRenderObserver) {
  75430. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75431. }
  75432. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75433. },
  75434. enumerable: true,
  75435. configurable: true
  75436. });
  75437. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  75438. /**
  75439. * 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
  75440. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  75441. */
  75442. get: function () {
  75443. return this._textures.data[this._currentRenderTextureInd];
  75444. },
  75445. set: function (value) {
  75446. this._forcedOutputTexture = value;
  75447. },
  75448. enumerable: true,
  75449. configurable: true
  75450. });
  75451. /**
  75452. * Gets the camera which post process is applied to.
  75453. * @returns The camera the post process is applied to.
  75454. */
  75455. PostProcess.prototype.getCamera = function () {
  75456. return this._camera;
  75457. };
  75458. Object.defineProperty(PostProcess.prototype, "texelSize", {
  75459. /**
  75460. * Gets the texel size of the postprocess.
  75461. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  75462. */
  75463. get: function () {
  75464. if (this._shareOutputWithPostProcess) {
  75465. return this._shareOutputWithPostProcess.texelSize;
  75466. }
  75467. if (this._forcedOutputTexture) {
  75468. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  75469. }
  75470. return this._texelSize;
  75471. },
  75472. enumerable: true,
  75473. configurable: true
  75474. });
  75475. /**
  75476. * Gets the engine which this post process belongs to.
  75477. * @returns The engine the post process was enabled with.
  75478. */
  75479. PostProcess.prototype.getEngine = function () {
  75480. return this._engine;
  75481. };
  75482. /**
  75483. * The effect that is created when initializing the post process.
  75484. * @returns The created effect corrisponding the the postprocess.
  75485. */
  75486. PostProcess.prototype.getEffect = function () {
  75487. return this._effect;
  75488. };
  75489. /**
  75490. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  75491. * @param postProcess The post process to share the output with.
  75492. * @returns This post process.
  75493. */
  75494. PostProcess.prototype.shareOutputWith = function (postProcess) {
  75495. this._disposeTextures();
  75496. this._shareOutputWithPostProcess = postProcess;
  75497. return this;
  75498. };
  75499. /**
  75500. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  75501. * This should be called if the post process that shares output with this post process is disabled/disposed.
  75502. */
  75503. PostProcess.prototype.useOwnOutput = function () {
  75504. if (this._textures.length == 0) {
  75505. this._textures = new BABYLON.SmartArray(2);
  75506. }
  75507. this._shareOutputWithPostProcess = null;
  75508. };
  75509. /**
  75510. * Updates the effect with the current post process compile time values and recompiles the shader.
  75511. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75512. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75513. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75514. * @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
  75515. * @param onCompiled Called when the shader has been compiled.
  75516. * @param onError Called if there is an error when compiling a shader.
  75517. */
  75518. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75519. if (defines === void 0) { defines = null; }
  75520. if (uniforms === void 0) { uniforms = null; }
  75521. if (samplers === void 0) { samplers = null; }
  75522. 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);
  75523. };
  75524. /**
  75525. * The post process is reusable if it can be used multiple times within one frame.
  75526. * @returns If the post process is reusable
  75527. */
  75528. PostProcess.prototype.isReusable = function () {
  75529. return this._reusable;
  75530. };
  75531. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  75532. PostProcess.prototype.markTextureDirty = function () {
  75533. this.width = -1;
  75534. };
  75535. /**
  75536. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  75537. * 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.
  75538. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  75539. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  75540. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  75541. * @returns The target texture that was bound to be written to.
  75542. */
  75543. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  75544. var _this = this;
  75545. if (sourceTexture === void 0) { sourceTexture = null; }
  75546. camera = camera || this._camera;
  75547. var scene = camera.getScene();
  75548. var engine = scene.getEngine();
  75549. var maxSize = engine.getCaps().maxTextureSize;
  75550. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  75551. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  75552. // 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
  75553. var webVRCamera = camera.parent;
  75554. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  75555. requiredWidth /= 2;
  75556. }
  75557. var desiredWidth = (this._options.width || requiredWidth);
  75558. var desiredHeight = this._options.height || requiredHeight;
  75559. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  75560. if (this.adaptScaleToCurrentViewport) {
  75561. var currentViewport = engine.currentViewport;
  75562. if (currentViewport) {
  75563. desiredWidth *= currentViewport.width;
  75564. desiredHeight *= currentViewport.height;
  75565. }
  75566. }
  75567. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  75568. if (!this._options.width) {
  75569. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  75570. }
  75571. if (!this._options.height) {
  75572. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  75573. }
  75574. }
  75575. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  75576. if (this._textures.length > 0) {
  75577. for (var i = 0; i < this._textures.length; i++) {
  75578. this._engine._releaseTexture(this._textures.data[i]);
  75579. }
  75580. this._textures.reset();
  75581. }
  75582. this.width = desiredWidth;
  75583. this.height = desiredHeight;
  75584. var textureSize = { width: this.width, height: this.height };
  75585. var textureOptions = {
  75586. generateMipMaps: false,
  75587. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  75588. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  75589. samplingMode: this.renderTargetSamplingMode,
  75590. type: this._textureType
  75591. };
  75592. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75593. if (this._reusable) {
  75594. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75595. }
  75596. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  75597. this.onSizeChangedObservable.notifyObservers(this);
  75598. }
  75599. this._textures.forEach(function (texture) {
  75600. if (texture.samples !== _this.samples) {
  75601. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  75602. }
  75603. });
  75604. }
  75605. var target;
  75606. if (this._shareOutputWithPostProcess) {
  75607. target = this._shareOutputWithPostProcess.inputTexture;
  75608. }
  75609. else if (this._forcedOutputTexture) {
  75610. target = this._forcedOutputTexture;
  75611. this.width = this._forcedOutputTexture.width;
  75612. this.height = this._forcedOutputTexture.height;
  75613. }
  75614. else {
  75615. target = this.inputTexture;
  75616. }
  75617. // Bind the input of this post process to be used as the output of the previous post process.
  75618. if (this.enablePixelPerfectMode) {
  75619. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  75620. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  75621. }
  75622. else {
  75623. this._scaleRatio.copyFromFloats(1, 1);
  75624. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  75625. }
  75626. this.onActivateObservable.notifyObservers(camera);
  75627. // Clear
  75628. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  75629. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  75630. }
  75631. if (this._reusable) {
  75632. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  75633. }
  75634. return target;
  75635. };
  75636. Object.defineProperty(PostProcess.prototype, "isSupported", {
  75637. /**
  75638. * If the post process is supported.
  75639. */
  75640. get: function () {
  75641. return this._effect.isSupported;
  75642. },
  75643. enumerable: true,
  75644. configurable: true
  75645. });
  75646. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  75647. /**
  75648. * The aspect ratio of the output texture.
  75649. */
  75650. get: function () {
  75651. if (this._shareOutputWithPostProcess) {
  75652. return this._shareOutputWithPostProcess.aspectRatio;
  75653. }
  75654. if (this._forcedOutputTexture) {
  75655. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  75656. }
  75657. return this.width / this.height;
  75658. },
  75659. enumerable: true,
  75660. configurable: true
  75661. });
  75662. /**
  75663. * Get a value indicating if the post-process is ready to be used
  75664. * @returns true if the post-process is ready (shader is compiled)
  75665. */
  75666. PostProcess.prototype.isReady = function () {
  75667. return this._effect && this._effect.isReady();
  75668. };
  75669. /**
  75670. * Binds all textures and uniforms to the shader, this will be run on every pass.
  75671. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  75672. */
  75673. PostProcess.prototype.apply = function () {
  75674. // Check
  75675. if (!this._effect || !this._effect.isReady()) {
  75676. return null;
  75677. }
  75678. // States
  75679. this._engine.enableEffect(this._effect);
  75680. this._engine.setState(false);
  75681. this._engine.setDepthBuffer(false);
  75682. this._engine.setDepthWrite(false);
  75683. // Alpha
  75684. this._engine.setAlphaMode(this.alphaMode);
  75685. if (this.alphaConstants) {
  75686. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  75687. }
  75688. // Bind the output texture of the preivous post process as the input to this post process.
  75689. var source;
  75690. if (this._shareOutputWithPostProcess) {
  75691. source = this._shareOutputWithPostProcess.inputTexture;
  75692. }
  75693. else if (this._forcedOutputTexture) {
  75694. source = this._forcedOutputTexture;
  75695. }
  75696. else {
  75697. source = this.inputTexture;
  75698. }
  75699. this._effect._bindTexture("textureSampler", source);
  75700. // Parameters
  75701. this._effect.setVector2("scale", this._scaleRatio);
  75702. this.onApplyObservable.notifyObservers(this._effect);
  75703. return this._effect;
  75704. };
  75705. PostProcess.prototype._disposeTextures = function () {
  75706. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  75707. return;
  75708. }
  75709. if (this._textures.length > 0) {
  75710. for (var i = 0; i < this._textures.length; i++) {
  75711. this._engine._releaseTexture(this._textures.data[i]);
  75712. }
  75713. }
  75714. this._textures.dispose();
  75715. };
  75716. /**
  75717. * Disposes the post process.
  75718. * @param camera The camera to dispose the post process on.
  75719. */
  75720. PostProcess.prototype.dispose = function (camera) {
  75721. camera = camera || this._camera;
  75722. this._disposeTextures();
  75723. if (this._scene) {
  75724. var index_1 = this._scene.postProcesses.indexOf(this);
  75725. if (index_1 !== -1) {
  75726. this._scene.postProcesses.splice(index_1, 1);
  75727. }
  75728. }
  75729. else {
  75730. var index_2 = this._engine.postProcesses.indexOf(this);
  75731. if (index_2 !== -1) {
  75732. this._engine.postProcesses.splice(index_2, 1);
  75733. }
  75734. }
  75735. if (!camera) {
  75736. return;
  75737. }
  75738. camera.detachPostProcess(this);
  75739. var index = camera._postProcesses.indexOf(this);
  75740. if (index === 0 && camera._postProcesses.length > 0) {
  75741. var firstPostProcess = this._camera._getFirstPostProcess();
  75742. if (firstPostProcess) {
  75743. firstPostProcess.markTextureDirty();
  75744. }
  75745. }
  75746. this.onActivateObservable.clear();
  75747. this.onAfterRenderObservable.clear();
  75748. this.onApplyObservable.clear();
  75749. this.onBeforeRenderObservable.clear();
  75750. this.onSizeChangedObservable.clear();
  75751. };
  75752. return PostProcess;
  75753. }());
  75754. BABYLON.PostProcess = PostProcess;
  75755. })(BABYLON || (BABYLON = {}));
  75756. //# sourceMappingURL=babylon.postProcess.js.map
  75757. var BABYLON;
  75758. (function (BABYLON) {
  75759. /**
  75760. * PassPostProcess which produces an output the same as it's input
  75761. */
  75762. var PassPostProcess = /** @class */ (function (_super) {
  75763. __extends(PassPostProcess, _super);
  75764. /**
  75765. * Creates the PassPostProcess
  75766. * @param name The name of the effect.
  75767. * @param options The required width/height ratio to downsize to before computing the render pass.
  75768. * @param camera The camera to apply the render pass to.
  75769. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75770. * @param engine The engine which the post process will be applied. (default: current engine)
  75771. * @param reusable If the post process can be reused on the same frame. (default: false)
  75772. * @param textureType The type of texture to be used when performing the post processing.
  75773. * @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)
  75774. */
  75775. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75776. if (camera === void 0) { camera = null; }
  75777. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75778. if (blockCompilation === void 0) { blockCompilation = false; }
  75779. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  75780. }
  75781. return PassPostProcess;
  75782. }(BABYLON.PostProcess));
  75783. BABYLON.PassPostProcess = PassPostProcess;
  75784. })(BABYLON || (BABYLON = {}));
  75785. //# sourceMappingURL=babylon.passPostProcess.js.map
  75786. var __assign = (this && this.__assign) || function () {
  75787. __assign = Object.assign || function(t) {
  75788. for (var s, i = 1, n = arguments.length; i < n; i++) {
  75789. s = arguments[i];
  75790. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  75791. t[p] = s[p];
  75792. }
  75793. return t;
  75794. };
  75795. return __assign.apply(this, arguments);
  75796. };
  75797. var BABYLON;
  75798. (function (BABYLON) {
  75799. /**
  75800. * Default implementation IShadowGenerator.
  75801. * This is the main object responsible of generating shadows in the framework.
  75802. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  75803. */
  75804. var ShadowGenerator = /** @class */ (function () {
  75805. /**
  75806. * Creates a ShadowGenerator object.
  75807. * A ShadowGenerator is the required tool to use the shadows.
  75808. * Each light casting shadows needs to use its own ShadowGenerator.
  75809. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  75810. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  75811. * @param light The light object generating the shadows.
  75812. * @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.
  75813. */
  75814. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  75815. this._bias = 0.00005;
  75816. this._normalBias = 0;
  75817. this._blurBoxOffset = 1;
  75818. this._blurScale = 2;
  75819. this._blurKernel = 1;
  75820. this._useKernelBlur = false;
  75821. this._filter = ShadowGenerator.FILTER_NONE;
  75822. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  75823. this._contactHardeningLightSizeUVRatio = 0.1;
  75824. this._darkness = 0;
  75825. this._transparencyShadow = false;
  75826. /**
  75827. * Controls the extent to which the shadows fade out at the edge of the frustum
  75828. * Used only by directionals and spots
  75829. */
  75830. this.frustumEdgeFalloff = 0;
  75831. /**
  75832. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  75833. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  75834. * It might on the other hand introduce peter panning.
  75835. */
  75836. this.forceBackFacesOnly = false;
  75837. this._lightDirection = BABYLON.Vector3.Zero();
  75838. this._viewMatrix = BABYLON.Matrix.Zero();
  75839. this._projectionMatrix = BABYLON.Matrix.Zero();
  75840. this._transformMatrix = BABYLON.Matrix.Zero();
  75841. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75842. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75843. this._currentFaceIndex = 0;
  75844. this._currentFaceIndexCache = 0;
  75845. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  75846. this._mapSize = mapSize;
  75847. this._light = light;
  75848. this._scene = light.getScene();
  75849. light._shadowGenerator = this;
  75850. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  75851. if (!component) {
  75852. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  75853. this._scene._addComponent(component);
  75854. }
  75855. // Texture type fallback from float to int if not supported.
  75856. var caps = this._scene.getEngine().getCaps();
  75857. if (!useFullFloatFirst) {
  75858. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75859. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75860. }
  75861. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75862. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75863. }
  75864. else {
  75865. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75866. }
  75867. }
  75868. else {
  75869. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75870. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75871. }
  75872. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75873. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75874. }
  75875. else {
  75876. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75877. }
  75878. }
  75879. this._initializeGenerator();
  75880. this._applyFilterValues();
  75881. }
  75882. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  75883. /**
  75884. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  75885. */
  75886. get: function () {
  75887. return this._bias;
  75888. },
  75889. /**
  75890. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  75891. */
  75892. set: function (bias) {
  75893. this._bias = bias;
  75894. },
  75895. enumerable: true,
  75896. configurable: true
  75897. });
  75898. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  75899. /**
  75900. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75901. */
  75902. get: function () {
  75903. return this._normalBias;
  75904. },
  75905. /**
  75906. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75907. */
  75908. set: function (normalBias) {
  75909. this._normalBias = normalBias;
  75910. },
  75911. enumerable: true,
  75912. configurable: true
  75913. });
  75914. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  75915. /**
  75916. * Gets the blur box offset: offset applied during the blur pass.
  75917. * Only usefull if useKernelBlur = false
  75918. */
  75919. get: function () {
  75920. return this._blurBoxOffset;
  75921. },
  75922. /**
  75923. * Sets the blur box offset: offset applied during the blur pass.
  75924. * Only usefull if useKernelBlur = false
  75925. */
  75926. set: function (value) {
  75927. if (this._blurBoxOffset === value) {
  75928. return;
  75929. }
  75930. this._blurBoxOffset = value;
  75931. this._disposeBlurPostProcesses();
  75932. },
  75933. enumerable: true,
  75934. configurable: true
  75935. });
  75936. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  75937. /**
  75938. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  75939. * 2 means half of the size.
  75940. */
  75941. get: function () {
  75942. return this._blurScale;
  75943. },
  75944. /**
  75945. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  75946. * 2 means half of the size.
  75947. */
  75948. set: function (value) {
  75949. if (this._blurScale === value) {
  75950. return;
  75951. }
  75952. this._blurScale = value;
  75953. this._disposeBlurPostProcesses();
  75954. },
  75955. enumerable: true,
  75956. configurable: true
  75957. });
  75958. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  75959. /**
  75960. * Gets the blur kernel: kernel size of the blur pass.
  75961. * Only usefull if useKernelBlur = true
  75962. */
  75963. get: function () {
  75964. return this._blurKernel;
  75965. },
  75966. /**
  75967. * Sets the blur kernel: kernel size of the blur pass.
  75968. * Only usefull if useKernelBlur = true
  75969. */
  75970. set: function (value) {
  75971. if (this._blurKernel === value) {
  75972. return;
  75973. }
  75974. this._blurKernel = value;
  75975. this._disposeBlurPostProcesses();
  75976. },
  75977. enumerable: true,
  75978. configurable: true
  75979. });
  75980. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  75981. /**
  75982. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  75983. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  75984. */
  75985. get: function () {
  75986. return this._useKernelBlur;
  75987. },
  75988. /**
  75989. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  75990. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  75991. */
  75992. set: function (value) {
  75993. if (this._useKernelBlur === value) {
  75994. return;
  75995. }
  75996. this._useKernelBlur = value;
  75997. this._disposeBlurPostProcesses();
  75998. },
  75999. enumerable: true,
  76000. configurable: true
  76001. });
  76002. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  76003. /**
  76004. * Gets the depth scale used in ESM mode.
  76005. */
  76006. get: function () {
  76007. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  76008. },
  76009. /**
  76010. * Sets the depth scale used in ESM mode.
  76011. * This can override the scale stored on the light.
  76012. */
  76013. set: function (value) {
  76014. this._depthScale = value;
  76015. },
  76016. enumerable: true,
  76017. configurable: true
  76018. });
  76019. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  76020. /**
  76021. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  76022. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76023. */
  76024. get: function () {
  76025. return this._filter;
  76026. },
  76027. /**
  76028. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  76029. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76030. */
  76031. set: function (value) {
  76032. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  76033. if (this._light.needCube()) {
  76034. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76035. this.useExponentialShadowMap = true;
  76036. return;
  76037. }
  76038. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76039. this.useCloseExponentialShadowMap = true;
  76040. return;
  76041. }
  76042. // PCF on cubemap would also be expensive
  76043. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76044. this.usePoissonSampling = true;
  76045. return;
  76046. }
  76047. }
  76048. // Weblg1 fallback for PCF.
  76049. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76050. if (this._scene.getEngine().webGLVersion === 1) {
  76051. this.usePoissonSampling = true;
  76052. return;
  76053. }
  76054. }
  76055. if (this._filter === value) {
  76056. return;
  76057. }
  76058. this._filter = value;
  76059. this._disposeBlurPostProcesses();
  76060. this._applyFilterValues();
  76061. this._light._markMeshesAsLightDirty();
  76062. },
  76063. enumerable: true,
  76064. configurable: true
  76065. });
  76066. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  76067. /**
  76068. * Gets if the current filter is set to Poisson Sampling.
  76069. */
  76070. get: function () {
  76071. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  76072. },
  76073. /**
  76074. * Sets the current filter to Poisson Sampling.
  76075. */
  76076. set: function (value) {
  76077. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  76078. return;
  76079. }
  76080. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  76081. },
  76082. enumerable: true,
  76083. configurable: true
  76084. });
  76085. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  76086. /**
  76087. * Gets if the current filter is set to ESM.
  76088. */
  76089. get: function () {
  76090. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  76091. },
  76092. /**
  76093. * Sets the current filter is to ESM.
  76094. */
  76095. set: function (value) {
  76096. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  76097. return;
  76098. }
  76099. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76100. },
  76101. enumerable: true,
  76102. configurable: true
  76103. });
  76104. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  76105. /**
  76106. * Gets if the current filter is set to filtered ESM.
  76107. */
  76108. get: function () {
  76109. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  76110. },
  76111. /**
  76112. * Gets if the current filter is set to filtered ESM.
  76113. */
  76114. set: function (value) {
  76115. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76116. return;
  76117. }
  76118. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76119. },
  76120. enumerable: true,
  76121. configurable: true
  76122. });
  76123. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  76124. /**
  76125. * Gets if the current filter is set to "close ESM" (using the inverse of the
  76126. * exponential to prevent steep falloff artifacts).
  76127. */
  76128. get: function () {
  76129. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  76130. },
  76131. /**
  76132. * Sets the current filter to "close ESM" (using the inverse of the
  76133. * exponential to prevent steep falloff artifacts).
  76134. */
  76135. set: function (value) {
  76136. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  76137. return;
  76138. }
  76139. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76140. },
  76141. enumerable: true,
  76142. configurable: true
  76143. });
  76144. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  76145. /**
  76146. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  76147. * exponential to prevent steep falloff artifacts).
  76148. */
  76149. get: function () {
  76150. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  76151. },
  76152. /**
  76153. * Sets the current filter to filtered "close ESM" (using the inverse of the
  76154. * exponential to prevent steep falloff artifacts).
  76155. */
  76156. set: function (value) {
  76157. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76158. return;
  76159. }
  76160. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76161. },
  76162. enumerable: true,
  76163. configurable: true
  76164. });
  76165. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  76166. /**
  76167. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  76168. */
  76169. get: function () {
  76170. return this.filter === ShadowGenerator.FILTER_PCF;
  76171. },
  76172. /**
  76173. * Sets the current filter to "PCF" (percentage closer filtering).
  76174. */
  76175. set: function (value) {
  76176. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  76177. return;
  76178. }
  76179. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  76180. },
  76181. enumerable: true,
  76182. configurable: true
  76183. });
  76184. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  76185. /**
  76186. * Gets the PCF or PCSS Quality.
  76187. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76188. */
  76189. get: function () {
  76190. return this._filteringQuality;
  76191. },
  76192. /**
  76193. * Sets the PCF or PCSS Quality.
  76194. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76195. */
  76196. set: function (filteringQuality) {
  76197. this._filteringQuality = filteringQuality;
  76198. },
  76199. enumerable: true,
  76200. configurable: true
  76201. });
  76202. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  76203. /**
  76204. * Gets if the current filter is set to "PCSS" (contact hardening).
  76205. */
  76206. get: function () {
  76207. return this.filter === ShadowGenerator.FILTER_PCSS;
  76208. },
  76209. /**
  76210. * Sets the current filter to "PCSS" (contact hardening).
  76211. */
  76212. set: function (value) {
  76213. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  76214. return;
  76215. }
  76216. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  76217. },
  76218. enumerable: true,
  76219. configurable: true
  76220. });
  76221. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  76222. /**
  76223. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76224. * Using a ratio helps keeping shape stability independently of the map size.
  76225. *
  76226. * It does not account for the light projection as it was having too much
  76227. * instability during the light setup or during light position changes.
  76228. *
  76229. * Only valid if useContactHardeningShadow is true.
  76230. */
  76231. get: function () {
  76232. return this._contactHardeningLightSizeUVRatio;
  76233. },
  76234. /**
  76235. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76236. * Using a ratio helps keeping shape stability independently of the map size.
  76237. *
  76238. * It does not account for the light projection as it was having too much
  76239. * instability during the light setup or during light position changes.
  76240. *
  76241. * Only valid if useContactHardeningShadow is true.
  76242. */
  76243. set: function (contactHardeningLightSizeUVRatio) {
  76244. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  76245. },
  76246. enumerable: true,
  76247. configurable: true
  76248. });
  76249. /**
  76250. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  76251. * 0 means strongest and 1 would means no shadow.
  76252. * @returns the darkness.
  76253. */
  76254. ShadowGenerator.prototype.getDarkness = function () {
  76255. return this._darkness;
  76256. };
  76257. /**
  76258. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  76259. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  76260. * @returns the shadow generator allowing fluent coding.
  76261. */
  76262. ShadowGenerator.prototype.setDarkness = function (darkness) {
  76263. if (darkness >= 1.0) {
  76264. this._darkness = 1.0;
  76265. }
  76266. else if (darkness <= 0.0) {
  76267. this._darkness = 0.0;
  76268. }
  76269. else {
  76270. this._darkness = darkness;
  76271. }
  76272. return this;
  76273. };
  76274. /**
  76275. * Sets the ability to have transparent shadow (boolean).
  76276. * @param transparent True if transparent else False
  76277. * @returns the shadow generator allowing fluent coding
  76278. */
  76279. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  76280. this._transparencyShadow = transparent;
  76281. return this;
  76282. };
  76283. /**
  76284. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  76285. * @returns The render target texture if present otherwise, null
  76286. */
  76287. ShadowGenerator.prototype.getShadowMap = function () {
  76288. return this._shadowMap;
  76289. };
  76290. /**
  76291. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  76292. * @returns The render target texture if the shadow map is present otherwise, null
  76293. */
  76294. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  76295. if (this._shadowMap2) {
  76296. return this._shadowMap2;
  76297. }
  76298. return this._shadowMap;
  76299. };
  76300. /**
  76301. * Helper function to add a mesh and its descendants to the list of shadow casters.
  76302. * @param mesh Mesh to add
  76303. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  76304. * @returns the Shadow Generator itself
  76305. */
  76306. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  76307. if (includeDescendants === void 0) { includeDescendants = true; }
  76308. var _a;
  76309. if (!this._shadowMap) {
  76310. return this;
  76311. }
  76312. if (!this._shadowMap.renderList) {
  76313. this._shadowMap.renderList = [];
  76314. }
  76315. this._shadowMap.renderList.push(mesh);
  76316. if (includeDescendants) {
  76317. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  76318. }
  76319. return this;
  76320. };
  76321. /**
  76322. * Helper function to remove a mesh and its descendants from the list of shadow casters
  76323. * @param mesh Mesh to remove
  76324. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  76325. * @returns the Shadow Generator itself
  76326. */
  76327. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  76328. if (includeDescendants === void 0) { includeDescendants = true; }
  76329. if (!this._shadowMap || !this._shadowMap.renderList) {
  76330. return this;
  76331. }
  76332. var index = this._shadowMap.renderList.indexOf(mesh);
  76333. if (index !== -1) {
  76334. this._shadowMap.renderList.splice(index, 1);
  76335. }
  76336. if (includeDescendants) {
  76337. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  76338. var child = _a[_i];
  76339. this.removeShadowCaster(child);
  76340. }
  76341. }
  76342. return this;
  76343. };
  76344. /**
  76345. * Returns the associated light object.
  76346. * @returns the light generating the shadow
  76347. */
  76348. ShadowGenerator.prototype.getLight = function () {
  76349. return this._light;
  76350. };
  76351. ShadowGenerator.prototype._initializeGenerator = function () {
  76352. this._light._markMeshesAsLightDirty();
  76353. this._initializeShadowMap();
  76354. };
  76355. ShadowGenerator.prototype._initializeShadowMap = function () {
  76356. var _this = this;
  76357. // Render target
  76358. var engine = this._scene.getEngine();
  76359. if (engine.webGLVersion > 1) {
  76360. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  76361. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  76362. }
  76363. else {
  76364. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  76365. }
  76366. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76367. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76368. this._shadowMap.anisotropicFilteringLevel = 1;
  76369. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76370. this._shadowMap.renderParticles = false;
  76371. this._shadowMap.ignoreCameraViewport = true;
  76372. // Record Face Index before render.
  76373. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  76374. _this._currentFaceIndex = faceIndex;
  76375. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76376. engine.setColorWrite(false);
  76377. }
  76378. });
  76379. // Custom render function.
  76380. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  76381. // Blur if required afer render.
  76382. this._shadowMap.onAfterUnbindObservable.add(function () {
  76383. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76384. engine.setColorWrite(true);
  76385. }
  76386. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  76387. return;
  76388. }
  76389. var shadowMap = _this.getShadowMapForRendering();
  76390. if (shadowMap) {
  76391. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  76392. }
  76393. });
  76394. // Clear according to the chosen filter.
  76395. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  76396. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  76397. this._shadowMap.onClearObservable.add(function (engine) {
  76398. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76399. engine.clear(clearOne, false, true, false);
  76400. }
  76401. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  76402. engine.clear(clearZero, true, true, false);
  76403. }
  76404. else {
  76405. engine.clear(clearOne, true, true, false);
  76406. }
  76407. });
  76408. };
  76409. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  76410. var _this = this;
  76411. var engine = this._scene.getEngine();
  76412. var targetSize = this._mapSize / this.blurScale;
  76413. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  76414. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  76415. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76416. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76417. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76418. }
  76419. if (this.useKernelBlur) {
  76420. 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);
  76421. this._kernelBlurXPostprocess.width = targetSize;
  76422. this._kernelBlurXPostprocess.height = targetSize;
  76423. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  76424. effect.setTexture("textureSampler", _this._shadowMap);
  76425. });
  76426. 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);
  76427. this._kernelBlurXPostprocess.autoClear = false;
  76428. this._kernelBlurYPostprocess.autoClear = false;
  76429. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76430. this._kernelBlurXPostprocess.packedFloat = true;
  76431. this._kernelBlurYPostprocess.packedFloat = true;
  76432. }
  76433. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  76434. }
  76435. else {
  76436. 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);
  76437. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  76438. effect.setFloat2("screenSize", targetSize, targetSize);
  76439. effect.setTexture("textureSampler", _this._shadowMap);
  76440. });
  76441. this._boxBlurPostprocess.autoClear = false;
  76442. this._blurPostProcesses = [this._boxBlurPostprocess];
  76443. }
  76444. };
  76445. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76446. var index;
  76447. var engine = this._scene.getEngine();
  76448. if (depthOnlySubMeshes.length) {
  76449. engine.setColorWrite(false);
  76450. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76451. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  76452. }
  76453. engine.setColorWrite(true);
  76454. }
  76455. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76456. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  76457. }
  76458. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76459. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  76460. }
  76461. if (this._transparencyShadow) {
  76462. for (index = 0; index < transparentSubMeshes.length; index++) {
  76463. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  76464. }
  76465. }
  76466. };
  76467. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  76468. var _this = this;
  76469. var mesh = subMesh.getRenderingMesh();
  76470. var scene = this._scene;
  76471. var engine = scene.getEngine();
  76472. var material = subMesh.getMaterial();
  76473. if (!material || subMesh.verticesCount === 0) {
  76474. return;
  76475. }
  76476. // Culling
  76477. engine.setState(material.backFaceCulling);
  76478. // Managing instances
  76479. var batch = mesh._getInstancesRenderList(subMesh._id);
  76480. if (batch.mustReturn) {
  76481. return;
  76482. }
  76483. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76484. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  76485. engine.enableEffect(this._effect);
  76486. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76487. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  76488. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  76489. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76490. this._effect.setVector3("lightData", this._cachedDirection);
  76491. }
  76492. else {
  76493. this._effect.setVector3("lightData", this._cachedPosition);
  76494. }
  76495. if (scene.activeCamera) {
  76496. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  76497. }
  76498. // Alpha test
  76499. if (material && material.needAlphaTesting()) {
  76500. var alphaTexture = material.getAlphaTestTexture();
  76501. if (alphaTexture) {
  76502. this._effect.setTexture("diffuseSampler", alphaTexture);
  76503. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  76504. }
  76505. }
  76506. // Bones
  76507. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76508. var skeleton = mesh.skeleton;
  76509. if (skeleton.isUsingTextureForMatrices) {
  76510. var boneTexture = skeleton.getTransformMatrixTexture();
  76511. if (!boneTexture) {
  76512. return;
  76513. }
  76514. this._effect.setTexture("boneSampler", boneTexture);
  76515. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  76516. }
  76517. else {
  76518. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  76519. }
  76520. }
  76521. // Morph targets
  76522. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  76523. if (this.forceBackFacesOnly) {
  76524. engine.setState(true, 0, false, true);
  76525. }
  76526. // Draw
  76527. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76528. if (this.forceBackFacesOnly) {
  76529. engine.setState(true, 0, false, false);
  76530. }
  76531. }
  76532. else {
  76533. // Need to reset refresh rate of the shadowMap
  76534. if (this._shadowMap) {
  76535. this._shadowMap.resetRefreshCounter();
  76536. }
  76537. }
  76538. };
  76539. ShadowGenerator.prototype._applyFilterValues = function () {
  76540. if (!this._shadowMap) {
  76541. return;
  76542. }
  76543. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  76544. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  76545. }
  76546. else {
  76547. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76548. }
  76549. };
  76550. /**
  76551. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76552. * @param onCompiled Callback triggered at the and of the effects compilation
  76553. * @param options Sets of optional options forcing the compilation with different modes
  76554. */
  76555. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  76556. var _this = this;
  76557. var localOptions = __assign({ useInstances: false }, options);
  76558. var shadowMap = this.getShadowMap();
  76559. if (!shadowMap) {
  76560. if (onCompiled) {
  76561. onCompiled(this);
  76562. }
  76563. return;
  76564. }
  76565. var renderList = shadowMap.renderList;
  76566. if (!renderList) {
  76567. if (onCompiled) {
  76568. onCompiled(this);
  76569. }
  76570. return;
  76571. }
  76572. var subMeshes = new Array();
  76573. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  76574. var mesh = renderList_1[_i];
  76575. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  76576. }
  76577. if (subMeshes.length === 0) {
  76578. if (onCompiled) {
  76579. onCompiled(this);
  76580. }
  76581. return;
  76582. }
  76583. var currentIndex = 0;
  76584. var checkReady = function () {
  76585. if (!_this._scene || !_this._scene.getEngine()) {
  76586. return;
  76587. }
  76588. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  76589. currentIndex++;
  76590. if (currentIndex >= subMeshes.length) {
  76591. if (onCompiled) {
  76592. onCompiled(_this);
  76593. }
  76594. return;
  76595. }
  76596. }
  76597. setTimeout(checkReady, 16);
  76598. };
  76599. checkReady();
  76600. };
  76601. /**
  76602. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76603. * @param options Sets of optional options forcing the compilation with different modes
  76604. * @returns A promise that resolves when the compilation completes
  76605. */
  76606. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  76607. var _this = this;
  76608. return new Promise(function (resolve) {
  76609. _this.forceCompilation(function () {
  76610. resolve();
  76611. }, options);
  76612. });
  76613. };
  76614. /**
  76615. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  76616. * @param subMesh The submesh we want to render in the shadow map
  76617. * @param useInstances Defines wether will draw in the map using instances
  76618. * @returns true if ready otherwise, false
  76619. */
  76620. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  76621. var defines = [];
  76622. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76623. defines.push("#define FLOAT");
  76624. }
  76625. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76626. defines.push("#define ESM");
  76627. }
  76628. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  76629. defines.push("#define DEPTHTEXTURE");
  76630. }
  76631. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76632. var mesh = subMesh.getMesh();
  76633. var material = subMesh.getMaterial();
  76634. // Normal bias.
  76635. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76636. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76637. defines.push("#define NORMAL");
  76638. if (mesh.nonUniformScaling) {
  76639. defines.push("#define NONUNIFORMSCALING");
  76640. }
  76641. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76642. defines.push("#define DIRECTIONINLIGHTDATA");
  76643. }
  76644. }
  76645. // Alpha test
  76646. if (material && material.needAlphaTesting()) {
  76647. var alphaTexture = material.getAlphaTestTexture();
  76648. if (alphaTexture) {
  76649. defines.push("#define ALPHATEST");
  76650. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76651. attribs.push(BABYLON.VertexBuffer.UVKind);
  76652. defines.push("#define UV1");
  76653. }
  76654. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76655. if (alphaTexture.coordinatesIndex === 1) {
  76656. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76657. defines.push("#define UV2");
  76658. }
  76659. }
  76660. }
  76661. }
  76662. // Bones
  76663. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76664. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76665. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76666. if (mesh.numBoneInfluencers > 4) {
  76667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76669. }
  76670. var skeleton = mesh.skeleton;
  76671. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76672. if (skeleton.isUsingTextureForMatrices) {
  76673. defines.push("#define BONETEXTURE");
  76674. }
  76675. else {
  76676. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  76677. }
  76678. }
  76679. else {
  76680. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76681. }
  76682. // Morph targets
  76683. var manager = mesh.morphTargetManager;
  76684. var morphInfluencers = 0;
  76685. if (manager) {
  76686. if (manager.numInfluencers > 0) {
  76687. defines.push("#define MORPHTARGETS");
  76688. morphInfluencers = manager.numInfluencers;
  76689. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  76690. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  76691. }
  76692. }
  76693. // Instances
  76694. if (useInstances) {
  76695. defines.push("#define INSTANCES");
  76696. attribs.push("world0");
  76697. attribs.push("world1");
  76698. attribs.push("world2");
  76699. attribs.push("world3");
  76700. }
  76701. // Get correct effect
  76702. var join = defines.join("\n");
  76703. if (this._cachedDefines !== join) {
  76704. this._cachedDefines = join;
  76705. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"], ["diffuseSampler", "boneSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  76706. }
  76707. if (!this._effect.isReady()) {
  76708. return false;
  76709. }
  76710. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76711. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  76712. this._initializeBlurRTTAndPostProcesses();
  76713. }
  76714. }
  76715. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  76716. return false;
  76717. }
  76718. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  76719. return false;
  76720. }
  76721. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  76722. return false;
  76723. }
  76724. return true;
  76725. };
  76726. /**
  76727. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  76728. * @param defines Defines of the material we want to update
  76729. * @param lightIndex Index of the light in the enabled light list of the material
  76730. */
  76731. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  76732. var scene = this._scene;
  76733. var light = this._light;
  76734. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76735. return;
  76736. }
  76737. defines["SHADOW" + lightIndex] = true;
  76738. if (this.useContactHardeningShadow) {
  76739. defines["SHADOWPCSS" + lightIndex] = true;
  76740. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76741. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76742. }
  76743. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76744. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76745. }
  76746. // else default to high.
  76747. }
  76748. if (this.usePercentageCloserFiltering) {
  76749. defines["SHADOWPCF" + lightIndex] = true;
  76750. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76751. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76752. }
  76753. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76754. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76755. }
  76756. // else default to high.
  76757. }
  76758. else if (this.usePoissonSampling) {
  76759. defines["SHADOWPOISSON" + lightIndex] = true;
  76760. }
  76761. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76762. defines["SHADOWESM" + lightIndex] = true;
  76763. }
  76764. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76765. defines["SHADOWCLOSEESM" + lightIndex] = true;
  76766. }
  76767. if (light.needCube()) {
  76768. defines["SHADOWCUBE" + lightIndex] = true;
  76769. }
  76770. };
  76771. /**
  76772. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  76773. * defined in the generator but impacting the effect).
  76774. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  76775. * @param effect The effect we are binfing the information for
  76776. */
  76777. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  76778. var light = this._light;
  76779. var scene = this._scene;
  76780. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76781. return;
  76782. }
  76783. var camera = scene.activeCamera;
  76784. if (!camera) {
  76785. return;
  76786. }
  76787. var shadowMap = this.getShadowMap();
  76788. if (!shadowMap) {
  76789. return;
  76790. }
  76791. if (!light.needCube()) {
  76792. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  76793. }
  76794. // Only PCF uses depth stencil texture.
  76795. if (this._filter === ShadowGenerator.FILTER_PCF) {
  76796. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76797. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76798. }
  76799. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  76800. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76801. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  76802. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76803. }
  76804. else {
  76805. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76806. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  76807. }
  76808. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  76809. };
  76810. /**
  76811. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  76812. * (eq to shadow prjection matrix * light transform matrix)
  76813. * @returns The transform matrix used to create the shadow map
  76814. */
  76815. ShadowGenerator.prototype.getTransformMatrix = function () {
  76816. var scene = this._scene;
  76817. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  76818. return this._transformMatrix;
  76819. }
  76820. this._currentRenderID = scene.getRenderId();
  76821. this._currentFaceIndexCache = this._currentFaceIndex;
  76822. var lightPosition = this._light.position;
  76823. if (this._light.computeTransformedInformation()) {
  76824. lightPosition = this._light.transformedPosition;
  76825. }
  76826. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  76827. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  76828. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  76829. }
  76830. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  76831. this._cachedPosition.copyFrom(lightPosition);
  76832. this._cachedDirection.copyFrom(this._lightDirection);
  76833. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  76834. var shadowMap = this.getShadowMap();
  76835. if (shadowMap) {
  76836. var renderList = shadowMap.renderList;
  76837. if (renderList) {
  76838. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  76839. }
  76840. }
  76841. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  76842. }
  76843. return this._transformMatrix;
  76844. };
  76845. /**
  76846. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  76847. * Cube and 2D textures for instance.
  76848. */
  76849. ShadowGenerator.prototype.recreateShadowMap = function () {
  76850. var shadowMap = this._shadowMap;
  76851. if (!shadowMap) {
  76852. return;
  76853. }
  76854. // Track render list.
  76855. var renderList = shadowMap.renderList;
  76856. // Clean up existing data.
  76857. this._disposeRTTandPostProcesses();
  76858. // Reinitializes.
  76859. this._initializeGenerator();
  76860. // Reaffect the filter to ensure a correct fallback if necessary.
  76861. this.filter = this.filter;
  76862. // Reaffect the filter.
  76863. this._applyFilterValues();
  76864. // Reaffect Render List.
  76865. this._shadowMap.renderList = renderList;
  76866. };
  76867. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  76868. if (this._shadowMap2) {
  76869. this._shadowMap2.dispose();
  76870. this._shadowMap2 = null;
  76871. }
  76872. if (this._boxBlurPostprocess) {
  76873. this._boxBlurPostprocess.dispose();
  76874. this._boxBlurPostprocess = null;
  76875. }
  76876. if (this._kernelBlurXPostprocess) {
  76877. this._kernelBlurXPostprocess.dispose();
  76878. this._kernelBlurXPostprocess = null;
  76879. }
  76880. if (this._kernelBlurYPostprocess) {
  76881. this._kernelBlurYPostprocess.dispose();
  76882. this._kernelBlurYPostprocess = null;
  76883. }
  76884. this._blurPostProcesses = [];
  76885. };
  76886. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  76887. if (this._shadowMap) {
  76888. this._shadowMap.dispose();
  76889. this._shadowMap = null;
  76890. }
  76891. this._disposeBlurPostProcesses();
  76892. };
  76893. /**
  76894. * Disposes the ShadowGenerator.
  76895. * Returns nothing.
  76896. */
  76897. ShadowGenerator.prototype.dispose = function () {
  76898. this._disposeRTTandPostProcesses();
  76899. if (this._light) {
  76900. this._light._shadowGenerator = null;
  76901. this._light._markMeshesAsLightDirty();
  76902. }
  76903. };
  76904. /**
  76905. * Serializes the shadow generator setup to a json object.
  76906. * @returns The serialized JSON object
  76907. */
  76908. ShadowGenerator.prototype.serialize = function () {
  76909. var serializationObject = {};
  76910. var shadowMap = this.getShadowMap();
  76911. if (!shadowMap) {
  76912. return serializationObject;
  76913. }
  76914. serializationObject.lightId = this._light.id;
  76915. serializationObject.mapSize = shadowMap.getRenderSize();
  76916. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  76917. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  76918. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76919. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76920. serializationObject.usePoissonSampling = this.usePoissonSampling;
  76921. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  76922. serializationObject.depthScale = this.depthScale;
  76923. serializationObject.darkness = this.getDarkness();
  76924. serializationObject.blurBoxOffset = this.blurBoxOffset;
  76925. serializationObject.blurKernel = this.blurKernel;
  76926. serializationObject.blurScale = this.blurScale;
  76927. serializationObject.useKernelBlur = this.useKernelBlur;
  76928. serializationObject.transparencyShadow = this._transparencyShadow;
  76929. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  76930. serializationObject.bias = this.bias;
  76931. serializationObject.normalBias = this.normalBias;
  76932. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  76933. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  76934. serializationObject.filteringQuality = this.filteringQuality;
  76935. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  76936. serializationObject.renderList = [];
  76937. if (shadowMap.renderList) {
  76938. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  76939. var mesh = shadowMap.renderList[meshIndex];
  76940. serializationObject.renderList.push(mesh.id);
  76941. }
  76942. }
  76943. return serializationObject;
  76944. };
  76945. /**
  76946. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  76947. * @param parsedShadowGenerator The JSON object to parse
  76948. * @param scene The scene to create the shadow map for
  76949. * @returns The parsed shadow generator
  76950. */
  76951. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  76952. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  76953. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  76954. var shadowMap = shadowGenerator.getShadowMap();
  76955. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  76956. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  76957. meshes.forEach(function (mesh) {
  76958. if (!shadowMap) {
  76959. return;
  76960. }
  76961. if (!shadowMap.renderList) {
  76962. shadowMap.renderList = [];
  76963. }
  76964. shadowMap.renderList.push(mesh);
  76965. });
  76966. }
  76967. if (parsedShadowGenerator.usePoissonSampling) {
  76968. shadowGenerator.usePoissonSampling = true;
  76969. }
  76970. else if (parsedShadowGenerator.useExponentialShadowMap) {
  76971. shadowGenerator.useExponentialShadowMap = true;
  76972. }
  76973. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  76974. shadowGenerator.useBlurExponentialShadowMap = true;
  76975. }
  76976. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  76977. shadowGenerator.useCloseExponentialShadowMap = true;
  76978. }
  76979. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  76980. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  76981. }
  76982. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  76983. shadowGenerator.usePercentageCloserFiltering = true;
  76984. }
  76985. else if (parsedShadowGenerator.useContactHardeningShadow) {
  76986. shadowGenerator.useContactHardeningShadow = true;
  76987. }
  76988. if (parsedShadowGenerator.filteringQuality) {
  76989. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  76990. }
  76991. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  76992. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  76993. }
  76994. // Backward compat
  76995. else if (parsedShadowGenerator.useVarianceShadowMap) {
  76996. shadowGenerator.useExponentialShadowMap = true;
  76997. }
  76998. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  76999. shadowGenerator.useBlurExponentialShadowMap = true;
  77000. }
  77001. if (parsedShadowGenerator.depthScale) {
  77002. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  77003. }
  77004. if (parsedShadowGenerator.blurScale) {
  77005. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  77006. }
  77007. if (parsedShadowGenerator.blurBoxOffset) {
  77008. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  77009. }
  77010. if (parsedShadowGenerator.useKernelBlur) {
  77011. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  77012. }
  77013. if (parsedShadowGenerator.blurKernel) {
  77014. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  77015. }
  77016. if (parsedShadowGenerator.bias !== undefined) {
  77017. shadowGenerator.bias = parsedShadowGenerator.bias;
  77018. }
  77019. if (parsedShadowGenerator.normalBias !== undefined) {
  77020. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  77021. }
  77022. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  77023. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  77024. }
  77025. if (parsedShadowGenerator.darkness) {
  77026. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  77027. }
  77028. if (parsedShadowGenerator.transparencyShadow) {
  77029. shadowGenerator.setTransparencyShadow(true);
  77030. }
  77031. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  77032. return shadowGenerator;
  77033. };
  77034. /**
  77035. * Shadow generator mode None: no filtering applied.
  77036. */
  77037. ShadowGenerator.FILTER_NONE = 0;
  77038. /**
  77039. * Shadow generator mode ESM: Exponential Shadow Mapping.
  77040. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77041. */
  77042. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  77043. /**
  77044. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  77045. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  77046. */
  77047. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  77048. /**
  77049. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  77050. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77051. */
  77052. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  77053. /**
  77054. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  77055. * edge artifacts on steep falloff.
  77056. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77057. */
  77058. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  77059. /**
  77060. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  77061. * edge artifacts on steep falloff.
  77062. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77063. */
  77064. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  77065. /**
  77066. * Shadow generator mode PCF: Percentage Closer Filtering
  77067. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77068. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  77069. */
  77070. ShadowGenerator.FILTER_PCF = 6;
  77071. /**
  77072. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  77073. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77074. * Contact Hardening
  77075. */
  77076. ShadowGenerator.FILTER_PCSS = 7;
  77077. /**
  77078. * Reserved for PCF and PCSS
  77079. * Highest Quality.
  77080. *
  77081. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  77082. *
  77083. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  77084. */
  77085. ShadowGenerator.QUALITY_HIGH = 0;
  77086. /**
  77087. * Reserved for PCF and PCSS
  77088. * Good tradeoff for quality/perf cross devices
  77089. *
  77090. * Execute PCF on a 3*3 kernel.
  77091. *
  77092. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  77093. */
  77094. ShadowGenerator.QUALITY_MEDIUM = 1;
  77095. /**
  77096. * Reserved for PCF and PCSS
  77097. * The lowest quality but the fastest.
  77098. *
  77099. * Execute PCF on a 1*1 kernel.
  77100. *
  77101. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  77102. */
  77103. ShadowGenerator.QUALITY_LOW = 2;
  77104. return ShadowGenerator;
  77105. }());
  77106. BABYLON.ShadowGenerator = ShadowGenerator;
  77107. })(BABYLON || (BABYLON = {}));
  77108. //# sourceMappingURL=babylon.shadowGenerator.js.map
  77109. var BABYLON;
  77110. (function (BABYLON) {
  77111. // Adds the parser to the scene parsers.
  77112. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  77113. // Shadows
  77114. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  77115. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  77116. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  77117. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  77118. // SG would be available on their associated lights
  77119. }
  77120. }
  77121. });
  77122. /**
  77123. * Defines the shadow generator component responsible to manage any shadow generators
  77124. * in a given scene.
  77125. */
  77126. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  77127. /**
  77128. * Creates a new instance of the component for the given scene
  77129. * @param scene Defines the scene to register the component in
  77130. */
  77131. function ShadowGeneratorSceneComponent(scene) {
  77132. /**
  77133. * The component name helpfull to identify the component in the list of scene components.
  77134. */
  77135. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  77136. this.scene = scene;
  77137. }
  77138. /**
  77139. * Registers the component in a given scene
  77140. */
  77141. ShadowGeneratorSceneComponent.prototype.register = function () {
  77142. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  77143. };
  77144. /**
  77145. * Rebuilds the elements related to this component in case of
  77146. * context lost for instance.
  77147. */
  77148. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  77149. // Nothing To Do Here.
  77150. };
  77151. /**
  77152. * Serializes the component data to the specified json object
  77153. * @param serializationObject The object to serialize to
  77154. */
  77155. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  77156. // Shadows
  77157. serializationObject.shadowGenerators = [];
  77158. var lights = this.scene.lights;
  77159. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  77160. var light = lights_1[_i];
  77161. var shadowGenerator = light.getShadowGenerator();
  77162. if (shadowGenerator) {
  77163. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77164. }
  77165. }
  77166. };
  77167. /**
  77168. * Adds all the element from the container to the scene
  77169. * @param container the container holding the elements
  77170. */
  77171. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  77172. // Nothing To Do Here. (directly attached to a light)
  77173. };
  77174. /**
  77175. * Removes all the elements in the container from the scene
  77176. * @param container contains the elements to remove
  77177. */
  77178. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  77179. // Nothing To Do Here. (directly attached to a light)
  77180. };
  77181. /**
  77182. * Rebuilds the elements related to this component in case of
  77183. * context lost for instance.
  77184. */
  77185. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  77186. // Nothing To Do Here.
  77187. };
  77188. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77189. // Shadows
  77190. var scene = this.scene;
  77191. if (this.scene.shadowsEnabled) {
  77192. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  77193. var light = scene.lights[lightIndex];
  77194. var shadowGenerator = light.getShadowGenerator();
  77195. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  77196. var shadowMap = (shadowGenerator.getShadowMap());
  77197. if (scene.textures.indexOf(shadowMap) !== -1) {
  77198. renderTargets.push(shadowMap);
  77199. }
  77200. }
  77201. }
  77202. }
  77203. };
  77204. return ShadowGeneratorSceneComponent;
  77205. }());
  77206. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  77207. })(BABYLON || (BABYLON = {}));
  77208. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  77209. var BABYLON;
  77210. (function (BABYLON) {
  77211. /**
  77212. * Class used for the default loading screen
  77213. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77214. */
  77215. var DefaultLoadingScreen = /** @class */ (function () {
  77216. /**
  77217. * Creates a new default loading screen
  77218. * @param _renderingCanvas defines the canvas used to render the scene
  77219. * @param _loadingText defines the default text to display
  77220. * @param _loadingDivBackgroundColor defines the default background color
  77221. */
  77222. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  77223. if (_loadingText === void 0) { _loadingText = ""; }
  77224. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  77225. var _this = this;
  77226. this._renderingCanvas = _renderingCanvas;
  77227. this._loadingText = _loadingText;
  77228. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  77229. // Resize
  77230. this._resizeLoadingUI = function () {
  77231. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  77232. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  77233. if (!_this._loadingDiv) {
  77234. return;
  77235. }
  77236. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  77237. _this._loadingDiv.style.left = canvasRect.left + "px";
  77238. _this._loadingDiv.style.top = canvasRect.top + "px";
  77239. _this._loadingDiv.style.width = canvasRect.width + "px";
  77240. _this._loadingDiv.style.height = canvasRect.height + "px";
  77241. };
  77242. }
  77243. /**
  77244. * Function called to display the loading screen
  77245. */
  77246. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  77247. if (this._loadingDiv) {
  77248. // Do not add a loading screen if there is already one
  77249. return;
  77250. }
  77251. this._loadingDiv = document.createElement("div");
  77252. this._loadingDiv.id = "babylonjsLoadingDiv";
  77253. this._loadingDiv.style.opacity = "0";
  77254. this._loadingDiv.style.transition = "opacity 1.5s ease";
  77255. this._loadingDiv.style.pointerEvents = "none";
  77256. // Loading text
  77257. this._loadingTextDiv = document.createElement("div");
  77258. this._loadingTextDiv.style.position = "absolute";
  77259. this._loadingTextDiv.style.left = "0";
  77260. this._loadingTextDiv.style.top = "50%";
  77261. this._loadingTextDiv.style.marginTop = "80px";
  77262. this._loadingTextDiv.style.width = "100%";
  77263. this._loadingTextDiv.style.height = "20px";
  77264. this._loadingTextDiv.style.fontFamily = "Arial";
  77265. this._loadingTextDiv.style.fontSize = "14px";
  77266. this._loadingTextDiv.style.color = "white";
  77267. this._loadingTextDiv.style.textAlign = "center";
  77268. this._loadingTextDiv.innerHTML = "Loading";
  77269. this._loadingDiv.appendChild(this._loadingTextDiv);
  77270. //set the predefined text
  77271. this._loadingTextDiv.innerHTML = this._loadingText;
  77272. // Generating keyframes
  77273. var style = document.createElement('style');
  77274. style.type = 'text/css';
  77275. 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 }";
  77276. style.innerHTML = keyFrames;
  77277. document.getElementsByTagName('head')[0].appendChild(style);
  77278. // Loading img
  77279. var imgBack = new Image();
  77280. 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";
  77281. imgBack.style.position = "absolute";
  77282. imgBack.style.left = "50%";
  77283. imgBack.style.top = "50%";
  77284. imgBack.style.marginLeft = "-60px";
  77285. imgBack.style.marginTop = "-60px";
  77286. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  77287. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  77288. imgBack.style.transformOrigin = "50% 50%";
  77289. imgBack.style.webkitTransformOrigin = "50% 50%";
  77290. this._loadingDiv.appendChild(imgBack);
  77291. this._resizeLoadingUI();
  77292. window.addEventListener("resize", this._resizeLoadingUI);
  77293. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77294. document.body.appendChild(this._loadingDiv);
  77295. this._loadingDiv.style.opacity = "1";
  77296. };
  77297. /**
  77298. * Function called to hide the loading screen
  77299. */
  77300. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  77301. var _this = this;
  77302. if (!this._loadingDiv) {
  77303. return;
  77304. }
  77305. var onTransitionEnd = function () {
  77306. if (!_this._loadingDiv) {
  77307. return;
  77308. }
  77309. document.body.removeChild(_this._loadingDiv);
  77310. window.removeEventListener("resize", _this._resizeLoadingUI);
  77311. _this._loadingDiv = null;
  77312. };
  77313. this._loadingDiv.style.opacity = "0";
  77314. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  77315. };
  77316. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  77317. get: function () {
  77318. return this._loadingText;
  77319. },
  77320. /**
  77321. * Gets or sets the text to display while loading
  77322. */
  77323. set: function (text) {
  77324. this._loadingText = text;
  77325. if (this._loadingTextDiv) {
  77326. this._loadingTextDiv.innerHTML = this._loadingText;
  77327. }
  77328. },
  77329. enumerable: true,
  77330. configurable: true
  77331. });
  77332. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  77333. /**
  77334. * Gets or sets the color to use for the background
  77335. */
  77336. get: function () {
  77337. return this._loadingDivBackgroundColor;
  77338. },
  77339. set: function (color) {
  77340. this._loadingDivBackgroundColor = color;
  77341. if (!this._loadingDiv) {
  77342. return;
  77343. }
  77344. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77345. },
  77346. enumerable: true,
  77347. configurable: true
  77348. });
  77349. return DefaultLoadingScreen;
  77350. }());
  77351. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  77352. })(BABYLON || (BABYLON = {}));
  77353. //# sourceMappingURL=babylon.loadingScreen.js.map
  77354. var BABYLON;
  77355. (function (BABYLON) {
  77356. /**
  77357. * Class used to represent data loading progression
  77358. */
  77359. var SceneLoaderProgressEvent = /** @class */ (function () {
  77360. /**
  77361. * Create a new progress event
  77362. * @param lengthComputable defines if data length to load can be evaluated
  77363. * @param loaded defines the loaded data length
  77364. * @param total defines the data length to load
  77365. */
  77366. function SceneLoaderProgressEvent(
  77367. /** defines if data length to load can be evaluated */
  77368. lengthComputable,
  77369. /** defines the loaded data length */
  77370. loaded,
  77371. /** defines the data length to load */
  77372. total) {
  77373. this.lengthComputable = lengthComputable;
  77374. this.loaded = loaded;
  77375. this.total = total;
  77376. }
  77377. /**
  77378. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  77379. * @param event defines the source event
  77380. * @returns a new SceneLoaderProgressEvent
  77381. */
  77382. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  77383. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  77384. };
  77385. return SceneLoaderProgressEvent;
  77386. }());
  77387. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  77388. /**
  77389. * Class used to load scene from various file formats using registered plugins
  77390. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  77391. */
  77392. var SceneLoader = /** @class */ (function () {
  77393. function SceneLoader() {
  77394. }
  77395. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  77396. /**
  77397. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  77398. */
  77399. get: function () {
  77400. return SceneLoader._ForceFullSceneLoadingForIncremental;
  77401. },
  77402. set: function (value) {
  77403. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  77404. },
  77405. enumerable: true,
  77406. configurable: true
  77407. });
  77408. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  77409. /**
  77410. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  77411. */
  77412. get: function () {
  77413. return SceneLoader._ShowLoadingScreen;
  77414. },
  77415. set: function (value) {
  77416. SceneLoader._ShowLoadingScreen = value;
  77417. },
  77418. enumerable: true,
  77419. configurable: true
  77420. });
  77421. Object.defineProperty(SceneLoader, "loggingLevel", {
  77422. /**
  77423. * Defines the current logging level (while loading the scene)
  77424. * @ignorenaming
  77425. */
  77426. get: function () {
  77427. return SceneLoader._loggingLevel;
  77428. },
  77429. set: function (value) {
  77430. SceneLoader._loggingLevel = value;
  77431. },
  77432. enumerable: true,
  77433. configurable: true
  77434. });
  77435. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  77436. /**
  77437. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  77438. */
  77439. get: function () {
  77440. return SceneLoader._CleanBoneMatrixWeights;
  77441. },
  77442. set: function (value) {
  77443. SceneLoader._CleanBoneMatrixWeights = value;
  77444. },
  77445. enumerable: true,
  77446. configurable: true
  77447. });
  77448. SceneLoader._getDefaultPlugin = function () {
  77449. return SceneLoader._registeredPlugins[".babylon"];
  77450. };
  77451. SceneLoader._getPluginForExtension = function (extension) {
  77452. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  77453. if (registeredPlugin) {
  77454. return registeredPlugin;
  77455. }
  77456. 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");
  77457. return SceneLoader._getDefaultPlugin();
  77458. };
  77459. SceneLoader._getPluginForDirectLoad = function (data) {
  77460. for (var extension in SceneLoader._registeredPlugins) {
  77461. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  77462. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  77463. return SceneLoader._registeredPlugins[extension];
  77464. }
  77465. }
  77466. return SceneLoader._getDefaultPlugin();
  77467. };
  77468. SceneLoader._getPluginForFilename = function (sceneFilename) {
  77469. var queryStringPosition = sceneFilename.indexOf("?");
  77470. if (queryStringPosition !== -1) {
  77471. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  77472. }
  77473. var dotPosition = sceneFilename.lastIndexOf(".");
  77474. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  77475. return SceneLoader._getPluginForExtension(extension);
  77476. };
  77477. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  77478. SceneLoader._getDirectLoad = function (sceneFilename) {
  77479. if (sceneFilename.substr(0, 5) === "data:") {
  77480. return sceneFilename.substr(5);
  77481. }
  77482. return null;
  77483. };
  77484. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  77485. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  77486. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  77487. var plugin;
  77488. if (registeredPlugin.plugin.createPlugin) {
  77489. plugin = registeredPlugin.plugin.createPlugin();
  77490. }
  77491. else {
  77492. plugin = registeredPlugin.plugin;
  77493. }
  77494. var useArrayBuffer = registeredPlugin.isBinary;
  77495. var offlineProvider;
  77496. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  77497. var dataCallback = function (data, responseURL) {
  77498. if (scene.isDisposed) {
  77499. onError("Scene has been disposed");
  77500. return;
  77501. }
  77502. scene.offlineProvider = offlineProvider;
  77503. onSuccess(plugin, data, responseURL);
  77504. };
  77505. var request = null;
  77506. var pluginDisposed = false;
  77507. var onDisposeObservable = plugin.onDisposeObservable;
  77508. if (onDisposeObservable) {
  77509. onDisposeObservable.add(function () {
  77510. pluginDisposed = true;
  77511. if (request) {
  77512. request.abort();
  77513. request = null;
  77514. }
  77515. onDispose();
  77516. });
  77517. }
  77518. var manifestChecked = function () {
  77519. if (pluginDisposed) {
  77520. return;
  77521. }
  77522. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  77523. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  77524. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  77525. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  77526. });
  77527. };
  77528. if (directLoad) {
  77529. dataCallback(directLoad);
  77530. return plugin;
  77531. }
  77532. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  77533. var engine = scene.getEngine();
  77534. var canUseOfflineSupport = engine.enableOfflineSupport;
  77535. if (canUseOfflineSupport) {
  77536. // Also check for exceptions
  77537. var exceptionFound = false;
  77538. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  77539. var regex = _a[_i];
  77540. if (regex.test(fileInfo.url)) {
  77541. exceptionFound = true;
  77542. break;
  77543. }
  77544. }
  77545. canUseOfflineSupport = !exceptionFound;
  77546. }
  77547. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  77548. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  77549. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  77550. }
  77551. else {
  77552. manifestChecked();
  77553. }
  77554. }
  77555. // Loading file from disk via input file or drag'n'drop
  77556. else {
  77557. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  77558. if (file) {
  77559. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  77560. }
  77561. else {
  77562. onError("Unable to find file named " + fileInfo.name);
  77563. }
  77564. }
  77565. return plugin;
  77566. };
  77567. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  77568. var url;
  77569. var name;
  77570. if (!sceneFilename) {
  77571. url = rootUrl;
  77572. name = BABYLON.Tools.GetFilename(rootUrl);
  77573. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  77574. }
  77575. else {
  77576. if (sceneFilename.substr(0, 1) === "/") {
  77577. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  77578. return null;
  77579. }
  77580. url = rootUrl + sceneFilename;
  77581. name = sceneFilename;
  77582. }
  77583. return {
  77584. url: url,
  77585. rootUrl: rootUrl,
  77586. name: name
  77587. };
  77588. };
  77589. // Public functions
  77590. /**
  77591. * Gets a plugin that can load the given extension
  77592. * @param extension defines the extension to load
  77593. * @returns a plugin or null if none works
  77594. */
  77595. SceneLoader.GetPluginForExtension = function (extension) {
  77596. return SceneLoader._getPluginForExtension(extension).plugin;
  77597. };
  77598. /**
  77599. * Gets a boolean indicating that the given extension can be loaded
  77600. * @param extension defines the extension to load
  77601. * @returns true if the extension is supported
  77602. */
  77603. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  77604. return !!SceneLoader._registeredPlugins[extension];
  77605. };
  77606. /**
  77607. * Adds a new plugin to the list of registered plugins
  77608. * @param plugin defines the plugin to add
  77609. */
  77610. SceneLoader.RegisterPlugin = function (plugin) {
  77611. if (typeof plugin.extensions === "string") {
  77612. var extension = plugin.extensions;
  77613. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77614. plugin: plugin,
  77615. isBinary: false
  77616. };
  77617. }
  77618. else {
  77619. var extensions = plugin.extensions;
  77620. Object.keys(extensions).forEach(function (extension) {
  77621. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77622. plugin: plugin,
  77623. isBinary: extensions[extension].isBinary
  77624. };
  77625. });
  77626. }
  77627. };
  77628. /**
  77629. * Import meshes into a scene
  77630. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77631. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77632. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77633. * @param scene the instance of BABYLON.Scene to append to
  77634. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  77635. * @param onProgress a callback with a progress event for each file being loaded
  77636. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77637. * @param pluginExtension the extension used to determine the plugin
  77638. * @returns The loaded plugin
  77639. */
  77640. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77641. if (sceneFilename === void 0) { sceneFilename = ""; }
  77642. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77643. if (onSuccess === void 0) { onSuccess = null; }
  77644. if (onProgress === void 0) { onProgress = null; }
  77645. if (onError === void 0) { onError = null; }
  77646. if (pluginExtension === void 0) { pluginExtension = null; }
  77647. if (!scene) {
  77648. BABYLON.Tools.Error("No scene available to import mesh to");
  77649. return null;
  77650. }
  77651. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77652. if (!fileInfo) {
  77653. return null;
  77654. }
  77655. var loadingToken = {};
  77656. scene._addPendingData(loadingToken);
  77657. var disposeHandler = function () {
  77658. scene._removePendingData(loadingToken);
  77659. };
  77660. var errorHandler = function (message, exception) {
  77661. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  77662. if (onError) {
  77663. onError(scene, errorMessage, exception);
  77664. }
  77665. else {
  77666. BABYLON.Tools.Error(errorMessage);
  77667. // should the exception be thrown?
  77668. }
  77669. disposeHandler();
  77670. };
  77671. var progressHandler = onProgress ? function (event) {
  77672. try {
  77673. onProgress(event);
  77674. }
  77675. catch (e) {
  77676. errorHandler("Error in onProgress callback", e);
  77677. }
  77678. } : undefined;
  77679. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  77680. scene.importedMeshesFiles.push(fileInfo.url);
  77681. if (onSuccess) {
  77682. try {
  77683. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  77684. }
  77685. catch (e) {
  77686. errorHandler("Error in onSuccess callback", e);
  77687. }
  77688. }
  77689. scene._removePendingData(loadingToken);
  77690. };
  77691. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77692. if (plugin.rewriteRootURL) {
  77693. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  77694. }
  77695. if (plugin.importMesh) {
  77696. var syncedPlugin = plugin;
  77697. var meshes = new Array();
  77698. var particleSystems = new Array();
  77699. var skeletons = new Array();
  77700. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  77701. return;
  77702. }
  77703. scene.loadingPluginName = plugin.name;
  77704. successHandler(meshes, particleSystems, skeletons, []);
  77705. }
  77706. else {
  77707. var asyncedPlugin = plugin;
  77708. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  77709. scene.loadingPluginName = plugin.name;
  77710. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  77711. }).catch(function (error) {
  77712. errorHandler(error.message, error);
  77713. });
  77714. }
  77715. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77716. };
  77717. /**
  77718. * Import meshes into a scene
  77719. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77720. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77721. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77722. * @param scene the instance of BABYLON.Scene to append to
  77723. * @param onProgress a callback with a progress event for each file being loaded
  77724. * @param pluginExtension the extension used to determine the plugin
  77725. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  77726. */
  77727. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77728. if (sceneFilename === void 0) { sceneFilename = ""; }
  77729. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77730. if (onProgress === void 0) { onProgress = null; }
  77731. if (pluginExtension === void 0) { pluginExtension = null; }
  77732. return new Promise(function (resolve, reject) {
  77733. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  77734. resolve({
  77735. meshes: meshes,
  77736. particleSystems: particleSystems,
  77737. skeletons: skeletons,
  77738. animationGroups: animationGroups
  77739. });
  77740. }, onProgress, function (scene, message, exception) {
  77741. reject(exception || new Error(message));
  77742. }, pluginExtension);
  77743. });
  77744. };
  77745. /**
  77746. * Load a scene
  77747. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77748. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77749. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77750. * @param onSuccess a callback with the scene when import succeeds
  77751. * @param onProgress a callback with a progress event for each file being loaded
  77752. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77753. * @param pluginExtension the extension used to determine the plugin
  77754. * @returns The loaded plugin
  77755. */
  77756. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  77757. if (onSuccess === void 0) { onSuccess = null; }
  77758. if (onProgress === void 0) { onProgress = null; }
  77759. if (onError === void 0) { onError = null; }
  77760. if (pluginExtension === void 0) { pluginExtension = null; }
  77761. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  77762. };
  77763. /**
  77764. * Load a scene
  77765. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77766. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77767. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77768. * @param onProgress a callback with a progress event for each file being loaded
  77769. * @param pluginExtension the extension used to determine the plugin
  77770. * @returns The loaded scene
  77771. */
  77772. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  77773. if (onProgress === void 0) { onProgress = null; }
  77774. if (pluginExtension === void 0) { pluginExtension = null; }
  77775. return new Promise(function (resolve, reject) {
  77776. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  77777. resolve(scene);
  77778. }, onProgress, function (scene, message, exception) {
  77779. reject(exception || new Error(message));
  77780. }, pluginExtension);
  77781. });
  77782. };
  77783. /**
  77784. * Append a scene
  77785. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77786. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77787. * @param scene is the instance of BABYLON.Scene to append to
  77788. * @param onSuccess a callback with the scene when import succeeds
  77789. * @param onProgress a callback with a progress event for each file being loaded
  77790. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77791. * @param pluginExtension the extension used to determine the plugin
  77792. * @returns The loaded plugin
  77793. */
  77794. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77795. if (sceneFilename === void 0) { sceneFilename = ""; }
  77796. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77797. if (onSuccess === void 0) { onSuccess = null; }
  77798. if (onProgress === void 0) { onProgress = null; }
  77799. if (onError === void 0) { onError = null; }
  77800. if (pluginExtension === void 0) { pluginExtension = null; }
  77801. if (!scene) {
  77802. BABYLON.Tools.Error("No scene available to append to");
  77803. return null;
  77804. }
  77805. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77806. if (!fileInfo) {
  77807. return null;
  77808. }
  77809. if (SceneLoader.ShowLoadingScreen) {
  77810. scene.getEngine().displayLoadingUI();
  77811. }
  77812. var loadingToken = {};
  77813. scene._addPendingData(loadingToken);
  77814. var disposeHandler = function () {
  77815. scene._removePendingData(loadingToken);
  77816. scene.getEngine().hideLoadingUI();
  77817. };
  77818. var errorHandler = function (message, exception) {
  77819. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  77820. if (onError) {
  77821. onError(scene, errorMessage, exception);
  77822. }
  77823. else {
  77824. BABYLON.Tools.Error(errorMessage);
  77825. // should the exception be thrown?
  77826. }
  77827. disposeHandler();
  77828. };
  77829. var progressHandler = onProgress ? function (event) {
  77830. try {
  77831. onProgress(event);
  77832. }
  77833. catch (e) {
  77834. errorHandler("Error in onProgress callback", e);
  77835. }
  77836. } : undefined;
  77837. var successHandler = function () {
  77838. if (onSuccess) {
  77839. try {
  77840. onSuccess(scene);
  77841. }
  77842. catch (e) {
  77843. errorHandler("Error in onSuccess callback", e);
  77844. }
  77845. }
  77846. scene._removePendingData(loadingToken);
  77847. };
  77848. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77849. if (plugin.load) {
  77850. var syncedPlugin = plugin;
  77851. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  77852. return;
  77853. }
  77854. scene.loadingPluginName = plugin.name;
  77855. successHandler();
  77856. }
  77857. else {
  77858. var asyncedPlugin = plugin;
  77859. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  77860. scene.loadingPluginName = plugin.name;
  77861. successHandler();
  77862. }).catch(function (error) {
  77863. errorHandler(error.message, error);
  77864. });
  77865. }
  77866. if (SceneLoader.ShowLoadingScreen) {
  77867. scene.executeWhenReady(function () {
  77868. scene.getEngine().hideLoadingUI();
  77869. });
  77870. }
  77871. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77872. };
  77873. /**
  77874. * Append a scene
  77875. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77876. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77877. * @param scene is the instance of BABYLON.Scene to append to
  77878. * @param onProgress a callback with a progress event for each file being loaded
  77879. * @param pluginExtension the extension used to determine the plugin
  77880. * @returns The given scene
  77881. */
  77882. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77883. if (sceneFilename === void 0) { sceneFilename = ""; }
  77884. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77885. if (onProgress === void 0) { onProgress = null; }
  77886. if (pluginExtension === void 0) { pluginExtension = null; }
  77887. return new Promise(function (resolve, reject) {
  77888. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  77889. resolve(scene);
  77890. }, onProgress, function (scene, message, exception) {
  77891. reject(exception || new Error(message));
  77892. }, pluginExtension);
  77893. });
  77894. };
  77895. /**
  77896. * Load a scene into an asset container
  77897. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77898. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77899. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  77900. * @param onSuccess a callback with the scene when import succeeds
  77901. * @param onProgress a callback with a progress event for each file being loaded
  77902. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77903. * @param pluginExtension the extension used to determine the plugin
  77904. * @returns The loaded plugin
  77905. */
  77906. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77907. if (sceneFilename === void 0) { sceneFilename = ""; }
  77908. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77909. if (onSuccess === void 0) { onSuccess = null; }
  77910. if (onProgress === void 0) { onProgress = null; }
  77911. if (onError === void 0) { onError = null; }
  77912. if (pluginExtension === void 0) { pluginExtension = null; }
  77913. if (!scene) {
  77914. BABYLON.Tools.Error("No scene available to load asset container to");
  77915. return null;
  77916. }
  77917. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77918. if (!fileInfo) {
  77919. return null;
  77920. }
  77921. var loadingToken = {};
  77922. scene._addPendingData(loadingToken);
  77923. var disposeHandler = function () {
  77924. scene._removePendingData(loadingToken);
  77925. };
  77926. var errorHandler = function (message, exception) {
  77927. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  77928. if (onError) {
  77929. onError(scene, errorMessage, exception);
  77930. }
  77931. else {
  77932. BABYLON.Tools.Error(errorMessage);
  77933. // should the exception be thrown?
  77934. }
  77935. disposeHandler();
  77936. };
  77937. var progressHandler = onProgress ? function (event) {
  77938. try {
  77939. onProgress(event);
  77940. }
  77941. catch (e) {
  77942. errorHandler("Error in onProgress callback", e);
  77943. }
  77944. } : undefined;
  77945. var successHandler = function (assets) {
  77946. if (onSuccess) {
  77947. try {
  77948. onSuccess(assets);
  77949. }
  77950. catch (e) {
  77951. errorHandler("Error in onSuccess callback", e);
  77952. }
  77953. }
  77954. scene._removePendingData(loadingToken);
  77955. };
  77956. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77957. if (plugin.loadAssetContainer) {
  77958. var syncedPlugin = plugin;
  77959. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  77960. if (!assetContainer) {
  77961. return;
  77962. }
  77963. scene.loadingPluginName = plugin.name;
  77964. successHandler(assetContainer);
  77965. }
  77966. else if (plugin.loadAssetContainerAsync) {
  77967. var asyncedPlugin = plugin;
  77968. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  77969. scene.loadingPluginName = plugin.name;
  77970. successHandler(assetContainer);
  77971. }).catch(function (error) {
  77972. errorHandler(error.message, error);
  77973. });
  77974. }
  77975. else {
  77976. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  77977. }
  77978. if (SceneLoader.ShowLoadingScreen) {
  77979. scene.executeWhenReady(function () {
  77980. scene.getEngine().hideLoadingUI();
  77981. });
  77982. }
  77983. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77984. };
  77985. /**
  77986. * Load a scene into an asset container
  77987. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  77988. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  77989. * @param scene is the instance of BABYLON.Scene to append to
  77990. * @param onProgress a callback with a progress event for each file being loaded
  77991. * @param pluginExtension the extension used to determine the plugin
  77992. * @returns The loaded asset container
  77993. */
  77994. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77995. if (sceneFilename === void 0) { sceneFilename = ""; }
  77996. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77997. if (onProgress === void 0) { onProgress = null; }
  77998. if (pluginExtension === void 0) { pluginExtension = null; }
  77999. return new Promise(function (resolve, reject) {
  78000. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  78001. resolve(assetContainer);
  78002. }, onProgress, function (scene, message, exception) {
  78003. reject(exception || new Error(message));
  78004. }, pluginExtension);
  78005. });
  78006. };
  78007. // Flags
  78008. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  78009. SceneLoader._ShowLoadingScreen = true;
  78010. SceneLoader._CleanBoneMatrixWeights = false;
  78011. /**
  78012. * No logging while loading
  78013. */
  78014. SceneLoader.NO_LOGGING = 0;
  78015. /**
  78016. * Minimal logging while loading
  78017. */
  78018. SceneLoader.MINIMAL_LOGGING = 1;
  78019. /**
  78020. * Summary logging while loading
  78021. */
  78022. SceneLoader.SUMMARY_LOGGING = 2;
  78023. /**
  78024. * Detailled logging while loading
  78025. */
  78026. SceneLoader.DETAILED_LOGGING = 3;
  78027. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  78028. // Members
  78029. /**
  78030. * Event raised when a plugin is used to load a scene
  78031. */
  78032. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  78033. SceneLoader._registeredPlugins = {};
  78034. return SceneLoader;
  78035. }());
  78036. BABYLON.SceneLoader = SceneLoader;
  78037. })(BABYLON || (BABYLON = {}));
  78038. //# sourceMappingURL=babylon.sceneLoader.js.map
  78039. var BABYLON;
  78040. (function (BABYLON) {
  78041. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  78042. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78043. var parsedMaterial = parsedData.materials[index];
  78044. if (parsedMaterial.id === id) {
  78045. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78046. }
  78047. }
  78048. return null;
  78049. };
  78050. var isDescendantOf = function (mesh, names, hierarchyIds) {
  78051. for (var i in names) {
  78052. if (mesh.name === names[i]) {
  78053. hierarchyIds.push(mesh.id);
  78054. return true;
  78055. }
  78056. }
  78057. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  78058. hierarchyIds.push(mesh.id);
  78059. return true;
  78060. }
  78061. return false;
  78062. };
  78063. var logOperation = function (operation, producer) {
  78064. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  78065. };
  78066. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  78067. if (addToScene === void 0) { addToScene = false; }
  78068. var container = new BABYLON.AssetContainer(scene);
  78069. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78070. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78071. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78072. // and avoid problems with multiple concurrent .babylon loads.
  78073. var log = "importScene has failed JSON parse";
  78074. try {
  78075. var parsedData = JSON.parse(data);
  78076. log = "";
  78077. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78078. var index;
  78079. var cache;
  78080. // Lights
  78081. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  78082. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  78083. var parsedLight = parsedData.lights[index];
  78084. var light = BABYLON.Light.Parse(parsedLight, scene);
  78085. if (light) {
  78086. container.lights.push(light);
  78087. log += (index === 0 ? "\n\tLights:" : "");
  78088. log += "\n\t\t" + light.toString(fullDetails);
  78089. }
  78090. }
  78091. }
  78092. // Animations
  78093. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  78094. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  78095. var parsedAnimation = parsedData.animations[index];
  78096. var animation = BABYLON.Animation.Parse(parsedAnimation);
  78097. scene.animations.push(animation);
  78098. container.animations.push(animation);
  78099. log += (index === 0 ? "\n\tAnimations:" : "");
  78100. log += "\n\t\t" + animation.toString(fullDetails);
  78101. }
  78102. }
  78103. // Materials
  78104. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  78105. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78106. var parsedMaterial = parsedData.materials[index];
  78107. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78108. container.materials.push(mat);
  78109. log += (index === 0 ? "\n\tMaterials:" : "");
  78110. log += "\n\t\t" + mat.toString(fullDetails);
  78111. }
  78112. }
  78113. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78114. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  78115. var parsedMultiMaterial = parsedData.multiMaterials[index];
  78116. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78117. container.multiMaterials.push(mmat);
  78118. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  78119. log += "\n\t\t" + mmat.toString(fullDetails);
  78120. }
  78121. }
  78122. // Morph targets
  78123. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78124. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78125. var managerData = _a[_i];
  78126. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  78127. }
  78128. }
  78129. // Skeletons
  78130. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78131. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  78132. var parsedSkeleton = parsedData.skeletons[index];
  78133. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78134. container.skeletons.push(skeleton);
  78135. log += (index === 0 ? "\n\tSkeletons:" : "");
  78136. log += "\n\t\t" + skeleton.toString(fullDetails);
  78137. }
  78138. }
  78139. // Geometries
  78140. var geometries = parsedData.geometries;
  78141. if (geometries !== undefined && geometries !== null) {
  78142. var addedGeometry = new Array();
  78143. // Boxes
  78144. var boxes = geometries.boxes;
  78145. if (boxes !== undefined && boxes !== null) {
  78146. for (index = 0, cache = boxes.length; index < cache; index++) {
  78147. var parsedBox = boxes[index];
  78148. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  78149. }
  78150. }
  78151. // Spheres
  78152. var spheres = geometries.spheres;
  78153. if (spheres !== undefined && spheres !== null) {
  78154. for (index = 0, cache = spheres.length; index < cache; index++) {
  78155. var parsedSphere = spheres[index];
  78156. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  78157. }
  78158. }
  78159. // Cylinders
  78160. var cylinders = geometries.cylinders;
  78161. if (cylinders !== undefined && cylinders !== null) {
  78162. for (index = 0, cache = cylinders.length; index < cache; index++) {
  78163. var parsedCylinder = cylinders[index];
  78164. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  78165. }
  78166. }
  78167. // Toruses
  78168. var toruses = geometries.toruses;
  78169. if (toruses !== undefined && toruses !== null) {
  78170. for (index = 0, cache = toruses.length; index < cache; index++) {
  78171. var parsedTorus = toruses[index];
  78172. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  78173. }
  78174. }
  78175. // Grounds
  78176. var grounds = geometries.grounds;
  78177. if (grounds !== undefined && grounds !== null) {
  78178. for (index = 0, cache = grounds.length; index < cache; index++) {
  78179. var parsedGround = grounds[index];
  78180. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  78181. }
  78182. }
  78183. // Planes
  78184. var planes = geometries.planes;
  78185. if (planes !== undefined && planes !== null) {
  78186. for (index = 0, cache = planes.length; index < cache; index++) {
  78187. var parsedPlane = planes[index];
  78188. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  78189. }
  78190. }
  78191. // TorusKnots
  78192. var torusKnots = geometries.torusKnots;
  78193. if (torusKnots !== undefined && torusKnots !== null) {
  78194. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  78195. var parsedTorusKnot = torusKnots[index];
  78196. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  78197. }
  78198. }
  78199. // VertexData
  78200. var vertexData = geometries.vertexData;
  78201. if (vertexData !== undefined && vertexData !== null) {
  78202. for (index = 0, cache = vertexData.length; index < cache; index++) {
  78203. var parsedVertexData = vertexData[index];
  78204. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  78205. }
  78206. }
  78207. addedGeometry.forEach(function (g) {
  78208. if (g) {
  78209. container.geometries.push(g);
  78210. }
  78211. });
  78212. }
  78213. // Transform nodes
  78214. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  78215. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  78216. var parsedTransformNode = parsedData.transformNodes[index];
  78217. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  78218. container.transformNodes.push(node);
  78219. }
  78220. }
  78221. // Meshes
  78222. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78223. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78224. var parsedMesh = parsedData.meshes[index];
  78225. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78226. container.meshes.push(mesh);
  78227. log += (index === 0 ? "\n\tMeshes:" : "");
  78228. log += "\n\t\t" + mesh.toString(fullDetails);
  78229. }
  78230. }
  78231. // Cameras
  78232. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  78233. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  78234. var parsedCamera = parsedData.cameras[index];
  78235. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  78236. container.cameras.push(camera);
  78237. log += (index === 0 ? "\n\tCameras:" : "");
  78238. log += "\n\t\t" + camera.toString(fullDetails);
  78239. }
  78240. }
  78241. // Animation Groups
  78242. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  78243. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  78244. var parsedAnimationGroup = parsedData.animationGroups[index];
  78245. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  78246. container.animationGroups.push(animationGroup);
  78247. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  78248. log += "\n\t\t" + animationGroup.toString(fullDetails);
  78249. }
  78250. }
  78251. // Browsing all the graph to connect the dots
  78252. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  78253. var camera = scene.cameras[index];
  78254. if (camera._waitingParentId) {
  78255. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  78256. camera._waitingParentId = null;
  78257. }
  78258. }
  78259. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78260. var light_1 = scene.lights[index];
  78261. if (light_1 && light_1._waitingParentId) {
  78262. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  78263. light_1._waitingParentId = null;
  78264. }
  78265. }
  78266. // Connect parents & children and parse actions
  78267. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  78268. var transformNode = scene.transformNodes[index];
  78269. if (transformNode._waitingParentId) {
  78270. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  78271. transformNode._waitingParentId = null;
  78272. }
  78273. }
  78274. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78275. var mesh = scene.meshes[index];
  78276. if (mesh._waitingParentId) {
  78277. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  78278. mesh._waitingParentId = null;
  78279. }
  78280. }
  78281. // freeze world matrix application
  78282. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78283. var currentMesh = scene.meshes[index];
  78284. if (currentMesh._waitingFreezeWorldMatrix) {
  78285. currentMesh.freezeWorldMatrix();
  78286. currentMesh._waitingFreezeWorldMatrix = null;
  78287. }
  78288. else {
  78289. currentMesh.computeWorldMatrix(true);
  78290. }
  78291. }
  78292. // Lights exclusions / inclusions
  78293. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78294. var light_2 = scene.lights[index];
  78295. // Excluded check
  78296. if (light_2._excludedMeshesIds.length > 0) {
  78297. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  78298. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  78299. if (excludedMesh) {
  78300. light_2.excludedMeshes.push(excludedMesh);
  78301. }
  78302. }
  78303. light_2._excludedMeshesIds = [];
  78304. }
  78305. // Included check
  78306. if (light_2._includedOnlyMeshesIds.length > 0) {
  78307. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  78308. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  78309. if (includedOnlyMesh) {
  78310. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  78311. }
  78312. }
  78313. light_2._includedOnlyMeshesIds = [];
  78314. }
  78315. }
  78316. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  78317. // Actions (scene) Done last as it can access other objects.
  78318. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78319. var mesh = scene.meshes[index];
  78320. if (mesh._waitingActions) {
  78321. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  78322. mesh._waitingActions = null;
  78323. }
  78324. }
  78325. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  78326. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  78327. }
  78328. if (!addToScene) {
  78329. container.removeAllFromScene();
  78330. }
  78331. }
  78332. catch (err) {
  78333. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  78334. if (onError) {
  78335. onError(msg, err);
  78336. }
  78337. else {
  78338. BABYLON.Tools.Log(msg);
  78339. throw err;
  78340. }
  78341. }
  78342. finally {
  78343. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78344. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78345. }
  78346. }
  78347. return container;
  78348. };
  78349. BABYLON.SceneLoader.RegisterPlugin({
  78350. name: "babylon.js",
  78351. extensions: ".babylon",
  78352. canDirectLoad: function (data) {
  78353. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  78354. return true;
  78355. }
  78356. return false;
  78357. },
  78358. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  78359. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78360. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78361. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78362. // and avoid problems with multiple concurrent .babylon loads.
  78363. var log = "importMesh has failed JSON parse";
  78364. try {
  78365. var parsedData = JSON.parse(data);
  78366. log = "";
  78367. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78368. if (!meshesNames) {
  78369. meshesNames = null;
  78370. }
  78371. else if (!Array.isArray(meshesNames)) {
  78372. meshesNames = [meshesNames];
  78373. }
  78374. var hierarchyIds = new Array();
  78375. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78376. var loadedSkeletonsIds = [];
  78377. var loadedMaterialsIds = [];
  78378. var index;
  78379. var cache;
  78380. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78381. var parsedMesh = parsedData.meshes[index];
  78382. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  78383. if (meshesNames !== null) {
  78384. // Remove found mesh name from list.
  78385. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  78386. }
  78387. //Geometry?
  78388. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  78389. //does the file contain geometries?
  78390. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  78391. //find the correct geometry and add it to the scene
  78392. var found = false;
  78393. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  78394. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  78395. return;
  78396. }
  78397. else {
  78398. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  78399. if (parsedGeometryData.id === parsedMesh.geometryId) {
  78400. switch (geometryType) {
  78401. case "boxes":
  78402. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  78403. break;
  78404. case "spheres":
  78405. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  78406. break;
  78407. case "cylinders":
  78408. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  78409. break;
  78410. case "toruses":
  78411. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  78412. break;
  78413. case "grounds":
  78414. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  78415. break;
  78416. case "planes":
  78417. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  78418. break;
  78419. case "torusKnots":
  78420. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  78421. break;
  78422. case "vertexData":
  78423. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  78424. break;
  78425. }
  78426. found = true;
  78427. }
  78428. });
  78429. }
  78430. });
  78431. if (found === false) {
  78432. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  78433. }
  78434. }
  78435. }
  78436. // Material ?
  78437. if (parsedMesh.materialId) {
  78438. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  78439. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78440. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  78441. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  78442. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  78443. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  78444. var subMatId = parsedMultiMaterial.materials[matIndex];
  78445. loadedMaterialsIds.push(subMatId);
  78446. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  78447. if (mat) {
  78448. log += "\n\tMaterial " + mat.toString(fullDetails);
  78449. }
  78450. }
  78451. loadedMaterialsIds.push(parsedMultiMaterial.id);
  78452. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78453. if (mmat) {
  78454. materialFound = true;
  78455. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  78456. }
  78457. break;
  78458. }
  78459. }
  78460. }
  78461. if (materialFound === false) {
  78462. loadedMaterialsIds.push(parsedMesh.materialId);
  78463. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  78464. if (!mat) {
  78465. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  78466. }
  78467. else {
  78468. log += "\n\tMaterial " + mat.toString(fullDetails);
  78469. }
  78470. }
  78471. }
  78472. // Skeleton ?
  78473. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78474. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  78475. if (skeletonAlreadyLoaded === false) {
  78476. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  78477. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  78478. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  78479. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78480. skeletons.push(skeleton);
  78481. loadedSkeletonsIds.push(parsedSkeleton.id);
  78482. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  78483. }
  78484. }
  78485. }
  78486. }
  78487. // Morph targets ?
  78488. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78489. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78490. var managerData = _a[_i];
  78491. BABYLON.MorphTargetManager.Parse(managerData, scene);
  78492. }
  78493. }
  78494. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78495. meshes.push(mesh);
  78496. log += "\n\tMesh " + mesh.toString(fullDetails);
  78497. }
  78498. }
  78499. // Connecting parents
  78500. var currentMesh;
  78501. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78502. currentMesh = scene.meshes[index];
  78503. if (currentMesh._waitingParentId) {
  78504. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  78505. currentMesh._waitingParentId = null;
  78506. }
  78507. }
  78508. // freeze and compute world matrix application
  78509. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78510. currentMesh = scene.meshes[index];
  78511. if (currentMesh._waitingFreezeWorldMatrix) {
  78512. currentMesh.freezeWorldMatrix();
  78513. currentMesh._waitingFreezeWorldMatrix = null;
  78514. }
  78515. else {
  78516. currentMesh.computeWorldMatrix(true);
  78517. }
  78518. }
  78519. }
  78520. // Particles
  78521. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  78522. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  78523. if (parser) {
  78524. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  78525. var parsedParticleSystem = parsedData.particleSystems[index];
  78526. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  78527. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  78528. }
  78529. }
  78530. }
  78531. }
  78532. return true;
  78533. }
  78534. catch (err) {
  78535. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  78536. if (onError) {
  78537. onError(msg, err);
  78538. }
  78539. else {
  78540. BABYLON.Tools.Log(msg);
  78541. throw err;
  78542. }
  78543. }
  78544. finally {
  78545. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78546. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78547. }
  78548. }
  78549. return false;
  78550. },
  78551. load: function (scene, data, rootUrl, onError) {
  78552. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78553. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78554. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78555. // and avoid problems with multiple concurrent .babylon loads.
  78556. var log = "importScene has failed JSON parse";
  78557. try {
  78558. var parsedData = JSON.parse(data);
  78559. log = "";
  78560. // Scene
  78561. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  78562. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  78563. }
  78564. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  78565. scene.autoClear = parsedData.autoClear;
  78566. }
  78567. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  78568. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  78569. }
  78570. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  78571. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  78572. }
  78573. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  78574. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  78575. }
  78576. // Fog
  78577. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  78578. scene.fogMode = parsedData.fogMode;
  78579. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  78580. scene.fogStart = parsedData.fogStart;
  78581. scene.fogEnd = parsedData.fogEnd;
  78582. scene.fogDensity = parsedData.fogDensity;
  78583. log += "\tFog mode for scene: ";
  78584. switch (scene.fogMode) {
  78585. // getters not compiling, so using hardcoded
  78586. case 1:
  78587. log += "exp\n";
  78588. break;
  78589. case 2:
  78590. log += "exp2\n";
  78591. break;
  78592. case 3:
  78593. log += "linear\n";
  78594. break;
  78595. }
  78596. }
  78597. //Physics
  78598. if (parsedData.physicsEnabled) {
  78599. var physicsPlugin;
  78600. if (parsedData.physicsEngine === "cannon") {
  78601. physicsPlugin = new BABYLON.CannonJSPlugin();
  78602. }
  78603. else if (parsedData.physicsEngine === "oimo") {
  78604. physicsPlugin = new BABYLON.OimoJSPlugin();
  78605. }
  78606. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  78607. //else - default engine, which is currently oimo
  78608. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  78609. scene.enablePhysics(physicsGravity, physicsPlugin);
  78610. }
  78611. // Metadata
  78612. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  78613. scene.metadata = parsedData.metadata;
  78614. }
  78615. //collisions, if defined. otherwise, default is true
  78616. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  78617. scene.collisionsEnabled = parsedData.collisionsEnabled;
  78618. }
  78619. scene.workerCollisions = !!parsedData.workerCollisions;
  78620. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  78621. if (!container) {
  78622. return false;
  78623. }
  78624. if (parsedData.autoAnimate) {
  78625. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  78626. }
  78627. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  78628. scene.setActiveCameraByID(parsedData.activeCameraID);
  78629. }
  78630. // Environment texture
  78631. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  78632. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  78633. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  78634. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  78635. if (parsedData.environmentTextureRotationY) {
  78636. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  78637. }
  78638. scene.environmentTexture = hdrTexture;
  78639. }
  78640. else {
  78641. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  78642. if (parsedData.environmentTextureRotationY) {
  78643. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  78644. }
  78645. scene.environmentTexture = cubeTexture;
  78646. }
  78647. if (parsedData.createDefaultSkybox === true) {
  78648. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  78649. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  78650. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  78651. }
  78652. }
  78653. // Finish
  78654. return true;
  78655. }
  78656. catch (err) {
  78657. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  78658. if (onError) {
  78659. onError(msg, err);
  78660. }
  78661. else {
  78662. BABYLON.Tools.Log(msg);
  78663. throw err;
  78664. }
  78665. }
  78666. finally {
  78667. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78668. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78669. }
  78670. }
  78671. return false;
  78672. },
  78673. loadAssetContainer: function (scene, data, rootUrl, onError) {
  78674. var container = loadAssetContainer(scene, data, rootUrl, onError);
  78675. return container;
  78676. }
  78677. });
  78678. })(BABYLON || (BABYLON = {}));
  78679. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  78680. var BABYLON;
  78681. (function (BABYLON) {
  78682. /**
  78683. * Class used to help managing file picking and drag'n'drop
  78684. */
  78685. var FilesInput = /** @class */ (function () {
  78686. /**
  78687. * Creates a new FilesInput
  78688. * @param engine defines the rendering engine
  78689. * @param scene defines the hosting scene
  78690. * @param sceneLoadedCallback callback called when scene is loaded
  78691. * @param progressCallback callback called to track progress
  78692. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  78693. * @param textureLoadingCallback callback called when a texture is loading
  78694. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  78695. * @param onReloadCallback callback called when a reload is requested
  78696. * @param errorCallback callback call if an error occurs
  78697. */
  78698. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  78699. /**
  78700. * Callback called when a file is processed
  78701. */
  78702. this.onProcessFileCallback = function () { return true; };
  78703. this._engine = engine;
  78704. this._currentScene = scene;
  78705. this._sceneLoadedCallback = sceneLoadedCallback;
  78706. this._progressCallback = progressCallback;
  78707. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  78708. this._textureLoadingCallback = textureLoadingCallback;
  78709. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  78710. this._onReloadCallback = onReloadCallback;
  78711. this._errorCallback = errorCallback;
  78712. }
  78713. /**
  78714. * Calls this function to listen to drag'n'drop events on a specific DOM element
  78715. * @param elementToMonitor defines the DOM element to track
  78716. */
  78717. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  78718. var _this = this;
  78719. if (elementToMonitor) {
  78720. this._elementToMonitor = elementToMonitor;
  78721. this._dragEnterHandler = function (e) { _this.drag(e); };
  78722. this._dragOverHandler = function (e) { _this.drag(e); };
  78723. this._dropHandler = function (e) { _this.drop(e); };
  78724. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  78725. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  78726. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  78727. }
  78728. };
  78729. /**
  78730. * Release all associated resources
  78731. */
  78732. FilesInput.prototype.dispose = function () {
  78733. if (!this._elementToMonitor) {
  78734. return;
  78735. }
  78736. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  78737. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  78738. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  78739. };
  78740. FilesInput.prototype.renderFunction = function () {
  78741. if (this._additionalRenderLoopLogicCallback) {
  78742. this._additionalRenderLoopLogicCallback();
  78743. }
  78744. if (this._currentScene) {
  78745. if (this._textureLoadingCallback) {
  78746. var remaining = this._currentScene.getWaitingItemsCount();
  78747. if (remaining > 0) {
  78748. this._textureLoadingCallback(remaining);
  78749. }
  78750. }
  78751. this._currentScene.render();
  78752. }
  78753. };
  78754. FilesInput.prototype.drag = function (e) {
  78755. e.stopPropagation();
  78756. e.preventDefault();
  78757. };
  78758. FilesInput.prototype.drop = function (eventDrop) {
  78759. eventDrop.stopPropagation();
  78760. eventDrop.preventDefault();
  78761. this.loadFiles(eventDrop);
  78762. };
  78763. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  78764. var _this = this;
  78765. var reader = folder.createReader();
  78766. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  78767. reader.readEntries(function (entries) {
  78768. remaining.count += entries.length;
  78769. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  78770. var entry = entries_1[_i];
  78771. if (entry.isFile) {
  78772. entry.file(function (file) {
  78773. file.correctName = relativePath + file.name;
  78774. files.push(file);
  78775. if (--remaining.count === 0) {
  78776. callback();
  78777. }
  78778. });
  78779. }
  78780. else if (entry.isDirectory) {
  78781. _this._traverseFolder(entry, files, remaining, callback);
  78782. }
  78783. }
  78784. if (--remaining.count) {
  78785. callback();
  78786. }
  78787. });
  78788. };
  78789. FilesInput.prototype._processFiles = function (files) {
  78790. for (var i = 0; i < files.length; i++) {
  78791. var name = files[i].correctName.toLowerCase();
  78792. var extension = name.split('.').pop();
  78793. if (!this.onProcessFileCallback(files[i], name, extension)) {
  78794. continue;
  78795. }
  78796. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  78797. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  78798. this._sceneFileToLoad = files[i];
  78799. }
  78800. FilesInput.FilesToLoad[name] = files[i];
  78801. }
  78802. };
  78803. /**
  78804. * Load files from a drop event
  78805. * @param event defines the drop event to use as source
  78806. */
  78807. FilesInput.prototype.loadFiles = function (event) {
  78808. var _this = this;
  78809. // Handling data transfer via drag'n'drop
  78810. if (event && event.dataTransfer && event.dataTransfer.files) {
  78811. this._filesToLoad = event.dataTransfer.files;
  78812. }
  78813. // Handling files from input files
  78814. if (event && event.target && event.target.files) {
  78815. this._filesToLoad = event.target.files;
  78816. }
  78817. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  78818. return;
  78819. }
  78820. if (this._startingProcessingFilesCallback) {
  78821. this._startingProcessingFilesCallback(this._filesToLoad);
  78822. }
  78823. if (this._filesToLoad && this._filesToLoad.length > 0) {
  78824. var files_1 = new Array();
  78825. var folders = [];
  78826. var items = event.dataTransfer ? event.dataTransfer.items : null;
  78827. for (var i = 0; i < this._filesToLoad.length; i++) {
  78828. var fileToLoad = this._filesToLoad[i];
  78829. var name_1 = fileToLoad.name.toLowerCase();
  78830. var entry = void 0;
  78831. fileToLoad.correctName = name_1;
  78832. if (items) {
  78833. var item = items[i];
  78834. if (item.getAsEntry) {
  78835. entry = item.getAsEntry();
  78836. }
  78837. else if (item.webkitGetAsEntry) {
  78838. entry = item.webkitGetAsEntry();
  78839. }
  78840. }
  78841. if (!entry) {
  78842. files_1.push(fileToLoad);
  78843. }
  78844. else {
  78845. if (entry.isDirectory) {
  78846. folders.push(entry);
  78847. }
  78848. else {
  78849. files_1.push(fileToLoad);
  78850. }
  78851. }
  78852. }
  78853. if (folders.length === 0) {
  78854. this._processFiles(files_1);
  78855. this._processReload();
  78856. }
  78857. else {
  78858. var remaining = { count: folders.length };
  78859. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  78860. var folder = folders_1[_i];
  78861. this._traverseFolder(folder, files_1, remaining, function () {
  78862. _this._processFiles(files_1);
  78863. if (remaining.count === 0) {
  78864. _this._processReload();
  78865. }
  78866. });
  78867. }
  78868. }
  78869. }
  78870. };
  78871. FilesInput.prototype._processReload = function () {
  78872. if (this._onReloadCallback) {
  78873. this._onReloadCallback(this._sceneFileToLoad);
  78874. }
  78875. else {
  78876. this.reload();
  78877. }
  78878. };
  78879. /**
  78880. * Reload the current scene from the loaded files
  78881. */
  78882. FilesInput.prototype.reload = function () {
  78883. var _this = this;
  78884. // If a scene file has been provided
  78885. if (this._sceneFileToLoad) {
  78886. if (this._currentScene) {
  78887. if (BABYLON.Tools.errorsCount > 0) {
  78888. BABYLON.Tools.ClearLogCache();
  78889. }
  78890. this._engine.stopRenderLoop();
  78891. }
  78892. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  78893. if (_this._progressCallback) {
  78894. _this._progressCallback(progress);
  78895. }
  78896. }).then(function (scene) {
  78897. if (_this._currentScene) {
  78898. _this._currentScene.dispose();
  78899. }
  78900. _this._currentScene = scene;
  78901. if (_this._sceneLoadedCallback) {
  78902. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  78903. }
  78904. // Wait for textures and shaders to be ready
  78905. _this._currentScene.executeWhenReady(function () {
  78906. _this._engine.runRenderLoop(function () {
  78907. _this.renderFunction();
  78908. });
  78909. });
  78910. }).catch(function (error) {
  78911. if (_this._errorCallback) {
  78912. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  78913. }
  78914. });
  78915. }
  78916. else {
  78917. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  78918. }
  78919. };
  78920. /**
  78921. * List of files ready to be loaded
  78922. */
  78923. FilesInput.FilesToLoad = {};
  78924. return FilesInput;
  78925. }());
  78926. BABYLON.FilesInput = FilesInput;
  78927. })(BABYLON || (BABYLON = {}));
  78928. //# sourceMappingURL=babylon.filesInput.js.map
  78929. var BABYLON;
  78930. (function (BABYLON) {
  78931. /**
  78932. * Class used to store custom tags
  78933. */
  78934. var Tags = /** @class */ (function () {
  78935. function Tags() {
  78936. }
  78937. /**
  78938. * Adds support for tags on the given object
  78939. * @param obj defines the object to use
  78940. */
  78941. Tags.EnableFor = function (obj) {
  78942. obj._tags = obj._tags || {};
  78943. obj.hasTags = function () {
  78944. return Tags.HasTags(obj);
  78945. };
  78946. obj.addTags = function (tagsString) {
  78947. return Tags.AddTagsTo(obj, tagsString);
  78948. };
  78949. obj.removeTags = function (tagsString) {
  78950. return Tags.RemoveTagsFrom(obj, tagsString);
  78951. };
  78952. obj.matchesTagsQuery = function (tagsQuery) {
  78953. return Tags.MatchesQuery(obj, tagsQuery);
  78954. };
  78955. };
  78956. /**
  78957. * Removes tags support
  78958. * @param obj defines the object to use
  78959. */
  78960. Tags.DisableFor = function (obj) {
  78961. delete obj._tags;
  78962. delete obj.hasTags;
  78963. delete obj.addTags;
  78964. delete obj.removeTags;
  78965. delete obj.matchesTagsQuery;
  78966. };
  78967. /**
  78968. * Gets a boolean indicating if the given object has tags
  78969. * @param obj defines the object to use
  78970. * @returns a boolean
  78971. */
  78972. Tags.HasTags = function (obj) {
  78973. if (!obj._tags) {
  78974. return false;
  78975. }
  78976. return !BABYLON.Tools.IsEmpty(obj._tags);
  78977. };
  78978. /**
  78979. * Gets the tags available on a given object
  78980. * @param obj defines the object to use
  78981. * @param asString defines if the tags must be returned as a string instead of an array of strings
  78982. * @returns the tags
  78983. */
  78984. Tags.GetTags = function (obj, asString) {
  78985. if (asString === void 0) { asString = true; }
  78986. if (!obj._tags) {
  78987. return null;
  78988. }
  78989. if (asString) {
  78990. var tagsArray = [];
  78991. for (var tag in obj._tags) {
  78992. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  78993. tagsArray.push(tag);
  78994. }
  78995. }
  78996. return tagsArray.join(" ");
  78997. }
  78998. else {
  78999. return obj._tags;
  79000. }
  79001. };
  79002. /**
  79003. * Adds tags to an object
  79004. * @param obj defines the object to use
  79005. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  79006. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  79007. */
  79008. Tags.AddTagsTo = function (obj, tagsString) {
  79009. if (!tagsString) {
  79010. return;
  79011. }
  79012. if (typeof tagsString !== "string") {
  79013. return;
  79014. }
  79015. var tags = tagsString.split(" ");
  79016. tags.forEach(function (tag, index, array) {
  79017. Tags._AddTagTo(obj, tag);
  79018. });
  79019. };
  79020. /**
  79021. * @hidden
  79022. */
  79023. Tags._AddTagTo = function (obj, tag) {
  79024. tag = tag.trim();
  79025. if (tag === "" || tag === "true" || tag === "false") {
  79026. return;
  79027. }
  79028. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  79029. return;
  79030. }
  79031. Tags.EnableFor(obj);
  79032. obj._tags[tag] = true;
  79033. };
  79034. /**
  79035. * Removes specific tags from a specific object
  79036. * @param obj defines the object to use
  79037. * @param tagsString defines the tags to remove
  79038. */
  79039. Tags.RemoveTagsFrom = function (obj, tagsString) {
  79040. if (!Tags.HasTags(obj)) {
  79041. return;
  79042. }
  79043. var tags = tagsString.split(" ");
  79044. for (var t in tags) {
  79045. Tags._RemoveTagFrom(obj, tags[t]);
  79046. }
  79047. };
  79048. /**
  79049. * @hidden
  79050. */
  79051. Tags._RemoveTagFrom = function (obj, tag) {
  79052. delete obj._tags[tag];
  79053. };
  79054. /**
  79055. * Defines if tags hosted on an object match a given query
  79056. * @param obj defines the object to use
  79057. * @param tagsQuery defines the tag query
  79058. * @returns a boolean
  79059. */
  79060. Tags.MatchesQuery = function (obj, tagsQuery) {
  79061. if (tagsQuery === undefined) {
  79062. return true;
  79063. }
  79064. if (tagsQuery === "") {
  79065. return Tags.HasTags(obj);
  79066. }
  79067. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  79068. };
  79069. return Tags;
  79070. }());
  79071. BABYLON.Tags = Tags;
  79072. })(BABYLON || (BABYLON = {}));
  79073. //# sourceMappingURL=babylon.tags.js.map
  79074. var BABYLON;
  79075. (function (BABYLON) {
  79076. /**
  79077. * Class used to evalaute queries containing `and` and `or` operators
  79078. */
  79079. var AndOrNotEvaluator = /** @class */ (function () {
  79080. function AndOrNotEvaluator() {
  79081. }
  79082. /**
  79083. * Evaluate a query
  79084. * @param query defines the query to evaluate
  79085. * @param evaluateCallback defines the callback used to filter result
  79086. * @returns true if the query matches
  79087. */
  79088. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  79089. if (!query.match(/\([^\(\)]*\)/g)) {
  79090. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  79091. }
  79092. else {
  79093. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  79094. // remove parenthesis
  79095. r = r.slice(1, r.length - 1);
  79096. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  79097. });
  79098. }
  79099. if (query === "true") {
  79100. return true;
  79101. }
  79102. if (query === "false") {
  79103. return false;
  79104. }
  79105. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  79106. };
  79107. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  79108. evaluateCallback = evaluateCallback || (function (r) {
  79109. return r === "true" ? true : false;
  79110. });
  79111. var result;
  79112. var or = parenthesisContent.split("||");
  79113. for (var i in or) {
  79114. if (or.hasOwnProperty(i)) {
  79115. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  79116. var and = ori.split("&&");
  79117. if (and.length > 1) {
  79118. for (var j = 0; j < and.length; ++j) {
  79119. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  79120. if (andj !== "true" && andj !== "false") {
  79121. if (andj[0] === "!") {
  79122. result = !evaluateCallback(andj.substring(1));
  79123. }
  79124. else {
  79125. result = evaluateCallback(andj);
  79126. }
  79127. }
  79128. else {
  79129. result = andj === "true" ? true : false;
  79130. }
  79131. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  79132. ori = "false";
  79133. break;
  79134. }
  79135. }
  79136. }
  79137. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  79138. result = true;
  79139. break;
  79140. }
  79141. // result equals false (or undefined)
  79142. if (ori !== "true" && ori !== "false") {
  79143. if (ori[0] === "!") {
  79144. result = !evaluateCallback(ori.substring(1));
  79145. }
  79146. else {
  79147. result = evaluateCallback(ori);
  79148. }
  79149. }
  79150. else {
  79151. result = ori === "true" ? true : false;
  79152. }
  79153. }
  79154. }
  79155. // the whole parenthesis scope is replaced by 'true' or 'false'
  79156. return result ? "true" : "false";
  79157. };
  79158. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  79159. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  79160. // remove whitespaces
  79161. r = r.replace(/[\s]/g, function () { return ""; });
  79162. return r.length % 2 ? "!" : "";
  79163. });
  79164. booleanString = booleanString.trim();
  79165. if (booleanString === "!true") {
  79166. booleanString = "false";
  79167. }
  79168. else if (booleanString === "!false") {
  79169. booleanString = "true";
  79170. }
  79171. return booleanString;
  79172. };
  79173. return AndOrNotEvaluator;
  79174. }());
  79175. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  79176. })(BABYLON || (BABYLON = {}));
  79177. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  79178. var BABYLON;
  79179. (function (BABYLON) {
  79180. // Sets the default offline provider to Babylon.js
  79181. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  79182. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79183. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  79184. };
  79185. /**
  79186. * Class used to enable access to IndexedDB
  79187. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  79188. */
  79189. var Database = /** @class */ (function () {
  79190. /**
  79191. * Creates a new Database
  79192. * @param urlToScene defines the url to load the scene
  79193. * @param callbackManifestChecked defines the callback to use when manifest is checked
  79194. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  79195. */
  79196. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  79197. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79198. var _this = this;
  79199. // Handling various flavors of prefixed version of IndexedDB
  79200. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  79201. this._callbackManifestChecked = callbackManifestChecked;
  79202. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  79203. this._db = null;
  79204. this._enableSceneOffline = false;
  79205. this._enableTexturesOffline = false;
  79206. this._manifestVersionFound = 0;
  79207. this._mustUpdateRessources = false;
  79208. this._hasReachedQuota = false;
  79209. if (!Database.IDBStorageEnabled) {
  79210. this._callbackManifestChecked(true);
  79211. }
  79212. else {
  79213. if (disableManifestCheck) {
  79214. this._enableSceneOffline = true;
  79215. this._enableTexturesOffline = true;
  79216. this._manifestVersionFound = 1;
  79217. BABYLON.Tools.SetImmediate(function () {
  79218. _this._callbackManifestChecked(true);
  79219. });
  79220. }
  79221. else {
  79222. this._checkManifestFile();
  79223. }
  79224. }
  79225. }
  79226. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  79227. /**
  79228. * Gets a boolean indicating if scene must be saved in the database
  79229. */
  79230. get: function () {
  79231. return this._enableSceneOffline;
  79232. },
  79233. enumerable: true,
  79234. configurable: true
  79235. });
  79236. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  79237. /**
  79238. * Gets a boolean indicating if textures must be saved in the database
  79239. */
  79240. get: function () {
  79241. return this._enableTexturesOffline;
  79242. },
  79243. enumerable: true,
  79244. configurable: true
  79245. });
  79246. Database.prototype._checkManifestFile = function () {
  79247. var _this = this;
  79248. var noManifestFile = function () {
  79249. _this._enableSceneOffline = false;
  79250. _this._enableTexturesOffline = false;
  79251. _this._callbackManifestChecked(false);
  79252. };
  79253. var timeStampUsed = false;
  79254. var manifestURL = this._currentSceneUrl + ".manifest";
  79255. var xhr = new XMLHttpRequest();
  79256. if (navigator.onLine) {
  79257. // Adding a timestamp to by-pass browsers' cache
  79258. timeStampUsed = true;
  79259. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  79260. }
  79261. xhr.open("GET", manifestURL, true);
  79262. xhr.addEventListener("load", function () {
  79263. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79264. try {
  79265. var manifestFile = JSON.parse(xhr.response);
  79266. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  79267. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  79268. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  79269. _this._manifestVersionFound = manifestFile.version;
  79270. }
  79271. if (_this._callbackManifestChecked) {
  79272. _this._callbackManifestChecked(true);
  79273. }
  79274. }
  79275. catch (ex) {
  79276. noManifestFile();
  79277. }
  79278. }
  79279. else {
  79280. noManifestFile();
  79281. }
  79282. }, false);
  79283. xhr.addEventListener("error", function (event) {
  79284. if (timeStampUsed) {
  79285. timeStampUsed = false;
  79286. // Let's retry without the timeStamp
  79287. // It could fail when coupled with HTML5 Offline API
  79288. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  79289. xhr.open("GET", retryManifestURL, true);
  79290. xhr.send();
  79291. }
  79292. else {
  79293. noManifestFile();
  79294. }
  79295. }, false);
  79296. try {
  79297. xhr.send();
  79298. }
  79299. catch (ex) {
  79300. BABYLON.Tools.Error("Error on XHR send request.");
  79301. this._callbackManifestChecked(false);
  79302. }
  79303. };
  79304. /**
  79305. * Open the database and make it available
  79306. * @param successCallback defines the callback to call on success
  79307. * @param errorCallback defines the callback to call on error
  79308. */
  79309. Database.prototype.open = function (successCallback, errorCallback) {
  79310. var _this = this;
  79311. var handleError = function () {
  79312. _this._isSupported = false;
  79313. if (errorCallback) {
  79314. errorCallback();
  79315. }
  79316. };
  79317. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  79318. // Your browser doesn't support IndexedDB
  79319. this._isSupported = false;
  79320. if (errorCallback) {
  79321. errorCallback();
  79322. }
  79323. }
  79324. else {
  79325. // If the DB hasn't been opened or created yet
  79326. if (!this._db) {
  79327. this._hasReachedQuota = false;
  79328. this._isSupported = true;
  79329. var request = this._idbFactory.open("babylonjs", 1);
  79330. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  79331. request.onerror = function (event) {
  79332. handleError();
  79333. };
  79334. // executes when a version change transaction cannot complete due to other active transactions
  79335. request.onblocked = function (event) {
  79336. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  79337. handleError();
  79338. };
  79339. // DB has been opened successfully
  79340. request.onsuccess = function (event) {
  79341. _this._db = request.result;
  79342. successCallback();
  79343. };
  79344. // Initialization of the DB. Creating Scenes & Textures stores
  79345. request.onupgradeneeded = function (event) {
  79346. _this._db = (event.target).result;
  79347. if (_this._db) {
  79348. try {
  79349. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  79350. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  79351. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  79352. }
  79353. catch (ex) {
  79354. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  79355. handleError();
  79356. }
  79357. }
  79358. };
  79359. }
  79360. // DB has already been created and opened
  79361. else {
  79362. if (successCallback) {
  79363. successCallback();
  79364. }
  79365. }
  79366. }
  79367. };
  79368. /**
  79369. * Loads an image from the database
  79370. * @param url defines the url to load from
  79371. * @param image defines the target DOM image
  79372. */
  79373. Database.prototype.loadImage = function (url, image) {
  79374. var _this = this;
  79375. var completeURL = Database._ReturnFullUrlLocation(url);
  79376. var saveAndLoadImage = function () {
  79377. if (!_this._hasReachedQuota && _this._db !== null) {
  79378. // the texture is not yet in the DB, let's try to save it
  79379. _this._saveImageIntoDBAsync(completeURL, image);
  79380. }
  79381. // If the texture is not in the DB and we've reached the DB quota limit
  79382. // let's load it directly from the web
  79383. else {
  79384. image.src = url;
  79385. }
  79386. };
  79387. if (!this._mustUpdateRessources) {
  79388. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  79389. }
  79390. // First time we're download the images or update requested in the manifest file by a version change
  79391. else {
  79392. saveAndLoadImage();
  79393. }
  79394. };
  79395. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  79396. if (this._isSupported && this._db !== null) {
  79397. var texture;
  79398. var transaction = this._db.transaction(["textures"]);
  79399. transaction.onabort = function (event) {
  79400. image.src = url;
  79401. };
  79402. transaction.oncomplete = function (event) {
  79403. var blobTextureURL;
  79404. if (texture) {
  79405. var URL = window.URL || window.webkitURL;
  79406. blobTextureURL = URL.createObjectURL(texture.data);
  79407. image.onerror = function () {
  79408. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  79409. image.src = url;
  79410. };
  79411. image.src = blobTextureURL;
  79412. }
  79413. else {
  79414. notInDBCallback();
  79415. }
  79416. };
  79417. var getRequest = transaction.objectStore("textures").get(url);
  79418. getRequest.onsuccess = function (event) {
  79419. texture = (event.target).result;
  79420. };
  79421. getRequest.onerror = function (event) {
  79422. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  79423. image.src = url;
  79424. };
  79425. }
  79426. else {
  79427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79428. image.src = url;
  79429. }
  79430. };
  79431. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  79432. var _this = this;
  79433. if (this._isSupported) {
  79434. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  79435. var generateBlobUrl = function () {
  79436. var blobTextureURL;
  79437. if (blob) {
  79438. var URL = window.URL || window.webkitURL;
  79439. try {
  79440. blobTextureURL = URL.createObjectURL(blob);
  79441. }
  79442. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  79443. catch (ex) {
  79444. blobTextureURL = URL.createObjectURL(blob);
  79445. }
  79446. }
  79447. if (blobTextureURL) {
  79448. image.src = blobTextureURL;
  79449. }
  79450. };
  79451. if (Database.IsUASupportingBlobStorage) { // Create XHR
  79452. var xhr = new XMLHttpRequest(), blob;
  79453. xhr.open("GET", url, true);
  79454. xhr.responseType = "blob";
  79455. xhr.addEventListener("load", function () {
  79456. if (xhr.status === 200 && _this._db) {
  79457. // Blob as response (XHR2)
  79458. blob = xhr.response;
  79459. var transaction = _this._db.transaction(["textures"], "readwrite");
  79460. // the transaction could abort because of a QuotaExceededError error
  79461. transaction.onabort = function (event) {
  79462. try {
  79463. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79464. var srcElement = (event.srcElement || event.target);
  79465. var error = srcElement.error;
  79466. if (error && error.name === "QuotaExceededError") {
  79467. _this._hasReachedQuota = true;
  79468. }
  79469. }
  79470. catch (ex) { }
  79471. generateBlobUrl();
  79472. };
  79473. transaction.oncomplete = function (event) {
  79474. generateBlobUrl();
  79475. };
  79476. var newTexture = { textureUrl: url, data: blob };
  79477. try {
  79478. // Put the blob into the dabase
  79479. var addRequest = transaction.objectStore("textures").put(newTexture);
  79480. addRequest.onsuccess = function (event) {
  79481. };
  79482. addRequest.onerror = function (event) {
  79483. generateBlobUrl();
  79484. };
  79485. }
  79486. catch (ex) {
  79487. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  79488. if (ex.code === 25) {
  79489. Database.IsUASupportingBlobStorage = false;
  79490. _this._enableTexturesOffline = false;
  79491. }
  79492. image.src = url;
  79493. }
  79494. }
  79495. else {
  79496. image.src = url;
  79497. }
  79498. }, false);
  79499. xhr.addEventListener("error", function (event) {
  79500. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  79501. image.src = url;
  79502. }, false);
  79503. xhr.send();
  79504. }
  79505. else {
  79506. image.src = url;
  79507. }
  79508. }
  79509. else {
  79510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79511. image.src = url;
  79512. }
  79513. };
  79514. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  79515. var _this = this;
  79516. var updateVersion = function () {
  79517. // the version is not yet in the DB or we need to update it
  79518. _this._saveVersionIntoDBAsync(url, versionLoaded);
  79519. };
  79520. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  79521. };
  79522. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  79523. var _this = this;
  79524. if (this._isSupported && this._db) {
  79525. var version;
  79526. try {
  79527. var transaction = this._db.transaction(["versions"]);
  79528. transaction.oncomplete = function (event) {
  79529. if (version) {
  79530. // If the version in the JSON file is different from the version in DB
  79531. if (_this._manifestVersionFound !== version.data) {
  79532. _this._mustUpdateRessources = true;
  79533. updateInDBCallback();
  79534. }
  79535. else {
  79536. callback(version.data);
  79537. }
  79538. }
  79539. // version was not found in DB
  79540. else {
  79541. _this._mustUpdateRessources = true;
  79542. updateInDBCallback();
  79543. }
  79544. };
  79545. transaction.onabort = function (event) {
  79546. callback(-1);
  79547. };
  79548. var getRequest = transaction.objectStore("versions").get(url);
  79549. getRequest.onsuccess = function (event) {
  79550. version = (event.target).result;
  79551. };
  79552. getRequest.onerror = function (event) {
  79553. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  79554. callback(-1);
  79555. };
  79556. }
  79557. catch (ex) {
  79558. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  79559. callback(-1);
  79560. }
  79561. }
  79562. else {
  79563. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79564. callback(-1);
  79565. }
  79566. };
  79567. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  79568. var _this = this;
  79569. if (this._isSupported && !this._hasReachedQuota && this._db) {
  79570. try {
  79571. // Open a transaction to the database
  79572. var transaction = this._db.transaction(["versions"], "readwrite");
  79573. // the transaction could abort because of a QuotaExceededError error
  79574. transaction.onabort = function (event) {
  79575. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79576. var error = event.srcElement['error'];
  79577. if (error && error.name === "QuotaExceededError") {
  79578. _this._hasReachedQuota = true;
  79579. }
  79580. }
  79581. catch (ex) { }
  79582. callback(-1);
  79583. };
  79584. transaction.oncomplete = function (event) {
  79585. callback(_this._manifestVersionFound);
  79586. };
  79587. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  79588. // Put the scene into the database
  79589. var addRequest = transaction.objectStore("versions").put(newVersion);
  79590. addRequest.onsuccess = function (event) {
  79591. };
  79592. addRequest.onerror = function (event) {
  79593. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  79594. };
  79595. }
  79596. catch (ex) {
  79597. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  79598. callback(-1);
  79599. }
  79600. }
  79601. else {
  79602. callback(-1);
  79603. }
  79604. };
  79605. /**
  79606. * Loads a file from database
  79607. * @param url defines the URL to load from
  79608. * @param sceneLoaded defines a callback to call on success
  79609. * @param progressCallBack defines a callback to call when progress changed
  79610. * @param errorCallback defines a callback to call on error
  79611. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  79612. */
  79613. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  79614. var _this = this;
  79615. var completeUrl = Database._ReturnFullUrlLocation(url);
  79616. var saveAndLoadFile = function () {
  79617. // the scene is not yet in the DB, let's try to save it
  79618. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79619. };
  79620. this._checkVersionFromDB(completeUrl, function (version) {
  79621. if (version !== -1) {
  79622. if (!_this._mustUpdateRessources) {
  79623. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  79624. }
  79625. else {
  79626. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79627. }
  79628. }
  79629. else {
  79630. if (errorCallback) {
  79631. errorCallback();
  79632. }
  79633. }
  79634. });
  79635. };
  79636. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  79637. if (this._isSupported && this._db) {
  79638. var targetStore;
  79639. if (url.indexOf(".babylon") !== -1) {
  79640. targetStore = "scenes";
  79641. }
  79642. else {
  79643. targetStore = "textures";
  79644. }
  79645. var file;
  79646. var transaction = this._db.transaction([targetStore]);
  79647. transaction.oncomplete = function (event) {
  79648. if (file) {
  79649. callback(file.data);
  79650. }
  79651. // file was not found in DB
  79652. else {
  79653. notInDBCallback();
  79654. }
  79655. };
  79656. transaction.onabort = function (event) {
  79657. notInDBCallback();
  79658. };
  79659. var getRequest = transaction.objectStore(targetStore).get(url);
  79660. getRequest.onsuccess = function (event) {
  79661. file = (event.target).result;
  79662. };
  79663. getRequest.onerror = function (event) {
  79664. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  79665. notInDBCallback();
  79666. };
  79667. }
  79668. else {
  79669. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79670. callback();
  79671. }
  79672. };
  79673. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  79674. var _this = this;
  79675. if (this._isSupported) {
  79676. var targetStore;
  79677. if (url.indexOf(".babylon") !== -1) {
  79678. targetStore = "scenes";
  79679. }
  79680. else {
  79681. targetStore = "textures";
  79682. }
  79683. // Create XHR
  79684. var xhr = new XMLHttpRequest();
  79685. var fileData;
  79686. xhr.open("GET", url + "?" + Date.now(), true);
  79687. if (useArrayBuffer) {
  79688. xhr.responseType = "arraybuffer";
  79689. }
  79690. if (progressCallback) {
  79691. xhr.onprogress = progressCallback;
  79692. }
  79693. xhr.addEventListener("load", function () {
  79694. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  79695. // Blob as response (XHR2)
  79696. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  79697. if (!_this._hasReachedQuota && _this._db) {
  79698. // Open a transaction to the database
  79699. var transaction = _this._db.transaction([targetStore], "readwrite");
  79700. // the transaction could abort because of a QuotaExceededError error
  79701. transaction.onabort = function (event) {
  79702. try {
  79703. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79704. var error = event.srcElement['error'];
  79705. if (error && error.name === "QuotaExceededError") {
  79706. _this._hasReachedQuota = true;
  79707. }
  79708. }
  79709. catch (ex) { }
  79710. callback(fileData);
  79711. };
  79712. transaction.oncomplete = function (event) {
  79713. callback(fileData);
  79714. };
  79715. var newFile;
  79716. if (targetStore === "scenes") {
  79717. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  79718. }
  79719. else {
  79720. newFile = { textureUrl: url, data: fileData };
  79721. }
  79722. try {
  79723. // Put the scene into the database
  79724. var addRequest = transaction.objectStore(targetStore).put(newFile);
  79725. addRequest.onsuccess = function (event) {
  79726. };
  79727. addRequest.onerror = function (event) {
  79728. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  79729. };
  79730. }
  79731. catch (ex) {
  79732. callback(fileData);
  79733. }
  79734. }
  79735. else {
  79736. callback(fileData);
  79737. }
  79738. }
  79739. else {
  79740. if (xhr.status >= 400 && errorCallback) {
  79741. errorCallback(xhr);
  79742. }
  79743. else {
  79744. callback();
  79745. }
  79746. }
  79747. }, false);
  79748. xhr.addEventListener("error", function (event) {
  79749. BABYLON.Tools.Error("error on XHR request.");
  79750. callback();
  79751. }, false);
  79752. xhr.send();
  79753. }
  79754. else {
  79755. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  79756. callback();
  79757. }
  79758. };
  79759. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  79760. Database.IsUASupportingBlobStorage = true;
  79761. /**
  79762. * Gets a boolean indicating if Database storate is enabled (off by default)
  79763. */
  79764. Database.IDBStorageEnabled = false;
  79765. Database._ParseURL = function (url) {
  79766. var a = document.createElement('a');
  79767. a.href = url;
  79768. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  79769. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  79770. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  79771. return absLocation;
  79772. };
  79773. Database._ReturnFullUrlLocation = function (url) {
  79774. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  79775. return (Database._ParseURL(window.location.href) + url);
  79776. }
  79777. else {
  79778. return url;
  79779. }
  79780. };
  79781. return Database;
  79782. }());
  79783. BABYLON.Database = Database;
  79784. })(BABYLON || (BABYLON = {}));
  79785. //# sourceMappingURL=babylon.database.js.map
  79786. var BABYLON;
  79787. (function (BABYLON) {
  79788. /**
  79789. * This represents all the required information to add a fresnel effect on a material:
  79790. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  79791. */
  79792. var FresnelParameters = /** @class */ (function () {
  79793. function FresnelParameters() {
  79794. this._isEnabled = true;
  79795. /**
  79796. * Define the color used on edges (grazing angle)
  79797. */
  79798. this.leftColor = BABYLON.Color3.White();
  79799. /**
  79800. * Define the color used on center
  79801. */
  79802. this.rightColor = BABYLON.Color3.Black();
  79803. /**
  79804. * Define bias applied to computed fresnel term
  79805. */
  79806. this.bias = 0;
  79807. /**
  79808. * Defined the power exponent applied to fresnel term
  79809. */
  79810. this.power = 1;
  79811. }
  79812. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  79813. /**
  79814. * Define if the fresnel effect is enable or not.
  79815. */
  79816. get: function () {
  79817. return this._isEnabled;
  79818. },
  79819. set: function (value) {
  79820. if (this._isEnabled === value) {
  79821. return;
  79822. }
  79823. this._isEnabled = value;
  79824. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  79825. },
  79826. enumerable: true,
  79827. configurable: true
  79828. });
  79829. /**
  79830. * Clones the current fresnel and its valuues
  79831. * @returns a clone fresnel configuration
  79832. */
  79833. FresnelParameters.prototype.clone = function () {
  79834. var newFresnelParameters = new FresnelParameters();
  79835. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  79836. return newFresnelParameters;
  79837. };
  79838. /**
  79839. * Serializes the current fresnel parameters to a JSON representation.
  79840. * @return the JSON serialization
  79841. */
  79842. FresnelParameters.prototype.serialize = function () {
  79843. var serializationObject = {};
  79844. serializationObject.isEnabled = this.isEnabled;
  79845. serializationObject.leftColor = this.leftColor.asArray();
  79846. serializationObject.rightColor = this.rightColor.asArray();
  79847. serializationObject.bias = this.bias;
  79848. serializationObject.power = this.power;
  79849. return serializationObject;
  79850. };
  79851. /**
  79852. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  79853. * @param parsedFresnelParameters Define the JSON representation
  79854. * @returns the parsed parameters
  79855. */
  79856. FresnelParameters.Parse = function (parsedFresnelParameters) {
  79857. var fresnelParameters = new FresnelParameters();
  79858. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  79859. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  79860. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  79861. fresnelParameters.bias = parsedFresnelParameters.bias;
  79862. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  79863. return fresnelParameters;
  79864. };
  79865. return FresnelParameters;
  79866. }());
  79867. BABYLON.FresnelParameters = FresnelParameters;
  79868. })(BABYLON || (BABYLON = {}));
  79869. //# sourceMappingURL=babylon.fresnelParameters.js.map
  79870. var BABYLON;
  79871. (function (BABYLON) {
  79872. /**
  79873. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79874. * separate meshes. This can be use to improve performances.
  79875. * @see http://doc.babylonjs.com/how_to/multi_materials
  79876. */
  79877. var MultiMaterial = /** @class */ (function (_super) {
  79878. __extends(MultiMaterial, _super);
  79879. /**
  79880. * Instantiates a new Multi Material
  79881. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79882. * separate meshes. This can be use to improve performances.
  79883. * @see http://doc.babylonjs.com/how_to/multi_materials
  79884. * @param name Define the name in the scene
  79885. * @param scene Define the scene the material belongs to
  79886. */
  79887. function MultiMaterial(name, scene) {
  79888. var _this = _super.call(this, name, scene, true) || this;
  79889. scene.multiMaterials.push(_this);
  79890. _this.subMaterials = new Array();
  79891. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  79892. return _this;
  79893. }
  79894. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  79895. /**
  79896. * Gets or Sets the list of Materials used within the multi material.
  79897. * They need to be ordered according to the submeshes order in the associated mesh
  79898. */
  79899. get: function () {
  79900. return this._subMaterials;
  79901. },
  79902. set: function (value) {
  79903. this._subMaterials = value;
  79904. this._hookArray(value);
  79905. },
  79906. enumerable: true,
  79907. configurable: true
  79908. });
  79909. MultiMaterial.prototype._hookArray = function (array) {
  79910. var _this = this;
  79911. var oldPush = array.push;
  79912. array.push = function () {
  79913. var items = [];
  79914. for (var _i = 0; _i < arguments.length; _i++) {
  79915. items[_i] = arguments[_i];
  79916. }
  79917. var result = oldPush.apply(array, items);
  79918. _this._markAllSubMeshesAsTexturesDirty();
  79919. return result;
  79920. };
  79921. var oldSplice = array.splice;
  79922. array.splice = function (index, deleteCount) {
  79923. var deleted = oldSplice.apply(array, [index, deleteCount]);
  79924. _this._markAllSubMeshesAsTexturesDirty();
  79925. return deleted;
  79926. };
  79927. };
  79928. /**
  79929. * Get one of the submaterial by its index in the submaterials array
  79930. * @param index The index to look the sub material at
  79931. * @returns The Material if the index has been defined
  79932. */
  79933. MultiMaterial.prototype.getSubMaterial = function (index) {
  79934. if (index < 0 || index >= this.subMaterials.length) {
  79935. return this.getScene().defaultMaterial;
  79936. }
  79937. return this.subMaterials[index];
  79938. };
  79939. /**
  79940. * Get the list of active textures for the whole sub materials list.
  79941. * @returns All the textures that will be used during the rendering
  79942. */
  79943. MultiMaterial.prototype.getActiveTextures = function () {
  79944. var _a;
  79945. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  79946. if (subMaterial) {
  79947. return subMaterial.getActiveTextures();
  79948. }
  79949. else {
  79950. return [];
  79951. }
  79952. }));
  79953. };
  79954. /**
  79955. * Gets the current class name of the material e.g. "MultiMaterial"
  79956. * Mainly use in serialization.
  79957. * @returns the class name
  79958. */
  79959. MultiMaterial.prototype.getClassName = function () {
  79960. return "MultiMaterial";
  79961. };
  79962. /**
  79963. * Checks if the material is ready to render the requested sub mesh
  79964. * @param mesh Define the mesh the submesh belongs to
  79965. * @param subMesh Define the sub mesh to look readyness for
  79966. * @param useInstances Define whether or not the material is used with instances
  79967. * @returns true if ready, otherwise false
  79968. */
  79969. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79970. for (var index = 0; index < this.subMaterials.length; index++) {
  79971. var subMaterial = this.subMaterials[index];
  79972. if (subMaterial) {
  79973. if (subMaterial._storeEffectOnSubMeshes) {
  79974. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  79975. return false;
  79976. }
  79977. continue;
  79978. }
  79979. if (!subMaterial.isReady(mesh)) {
  79980. return false;
  79981. }
  79982. }
  79983. }
  79984. return true;
  79985. };
  79986. /**
  79987. * Clones the current material and its related sub materials
  79988. * @param name Define the name of the newly cloned material
  79989. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  79990. * @returns the cloned material
  79991. */
  79992. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  79993. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  79994. for (var index = 0; index < this.subMaterials.length; index++) {
  79995. var subMaterial = null;
  79996. var current = this.subMaterials[index];
  79997. if (cloneChildren && current) {
  79998. subMaterial = current.clone(name + "-" + current.name);
  79999. }
  80000. else {
  80001. subMaterial = this.subMaterials[index];
  80002. }
  80003. newMultiMaterial.subMaterials.push(subMaterial);
  80004. }
  80005. return newMultiMaterial;
  80006. };
  80007. /**
  80008. * Serializes the materials into a JSON representation.
  80009. * @returns the JSON representation
  80010. */
  80011. MultiMaterial.prototype.serialize = function () {
  80012. var serializationObject = {};
  80013. serializationObject.name = this.name;
  80014. serializationObject.id = this.id;
  80015. if (BABYLON.Tags) {
  80016. serializationObject.tags = BABYLON.Tags.GetTags(this);
  80017. }
  80018. serializationObject.materials = [];
  80019. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  80020. var subMat = this.subMaterials[matIndex];
  80021. if (subMat) {
  80022. serializationObject.materials.push(subMat.id);
  80023. }
  80024. else {
  80025. serializationObject.materials.push(null);
  80026. }
  80027. }
  80028. return serializationObject;
  80029. };
  80030. /**
  80031. * Dispose the material and release its associated resources
  80032. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  80033. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  80034. */
  80035. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80036. var scene = this.getScene();
  80037. if (!scene) {
  80038. return;
  80039. }
  80040. var index = scene.multiMaterials.indexOf(this);
  80041. if (index >= 0) {
  80042. scene.multiMaterials.splice(index, 1);
  80043. }
  80044. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  80045. };
  80046. return MultiMaterial;
  80047. }(BABYLON.Material));
  80048. BABYLON.MultiMaterial = MultiMaterial;
  80049. })(BABYLON || (BABYLON = {}));
  80050. //# sourceMappingURL=babylon.multiMaterial.js.map
  80051. var BABYLON;
  80052. (function (BABYLON) {
  80053. /**
  80054. * Manage the touch inputs to control the movement of a free camera.
  80055. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80056. */
  80057. var FreeCameraTouchInput = /** @class */ (function () {
  80058. function FreeCameraTouchInput() {
  80059. /**
  80060. * Defines the touch sensibility for rotation.
  80061. * The higher the faster.
  80062. */
  80063. this.touchAngularSensibility = 200000.0;
  80064. /**
  80065. * Defines the touch sensibility for move.
  80066. * The higher the faster.
  80067. */
  80068. this.touchMoveSensibility = 250.0;
  80069. this._offsetX = null;
  80070. this._offsetY = null;
  80071. this._pointerPressed = new Array();
  80072. }
  80073. /**
  80074. * Attach the input controls to a specific dom element to get the input from.
  80075. * @param element Defines the element the controls should be listened from
  80076. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80077. */
  80078. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  80079. var _this = this;
  80080. var previousPosition = null;
  80081. if (this._pointerInput === undefined) {
  80082. this._onLostFocus = function (evt) {
  80083. _this._offsetX = null;
  80084. _this._offsetY = null;
  80085. };
  80086. this._pointerInput = function (p, s) {
  80087. var evt = p.event;
  80088. if (evt.pointerType === "mouse") {
  80089. return;
  80090. }
  80091. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80092. if (!noPreventDefault) {
  80093. evt.preventDefault();
  80094. }
  80095. _this._pointerPressed.push(evt.pointerId);
  80096. if (_this._pointerPressed.length !== 1) {
  80097. return;
  80098. }
  80099. previousPosition = {
  80100. x: evt.clientX,
  80101. y: evt.clientY
  80102. };
  80103. }
  80104. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  80105. if (!noPreventDefault) {
  80106. evt.preventDefault();
  80107. }
  80108. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80109. if (index === -1) {
  80110. return;
  80111. }
  80112. _this._pointerPressed.splice(index, 1);
  80113. if (index != 0) {
  80114. return;
  80115. }
  80116. previousPosition = null;
  80117. _this._offsetX = null;
  80118. _this._offsetY = null;
  80119. }
  80120. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  80121. if (!noPreventDefault) {
  80122. evt.preventDefault();
  80123. }
  80124. if (!previousPosition) {
  80125. return;
  80126. }
  80127. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80128. if (index != 0) {
  80129. return;
  80130. }
  80131. _this._offsetX = evt.clientX - previousPosition.x;
  80132. _this._offsetY = -(evt.clientY - previousPosition.y);
  80133. }
  80134. };
  80135. }
  80136. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  80137. if (this._onLostFocus) {
  80138. element.addEventListener("blur", this._onLostFocus);
  80139. }
  80140. };
  80141. /**
  80142. * Detach the current controls from the specified dom element.
  80143. * @param element Defines the element to stop listening the inputs from
  80144. */
  80145. FreeCameraTouchInput.prototype.detachControl = function (element) {
  80146. if (this._pointerInput && element) {
  80147. if (this._observer) {
  80148. this.camera.getScene().onPointerObservable.remove(this._observer);
  80149. this._observer = null;
  80150. }
  80151. if (this._onLostFocus) {
  80152. element.removeEventListener("blur", this._onLostFocus);
  80153. this._onLostFocus = null;
  80154. }
  80155. this._pointerPressed = [];
  80156. this._offsetX = null;
  80157. this._offsetY = null;
  80158. }
  80159. };
  80160. /**
  80161. * Update the current camera state depending on the inputs that have been used this frame.
  80162. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80163. */
  80164. FreeCameraTouchInput.prototype.checkInputs = function () {
  80165. if (this._offsetX && this._offsetY) {
  80166. var camera = this.camera;
  80167. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  80168. if (this._pointerPressed.length > 1) {
  80169. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  80170. }
  80171. else {
  80172. var speed = camera._computeLocalCameraSpeed();
  80173. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  80174. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  80175. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  80176. }
  80177. }
  80178. };
  80179. /**
  80180. * Gets the class name of the current intput.
  80181. * @returns the class name
  80182. */
  80183. FreeCameraTouchInput.prototype.getClassName = function () {
  80184. return "FreeCameraTouchInput";
  80185. };
  80186. /**
  80187. * Get the friendly name associated with the input class.
  80188. * @returns the input friendly name
  80189. */
  80190. FreeCameraTouchInput.prototype.getSimpleName = function () {
  80191. return "touch";
  80192. };
  80193. __decorate([
  80194. BABYLON.serialize()
  80195. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  80196. __decorate([
  80197. BABYLON.serialize()
  80198. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  80199. return FreeCameraTouchInput;
  80200. }());
  80201. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  80202. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  80203. })(BABYLON || (BABYLON = {}));
  80204. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  80205. var BABYLON;
  80206. (function (BABYLON) {
  80207. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  80208. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  80209. });
  80210. /**
  80211. * This represents a FPS type of camera controlled by touch.
  80212. * This is like a universal camera minus the Gamepad controls.
  80213. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80214. */
  80215. var TouchCamera = /** @class */ (function (_super) {
  80216. __extends(TouchCamera, _super);
  80217. /**
  80218. * Instantiates a new touch camera.
  80219. * This represents a FPS type of camera controlled by touch.
  80220. * This is like a universal camera minus the Gamepad controls.
  80221. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80222. * @param name Define the name of the camera in the scene
  80223. * @param position Define the start position of the camera in the scene
  80224. * @param scene Define the scene the camera belongs to
  80225. */
  80226. function TouchCamera(name, position, scene) {
  80227. var _this = _super.call(this, name, position, scene) || this;
  80228. _this.inputs.addTouch();
  80229. _this._setupInputs();
  80230. return _this;
  80231. }
  80232. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  80233. /**
  80234. * Defines the touch sensibility for rotation.
  80235. * The higher the faster.
  80236. */
  80237. get: function () {
  80238. var touch = this.inputs.attached["touch"];
  80239. if (touch) {
  80240. return touch.touchAngularSensibility;
  80241. }
  80242. return 0;
  80243. },
  80244. set: function (value) {
  80245. var touch = this.inputs.attached["touch"];
  80246. if (touch) {
  80247. touch.touchAngularSensibility = value;
  80248. }
  80249. },
  80250. enumerable: true,
  80251. configurable: true
  80252. });
  80253. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  80254. /**
  80255. * Defines the touch sensibility for move.
  80256. * The higher the faster.
  80257. */
  80258. get: function () {
  80259. var touch = this.inputs.attached["touch"];
  80260. if (touch) {
  80261. return touch.touchMoveSensibility;
  80262. }
  80263. return 0;
  80264. },
  80265. set: function (value) {
  80266. var touch = this.inputs.attached["touch"];
  80267. if (touch) {
  80268. touch.touchMoveSensibility = value;
  80269. }
  80270. },
  80271. enumerable: true,
  80272. configurable: true
  80273. });
  80274. /**
  80275. * Gets the current object class name.
  80276. * @return the class name
  80277. */
  80278. TouchCamera.prototype.getClassName = function () {
  80279. return "TouchCamera";
  80280. };
  80281. /** @hidden */
  80282. TouchCamera.prototype._setupInputs = function () {
  80283. var mouse = this.inputs.attached["mouse"];
  80284. if (mouse) {
  80285. mouse.touchEnabled = false;
  80286. }
  80287. };
  80288. return TouchCamera;
  80289. }(BABYLON.FreeCamera));
  80290. BABYLON.TouchCamera = TouchCamera;
  80291. })(BABYLON || (BABYLON = {}));
  80292. //# sourceMappingURL=babylon.touchCamera.js.map
  80293. var BABYLON;
  80294. (function (BABYLON) {
  80295. /**
  80296. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80297. * This is the base class of any Procedural texture and contains most of the shareable code.
  80298. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80299. */
  80300. var ProceduralTexture = /** @class */ (function (_super) {
  80301. __extends(ProceduralTexture, _super);
  80302. /**
  80303. * Instantiates a new procedural texture.
  80304. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80305. * This is the base class of any Procedural texture and contains most of the shareable code.
  80306. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80307. * @param name Define the name of the texture
  80308. * @param size Define the size of the texture to create
  80309. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  80310. * @param scene Define the scene the texture belongs to
  80311. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80312. * @param generateMipMaps Define if the texture should creates mip maps or not
  80313. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  80314. */
  80315. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  80316. if (fallbackTexture === void 0) { fallbackTexture = null; }
  80317. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80318. if (isCube === void 0) { isCube = false; }
  80319. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  80320. _this.isCube = isCube;
  80321. /**
  80322. * Define if the texture is enabled or not (disabled texture will not render)
  80323. */
  80324. _this.isEnabled = true;
  80325. /**
  80326. * Define if the texture must be cleared before rendering (default is true)
  80327. */
  80328. _this.autoClear = true;
  80329. /**
  80330. * Event raised when the texture is generated
  80331. */
  80332. _this.onGeneratedObservable = new BABYLON.Observable();
  80333. /** @hidden */
  80334. _this._textures = {};
  80335. _this._currentRefreshId = -1;
  80336. _this._refreshRate = 1;
  80337. _this._vertexBuffers = {};
  80338. _this._uniforms = new Array();
  80339. _this._samplers = new Array();
  80340. _this._floats = {};
  80341. _this._ints = {};
  80342. _this._floatsArrays = {};
  80343. _this._colors3 = {};
  80344. _this._colors4 = {};
  80345. _this._vectors2 = {};
  80346. _this._vectors3 = {};
  80347. _this._matrices = {};
  80348. _this._fallbackTextureUsed = false;
  80349. _this._cachedDefines = "";
  80350. _this._contentUpdateId = -1;
  80351. scene = _this.getScene();
  80352. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  80353. if (!component) {
  80354. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  80355. scene._addComponent(component);
  80356. }
  80357. scene.proceduralTextures.push(_this);
  80358. _this._engine = scene.getEngine();
  80359. _this.name = name;
  80360. _this.isRenderTarget = true;
  80361. _this._size = size;
  80362. _this._generateMipMaps = generateMipMaps;
  80363. _this.setFragment(fragment);
  80364. _this._fallbackTexture = fallbackTexture;
  80365. if (isCube) {
  80366. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80367. _this.setFloat("face", 0);
  80368. }
  80369. else {
  80370. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80371. }
  80372. // VBO
  80373. var vertices = [];
  80374. vertices.push(1, 1);
  80375. vertices.push(-1, 1);
  80376. vertices.push(-1, -1);
  80377. vertices.push(1, -1);
  80378. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80379. _this._createIndexBuffer();
  80380. return _this;
  80381. }
  80382. /**
  80383. * The effect that is created when initializing the post process.
  80384. * @returns The created effect corrisponding the the postprocess.
  80385. */
  80386. ProceduralTexture.prototype.getEffect = function () {
  80387. return this._effect;
  80388. };
  80389. /**
  80390. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  80391. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  80392. */
  80393. ProceduralTexture.prototype.getContent = function () {
  80394. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  80395. return this._contentData;
  80396. }
  80397. this._contentData = this.readPixels(0, 0, this._contentData);
  80398. this._contentUpdateId = this._currentRefreshId;
  80399. return this._contentData;
  80400. };
  80401. ProceduralTexture.prototype._createIndexBuffer = function () {
  80402. var engine = this._engine;
  80403. // Indices
  80404. var indices = [];
  80405. indices.push(0);
  80406. indices.push(1);
  80407. indices.push(2);
  80408. indices.push(0);
  80409. indices.push(2);
  80410. indices.push(3);
  80411. this._indexBuffer = engine.createIndexBuffer(indices);
  80412. };
  80413. /** @hidden */
  80414. ProceduralTexture.prototype._rebuild = function () {
  80415. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80416. if (vb) {
  80417. vb._rebuild();
  80418. }
  80419. this._createIndexBuffer();
  80420. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  80421. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  80422. }
  80423. };
  80424. /**
  80425. * Resets the texture in order to recreate its associated resources.
  80426. * This can be called in case of context loss
  80427. */
  80428. ProceduralTexture.prototype.reset = function () {
  80429. if (this._effect === undefined) {
  80430. return;
  80431. }
  80432. var engine = this._engine;
  80433. engine._releaseEffect(this._effect);
  80434. };
  80435. ProceduralTexture.prototype._getDefines = function () {
  80436. return "";
  80437. };
  80438. /**
  80439. * Is the texture ready to be used ? (rendered at least once)
  80440. * @returns true if ready, otherwise, false.
  80441. */
  80442. ProceduralTexture.prototype.isReady = function () {
  80443. var _this = this;
  80444. var engine = this._engine;
  80445. var shaders;
  80446. if (!this._fragment) {
  80447. return false;
  80448. }
  80449. if (this._fallbackTextureUsed) {
  80450. return true;
  80451. }
  80452. var defines = this._getDefines();
  80453. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  80454. return true;
  80455. }
  80456. if (this._fragment.fragmentElement !== undefined) {
  80457. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  80458. }
  80459. else {
  80460. shaders = { vertex: "procedural", fragment: this._fragment };
  80461. }
  80462. this._cachedDefines = defines;
  80463. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  80464. _this.releaseInternalTexture();
  80465. if (_this._fallbackTexture) {
  80466. _this._texture = _this._fallbackTexture._texture;
  80467. if (_this._texture) {
  80468. _this._texture.incrementReferences();
  80469. }
  80470. }
  80471. _this._fallbackTextureUsed = true;
  80472. });
  80473. return this._effect.isReady();
  80474. };
  80475. /**
  80476. * Resets the refresh counter of the texture and start bak from scratch.
  80477. * Could be usefull to regenerate the texture if it is setup to render only once.
  80478. */
  80479. ProceduralTexture.prototype.resetRefreshCounter = function () {
  80480. this._currentRefreshId = -1;
  80481. };
  80482. /**
  80483. * Set the fragment shader to use in order to render the texture.
  80484. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  80485. */
  80486. ProceduralTexture.prototype.setFragment = function (fragment) {
  80487. this._fragment = fragment;
  80488. };
  80489. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  80490. /**
  80491. * Define the refresh rate of the texture or the rendering frequency.
  80492. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  80493. */
  80494. get: function () {
  80495. return this._refreshRate;
  80496. },
  80497. set: function (value) {
  80498. this._refreshRate = value;
  80499. this.resetRefreshCounter();
  80500. },
  80501. enumerable: true,
  80502. configurable: true
  80503. });
  80504. /** @hidden */
  80505. ProceduralTexture.prototype._shouldRender = function () {
  80506. if (!this.isEnabled || !this.isReady() || !this._texture) {
  80507. if (this._texture) {
  80508. this._texture.isReady = false;
  80509. }
  80510. return false;
  80511. }
  80512. if (this._fallbackTextureUsed) {
  80513. return false;
  80514. }
  80515. if (this._currentRefreshId === -1) { // At least render once
  80516. this._currentRefreshId = 1;
  80517. return true;
  80518. }
  80519. if (this.refreshRate === this._currentRefreshId) {
  80520. this._currentRefreshId = 1;
  80521. return true;
  80522. }
  80523. this._currentRefreshId++;
  80524. return false;
  80525. };
  80526. /**
  80527. * Get the size the texture is rendering at.
  80528. * @returns the size (texture is always squared)
  80529. */
  80530. ProceduralTexture.prototype.getRenderSize = function () {
  80531. return this._size;
  80532. };
  80533. /**
  80534. * Resize the texture to new value.
  80535. * @param size Define the new size the texture should have
  80536. * @param generateMipMaps Define whether the new texture should create mip maps
  80537. */
  80538. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  80539. if (this._fallbackTextureUsed) {
  80540. return;
  80541. }
  80542. this.releaseInternalTexture();
  80543. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  80544. // Update properties
  80545. this._size = size;
  80546. this._generateMipMaps = generateMipMaps;
  80547. };
  80548. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  80549. if (this._uniforms.indexOf(uniformName) === -1) {
  80550. this._uniforms.push(uniformName);
  80551. }
  80552. };
  80553. /**
  80554. * Set a texture in the shader program used to render.
  80555. * @param name Define the name of the uniform samplers as defined in the shader
  80556. * @param texture Define the texture to bind to this sampler
  80557. * @return the texture itself allowing "fluent" like uniform updates
  80558. */
  80559. ProceduralTexture.prototype.setTexture = function (name, texture) {
  80560. if (this._samplers.indexOf(name) === -1) {
  80561. this._samplers.push(name);
  80562. }
  80563. this._textures[name] = texture;
  80564. return this;
  80565. };
  80566. /**
  80567. * Set a float in the shader.
  80568. * @param name Define the name of the uniform as defined in the shader
  80569. * @param value Define the value to give to the uniform
  80570. * @return the texture itself allowing "fluent" like uniform updates
  80571. */
  80572. ProceduralTexture.prototype.setFloat = function (name, value) {
  80573. this._checkUniform(name);
  80574. this._floats[name] = value;
  80575. return this;
  80576. };
  80577. /**
  80578. * Set a int in the shader.
  80579. * @param name Define the name of the uniform as defined in the shader
  80580. * @param value Define the value to give to the uniform
  80581. * @return the texture itself allowing "fluent" like uniform updates
  80582. */
  80583. ProceduralTexture.prototype.setInt = function (name, value) {
  80584. this._checkUniform(name);
  80585. this._ints[name] = value;
  80586. return this;
  80587. };
  80588. /**
  80589. * Set an array of floats in the shader.
  80590. * @param name Define the name of the uniform as defined in the shader
  80591. * @param value Define the value to give to the uniform
  80592. * @return the texture itself allowing "fluent" like uniform updates
  80593. */
  80594. ProceduralTexture.prototype.setFloats = function (name, value) {
  80595. this._checkUniform(name);
  80596. this._floatsArrays[name] = value;
  80597. return this;
  80598. };
  80599. /**
  80600. * Set a vec3 in the shader from a Color3.
  80601. * @param name Define the name of the uniform as defined in the shader
  80602. * @param value Define the value to give to the uniform
  80603. * @return the texture itself allowing "fluent" like uniform updates
  80604. */
  80605. ProceduralTexture.prototype.setColor3 = function (name, value) {
  80606. this._checkUniform(name);
  80607. this._colors3[name] = value;
  80608. return this;
  80609. };
  80610. /**
  80611. * Set a vec4 in the shader from a Color4.
  80612. * @param name Define the name of the uniform as defined in the shader
  80613. * @param value Define the value to give to the uniform
  80614. * @return the texture itself allowing "fluent" like uniform updates
  80615. */
  80616. ProceduralTexture.prototype.setColor4 = function (name, value) {
  80617. this._checkUniform(name);
  80618. this._colors4[name] = value;
  80619. return this;
  80620. };
  80621. /**
  80622. * Set a vec2 in the shader from a Vector2.
  80623. * @param name Define the name of the uniform as defined in the shader
  80624. * @param value Define the value to give to the uniform
  80625. * @return the texture itself allowing "fluent" like uniform updates
  80626. */
  80627. ProceduralTexture.prototype.setVector2 = function (name, value) {
  80628. this._checkUniform(name);
  80629. this._vectors2[name] = value;
  80630. return this;
  80631. };
  80632. /**
  80633. * Set a vec3 in the shader from a Vector3.
  80634. * @param name Define the name of the uniform as defined in the shader
  80635. * @param value Define the value to give to the uniform
  80636. * @return the texture itself allowing "fluent" like uniform updates
  80637. */
  80638. ProceduralTexture.prototype.setVector3 = function (name, value) {
  80639. this._checkUniform(name);
  80640. this._vectors3[name] = value;
  80641. return this;
  80642. };
  80643. /**
  80644. * Set a mat4 in the shader from a MAtrix.
  80645. * @param name Define the name of the uniform as defined in the shader
  80646. * @param value Define the value to give to the uniform
  80647. * @return the texture itself allowing "fluent" like uniform updates
  80648. */
  80649. ProceduralTexture.prototype.setMatrix = function (name, value) {
  80650. this._checkUniform(name);
  80651. this._matrices[name] = value;
  80652. return this;
  80653. };
  80654. /**
  80655. * Render the texture to its associated render target.
  80656. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80657. */
  80658. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80659. var scene = this.getScene();
  80660. if (!scene) {
  80661. return;
  80662. }
  80663. var engine = this._engine;
  80664. // Render
  80665. engine.enableEffect(this._effect);
  80666. engine.setState(false);
  80667. // Texture
  80668. for (var name in this._textures) {
  80669. this._effect.setTexture(name, this._textures[name]);
  80670. }
  80671. // Float
  80672. for (name in this._ints) {
  80673. this._effect.setInt(name, this._ints[name]);
  80674. }
  80675. // Float
  80676. for (name in this._floats) {
  80677. this._effect.setFloat(name, this._floats[name]);
  80678. }
  80679. // Floats
  80680. for (name in this._floatsArrays) {
  80681. this._effect.setArray(name, this._floatsArrays[name]);
  80682. }
  80683. // Color3
  80684. for (name in this._colors3) {
  80685. this._effect.setColor3(name, this._colors3[name]);
  80686. }
  80687. // Color4
  80688. for (name in this._colors4) {
  80689. var color = this._colors4[name];
  80690. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  80691. }
  80692. // Vector2
  80693. for (name in this._vectors2) {
  80694. this._effect.setVector2(name, this._vectors2[name]);
  80695. }
  80696. // Vector3
  80697. for (name in this._vectors3) {
  80698. this._effect.setVector3(name, this._vectors3[name]);
  80699. }
  80700. // Matrix
  80701. for (name in this._matrices) {
  80702. this._effect.setMatrix(name, this._matrices[name]);
  80703. }
  80704. if (!this._texture) {
  80705. return;
  80706. }
  80707. if (this.isCube) {
  80708. for (var face = 0; face < 6; face++) {
  80709. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  80710. // VBOs
  80711. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80712. this._effect.setFloat("face", face);
  80713. // Clear
  80714. if (this.autoClear) {
  80715. engine.clear(scene.clearColor, true, false, false);
  80716. }
  80717. // Draw order
  80718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80719. // Mipmaps
  80720. if (face === 5) {
  80721. engine.generateMipMapsForCubemap(this._texture);
  80722. }
  80723. }
  80724. }
  80725. else {
  80726. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  80727. // VBOs
  80728. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80729. // Clear
  80730. if (this.autoClear) {
  80731. engine.clear(scene.clearColor, true, false, false);
  80732. }
  80733. // Draw order
  80734. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80735. }
  80736. // Unbind
  80737. engine.unBindFramebuffer(this._texture, this.isCube);
  80738. if (this.onGenerated) {
  80739. this.onGenerated();
  80740. }
  80741. this.onGeneratedObservable.notifyObservers(this);
  80742. };
  80743. /**
  80744. * Clone the texture.
  80745. * @returns the cloned texture
  80746. */
  80747. ProceduralTexture.prototype.clone = function () {
  80748. var textureSize = this.getSize();
  80749. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  80750. // Base texture
  80751. newTexture.hasAlpha = this.hasAlpha;
  80752. newTexture.level = this.level;
  80753. // RenderTarget Texture
  80754. newTexture.coordinatesMode = this.coordinatesMode;
  80755. return newTexture;
  80756. };
  80757. /**
  80758. * Dispose the texture and release its asoociated resources.
  80759. */
  80760. ProceduralTexture.prototype.dispose = function () {
  80761. var scene = this.getScene();
  80762. if (!scene) {
  80763. return;
  80764. }
  80765. var index = scene.proceduralTextures.indexOf(this);
  80766. if (index >= 0) {
  80767. scene.proceduralTextures.splice(index, 1);
  80768. }
  80769. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80770. if (vertexBuffer) {
  80771. vertexBuffer.dispose();
  80772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80773. }
  80774. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  80775. this._indexBuffer = null;
  80776. }
  80777. _super.prototype.dispose.call(this);
  80778. };
  80779. __decorate([
  80780. BABYLON.serialize()
  80781. ], ProceduralTexture.prototype, "isEnabled", void 0);
  80782. __decorate([
  80783. BABYLON.serialize()
  80784. ], ProceduralTexture.prototype, "autoClear", void 0);
  80785. __decorate([
  80786. BABYLON.serialize()
  80787. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  80788. __decorate([
  80789. BABYLON.serialize()
  80790. ], ProceduralTexture.prototype, "_size", void 0);
  80791. __decorate([
  80792. BABYLON.serialize()
  80793. ], ProceduralTexture.prototype, "refreshRate", null);
  80794. return ProceduralTexture;
  80795. }(BABYLON.Texture));
  80796. BABYLON.ProceduralTexture = ProceduralTexture;
  80797. })(BABYLON || (BABYLON = {}));
  80798. //# sourceMappingURL=babylon.proceduralTexture.js.map
  80799. var BABYLON;
  80800. (function (BABYLON) {
  80801. /**
  80802. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  80803. * in a given scene.
  80804. */
  80805. var ProceduralTextureSceneComponent = /** @class */ (function () {
  80806. /**
  80807. * Creates a new instance of the component for the given scene
  80808. * @param scene Defines the scene to register the component in
  80809. */
  80810. function ProceduralTextureSceneComponent(scene) {
  80811. /**
  80812. * The component name helpfull to identify the component in the list of scene components.
  80813. */
  80814. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  80815. this.scene = scene;
  80816. this.scene.proceduralTextures = new Array();
  80817. scene.layers = new Array();
  80818. }
  80819. /**
  80820. * Registers the component in a given scene
  80821. */
  80822. ProceduralTextureSceneComponent.prototype.register = function () {
  80823. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  80824. };
  80825. /**
  80826. * Rebuilds the elements related to this component in case of
  80827. * context lost for instance.
  80828. */
  80829. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  80830. // Nothing to do here.
  80831. };
  80832. /**
  80833. * Disposes the component and the associated ressources.
  80834. */
  80835. ProceduralTextureSceneComponent.prototype.dispose = function () {
  80836. // Nothing to do here.
  80837. };
  80838. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  80839. if (this.scene.proceduralTexturesEnabled) {
  80840. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80841. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  80842. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  80843. if (proceduralTexture._shouldRender()) {
  80844. proceduralTexture.render();
  80845. }
  80846. }
  80847. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80848. }
  80849. };
  80850. return ProceduralTextureSceneComponent;
  80851. }());
  80852. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  80853. })(BABYLON || (BABYLON = {}));
  80854. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  80855. var BABYLON;
  80856. (function (BABYLON) {
  80857. /**
  80858. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80859. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80860. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80861. */
  80862. var CustomProceduralTexture = /** @class */ (function (_super) {
  80863. __extends(CustomProceduralTexture, _super);
  80864. /**
  80865. * Instantiates a new Custom Procedural Texture.
  80866. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80867. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80868. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80869. * @param name Define the name of the texture
  80870. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  80871. * @param size Define the size of the texture to create
  80872. * @param scene Define the scene the texture belongs to
  80873. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80874. * @param generateMipMaps Define if the texture should creates mip maps or not
  80875. */
  80876. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  80877. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  80878. _this._animate = true;
  80879. _this._time = 0;
  80880. _this._texturePath = texturePath;
  80881. //Try to load json
  80882. _this._loadJson(texturePath);
  80883. _this.refreshRate = 1;
  80884. return _this;
  80885. }
  80886. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  80887. var _this = this;
  80888. var noConfigFile = function () {
  80889. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  80890. try {
  80891. _this.setFragment(_this._texturePath);
  80892. }
  80893. catch (ex) {
  80894. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  80895. }
  80896. };
  80897. var configFileUrl = jsonUrl + "/config.json";
  80898. var xhr = new XMLHttpRequest();
  80899. xhr.open("GET", configFileUrl, true);
  80900. xhr.addEventListener("load", function () {
  80901. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  80902. try {
  80903. _this._config = JSON.parse(xhr.response);
  80904. _this.updateShaderUniforms();
  80905. _this.updateTextures();
  80906. _this.setFragment(_this._texturePath + "/custom");
  80907. _this._animate = _this._config.animate;
  80908. _this.refreshRate = _this._config.refreshrate;
  80909. }
  80910. catch (ex) {
  80911. noConfigFile();
  80912. }
  80913. }
  80914. else {
  80915. noConfigFile();
  80916. }
  80917. }, false);
  80918. xhr.addEventListener("error", function () {
  80919. noConfigFile();
  80920. }, false);
  80921. try {
  80922. xhr.send();
  80923. }
  80924. catch (ex) {
  80925. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  80926. }
  80927. };
  80928. /**
  80929. * Is the texture ready to be used ? (rendered at least once)
  80930. * @returns true if ready, otherwise, false.
  80931. */
  80932. CustomProceduralTexture.prototype.isReady = function () {
  80933. if (!_super.prototype.isReady.call(this)) {
  80934. return false;
  80935. }
  80936. for (var name in this._textures) {
  80937. var texture = this._textures[name];
  80938. if (!texture.isReady()) {
  80939. return false;
  80940. }
  80941. }
  80942. return true;
  80943. };
  80944. /**
  80945. * Render the texture to its associated render target.
  80946. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80947. */
  80948. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80949. var scene = this.getScene();
  80950. if (this._animate && scene) {
  80951. this._time += scene.getAnimationRatio() * 0.03;
  80952. this.updateShaderUniforms();
  80953. }
  80954. _super.prototype.render.call(this, useCameraPostProcess);
  80955. };
  80956. /**
  80957. * Update the list of dependant textures samplers in the shader.
  80958. */
  80959. CustomProceduralTexture.prototype.updateTextures = function () {
  80960. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  80961. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  80962. }
  80963. };
  80964. /**
  80965. * Update the uniform values of the procedural texture in the shader.
  80966. */
  80967. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  80968. if (this._config) {
  80969. for (var j = 0; j < this._config.uniforms.length; j++) {
  80970. var uniform = this._config.uniforms[j];
  80971. switch (uniform.type) {
  80972. case "float":
  80973. this.setFloat(uniform.name, uniform.value);
  80974. break;
  80975. case "color3":
  80976. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  80977. break;
  80978. case "color4":
  80979. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  80980. break;
  80981. case "vector2":
  80982. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  80983. break;
  80984. case "vector3":
  80985. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  80986. break;
  80987. }
  80988. }
  80989. }
  80990. this.setFloat("time", this._time);
  80991. };
  80992. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  80993. /**
  80994. * Define if the texture animates or not.
  80995. */
  80996. get: function () {
  80997. return this._animate;
  80998. },
  80999. set: function (value) {
  81000. this._animate = value;
  81001. },
  81002. enumerable: true,
  81003. configurable: true
  81004. });
  81005. return CustomProceduralTexture;
  81006. }(BABYLON.ProceduralTexture));
  81007. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  81008. })(BABYLON || (BABYLON = {}));
  81009. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  81010. var BABYLON;
  81011. (function (BABYLON) {
  81012. /**
  81013. * Manage the gamepad inputs to control a free camera.
  81014. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81015. */
  81016. var FreeCameraGamepadInput = /** @class */ (function () {
  81017. function FreeCameraGamepadInput() {
  81018. /**
  81019. * Defines the gamepad rotation sensiblity.
  81020. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81021. */
  81022. this.gamepadAngularSensibility = 200;
  81023. /**
  81024. * Defines the gamepad move sensiblity.
  81025. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81026. */
  81027. this.gamepadMoveSensibility = 40;
  81028. this._cameraTransform = BABYLON.Matrix.Identity();
  81029. this._deltaTransform = BABYLON.Vector3.Zero();
  81030. this._vector3 = BABYLON.Vector3.Zero();
  81031. this._vector2 = BABYLON.Vector2.Zero();
  81032. }
  81033. /**
  81034. * Attach the input controls to a specific dom element to get the input from.
  81035. * @param element Defines the element the controls should be listened from
  81036. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81037. */
  81038. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81039. var _this = this;
  81040. var manager = this.camera.getScene().gamepadManager;
  81041. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81042. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81043. // prioritize XBOX gamepads.
  81044. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81045. _this.gamepad = gamepad;
  81046. }
  81047. }
  81048. });
  81049. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81050. if (_this.gamepad === gamepad) {
  81051. _this.gamepad = null;
  81052. }
  81053. });
  81054. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81055. };
  81056. /**
  81057. * Detach the current controls from the specified dom element.
  81058. * @param element Defines the element to stop listening the inputs from
  81059. */
  81060. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  81061. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81062. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81063. this.gamepad = null;
  81064. };
  81065. /**
  81066. * Update the current camera state depending on the inputs that have been used this frame.
  81067. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81068. */
  81069. FreeCameraGamepadInput.prototype.checkInputs = function () {
  81070. if (this.gamepad && this.gamepad.leftStick) {
  81071. var camera = this.camera;
  81072. var LSValues = this.gamepad.leftStick;
  81073. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  81074. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81075. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  81076. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  81077. var RSValues = this.gamepad.rightStick;
  81078. if (RSValues) {
  81079. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  81080. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  81081. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  81082. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  81083. }
  81084. else {
  81085. RSValues = { x: 0, y: 0 };
  81086. }
  81087. if (!camera.rotationQuaternion) {
  81088. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  81089. }
  81090. else {
  81091. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  81092. }
  81093. var speed = camera._computeLocalCameraSpeed() * 50.0;
  81094. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  81095. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  81096. camera.cameraDirection.addInPlace(this._deltaTransform);
  81097. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  81098. camera.cameraRotation.addInPlace(this._vector2);
  81099. }
  81100. };
  81101. /**
  81102. * Gets the class name of the current intput.
  81103. * @returns the class name
  81104. */
  81105. FreeCameraGamepadInput.prototype.getClassName = function () {
  81106. return "FreeCameraGamepadInput";
  81107. };
  81108. /**
  81109. * Get the friendly name associated with the input class.
  81110. * @returns the input friendly name
  81111. */
  81112. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  81113. return "gamepad";
  81114. };
  81115. __decorate([
  81116. BABYLON.serialize()
  81117. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  81118. __decorate([
  81119. BABYLON.serialize()
  81120. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81121. return FreeCameraGamepadInput;
  81122. }());
  81123. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  81124. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  81125. })(BABYLON || (BABYLON = {}));
  81126. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  81127. var BABYLON;
  81128. (function (BABYLON) {
  81129. /**
  81130. * Manage the gamepad inputs to control an arc rotate camera.
  81131. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81132. */
  81133. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  81134. function ArcRotateCameraGamepadInput() {
  81135. /**
  81136. * Defines the gamepad rotation sensiblity.
  81137. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81138. */
  81139. this.gamepadRotationSensibility = 80;
  81140. /**
  81141. * Defines the gamepad move sensiblity.
  81142. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81143. */
  81144. this.gamepadMoveSensibility = 40;
  81145. }
  81146. /**
  81147. * Attach the input controls to a specific dom element to get the input from.
  81148. * @param element Defines the element the controls should be listened from
  81149. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81150. */
  81151. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81152. var _this = this;
  81153. var manager = this.camera.getScene().gamepadManager;
  81154. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81155. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81156. // prioritize XBOX gamepads.
  81157. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81158. _this.gamepad = gamepad;
  81159. }
  81160. }
  81161. });
  81162. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81163. if (_this.gamepad === gamepad) {
  81164. _this.gamepad = null;
  81165. }
  81166. });
  81167. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81168. };
  81169. /**
  81170. * Detach the current controls from the specified dom element.
  81171. * @param element Defines the element to stop listening the inputs from
  81172. */
  81173. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  81174. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81175. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81176. this.gamepad = null;
  81177. };
  81178. /**
  81179. * Update the current camera state depending on the inputs that have been used this frame.
  81180. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81181. */
  81182. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  81183. if (this.gamepad) {
  81184. var camera = this.camera;
  81185. var RSValues = this.gamepad.rightStick;
  81186. if (RSValues) {
  81187. if (RSValues.x != 0) {
  81188. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  81189. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  81190. camera.inertialAlphaOffset += normalizedRX;
  81191. }
  81192. }
  81193. if (RSValues.y != 0) {
  81194. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  81195. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  81196. camera.inertialBetaOffset += normalizedRY;
  81197. }
  81198. }
  81199. }
  81200. var LSValues = this.gamepad.leftStick;
  81201. if (LSValues && LSValues.y != 0) {
  81202. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81203. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  81204. this.camera.inertialRadiusOffset -= normalizedLY;
  81205. }
  81206. }
  81207. }
  81208. };
  81209. /**
  81210. * Gets the class name of the current intput.
  81211. * @returns the class name
  81212. */
  81213. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  81214. return "ArcRotateCameraGamepadInput";
  81215. };
  81216. /**
  81217. * Get the friendly name associated with the input class.
  81218. * @returns the input friendly name
  81219. */
  81220. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  81221. return "gamepad";
  81222. };
  81223. __decorate([
  81224. BABYLON.serialize()
  81225. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  81226. __decorate([
  81227. BABYLON.serialize()
  81228. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81229. return ArcRotateCameraGamepadInput;
  81230. }());
  81231. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  81232. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  81233. })(BABYLON || (BABYLON = {}));
  81234. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  81235. var BABYLON;
  81236. (function (BABYLON) {
  81237. /**
  81238. * Manager for handling gamepads
  81239. */
  81240. var GamepadManager = /** @class */ (function () {
  81241. /**
  81242. * Initializes the gamepad manager
  81243. * @param _scene BabylonJS scene
  81244. */
  81245. function GamepadManager(_scene) {
  81246. var _this = this;
  81247. this._scene = _scene;
  81248. this._babylonGamepads = [];
  81249. this._oneGamepadConnected = false;
  81250. /** @hidden */
  81251. this._isMonitoring = false;
  81252. /**
  81253. * observable to be triggered when the gamepad controller has been disconnected
  81254. */
  81255. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  81256. if (!BABYLON.Tools.IsWindowObjectExist()) {
  81257. this._gamepadEventSupported = false;
  81258. }
  81259. else {
  81260. this._gamepadEventSupported = 'GamepadEvent' in window;
  81261. this._gamepadSupport = (navigator.getGamepads ||
  81262. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  81263. }
  81264. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  81265. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  81266. for (var i in _this._babylonGamepads) {
  81267. var gamepad = _this._babylonGamepads[i];
  81268. if (gamepad && gamepad._isConnected) {
  81269. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  81270. }
  81271. }
  81272. });
  81273. this._onGamepadConnectedEvent = function (evt) {
  81274. var gamepad = evt.gamepad;
  81275. if (gamepad.index in _this._babylonGamepads) {
  81276. if (_this._babylonGamepads[gamepad.index].isConnected) {
  81277. return;
  81278. }
  81279. }
  81280. var newGamepad;
  81281. if (_this._babylonGamepads[gamepad.index]) {
  81282. newGamepad = _this._babylonGamepads[gamepad.index];
  81283. newGamepad.browserGamepad = gamepad;
  81284. newGamepad._isConnected = true;
  81285. }
  81286. else {
  81287. newGamepad = _this._addNewGamepad(gamepad);
  81288. }
  81289. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81290. _this._startMonitoringGamepads();
  81291. };
  81292. this._onGamepadDisconnectedEvent = function (evt) {
  81293. var gamepad = evt.gamepad;
  81294. // Remove the gamepad from the list of gamepads to monitor.
  81295. for (var i in _this._babylonGamepads) {
  81296. if (_this._babylonGamepads[i].index === gamepad.index) {
  81297. var disconnectedGamepad = _this._babylonGamepads[i];
  81298. disconnectedGamepad._isConnected = false;
  81299. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  81300. break;
  81301. }
  81302. }
  81303. };
  81304. if (this._gamepadSupport) {
  81305. //first add already-connected gamepads
  81306. this._updateGamepadObjects();
  81307. if (this._babylonGamepads.length) {
  81308. this._startMonitoringGamepads();
  81309. }
  81310. // Checking if the gamepad connected event is supported (like in Firefox)
  81311. if (this._gamepadEventSupported) {
  81312. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  81313. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  81314. }
  81315. else {
  81316. this._startMonitoringGamepads();
  81317. }
  81318. }
  81319. }
  81320. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  81321. /**
  81322. * The gamepads in the game pad manager
  81323. */
  81324. get: function () {
  81325. return this._babylonGamepads;
  81326. },
  81327. enumerable: true,
  81328. configurable: true
  81329. });
  81330. /**
  81331. * Get the gamepad controllers based on type
  81332. * @param type The type of gamepad controller
  81333. * @returns Nullable gamepad
  81334. */
  81335. GamepadManager.prototype.getGamepadByType = function (type) {
  81336. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  81337. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  81338. var gamepad = _a[_i];
  81339. if (gamepad && gamepad.type === type) {
  81340. return gamepad;
  81341. }
  81342. }
  81343. return null;
  81344. };
  81345. /**
  81346. * Disposes the gamepad manager
  81347. */
  81348. GamepadManager.prototype.dispose = function () {
  81349. if (this._gamepadEventSupported) {
  81350. if (this._onGamepadConnectedEvent) {
  81351. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  81352. }
  81353. if (this._onGamepadDisconnectedEvent) {
  81354. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  81355. }
  81356. this._onGamepadConnectedEvent = null;
  81357. this._onGamepadDisconnectedEvent = null;
  81358. }
  81359. this._babylonGamepads.forEach(function (gamepad) {
  81360. gamepad.dispose();
  81361. });
  81362. this.onGamepadConnectedObservable.clear();
  81363. this.onGamepadDisconnectedObservable.clear();
  81364. this._oneGamepadConnected = false;
  81365. this._stopMonitoringGamepads();
  81366. this._babylonGamepads = [];
  81367. };
  81368. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  81369. if (!this._oneGamepadConnected) {
  81370. this._oneGamepadConnected = true;
  81371. }
  81372. var newGamepad;
  81373. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  81374. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  81375. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  81376. }
  81377. // if pose is supported, use the (WebVR) pose enabled controller
  81378. else if (gamepad.pose) {
  81379. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  81380. }
  81381. else {
  81382. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  81383. }
  81384. this._babylonGamepads[newGamepad.index] = newGamepad;
  81385. return newGamepad;
  81386. };
  81387. GamepadManager.prototype._startMonitoringGamepads = function () {
  81388. if (!this._isMonitoring) {
  81389. this._isMonitoring = true;
  81390. //back-comp
  81391. if (!this._scene) {
  81392. this._checkGamepadsStatus();
  81393. }
  81394. }
  81395. };
  81396. GamepadManager.prototype._stopMonitoringGamepads = function () {
  81397. this._isMonitoring = false;
  81398. };
  81399. /** @hidden */
  81400. GamepadManager.prototype._checkGamepadsStatus = function () {
  81401. var _this = this;
  81402. // Hack to be compatible Chrome
  81403. this._updateGamepadObjects();
  81404. for (var i in this._babylonGamepads) {
  81405. var gamepad = this._babylonGamepads[i];
  81406. if (!gamepad || !gamepad.isConnected) {
  81407. continue;
  81408. }
  81409. gamepad.update();
  81410. }
  81411. if (this._isMonitoring && !this._scene) {
  81412. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  81413. }
  81414. };
  81415. // This function is called only on Chrome, which does not properly support
  81416. // connection/disconnection events and forces you to recopy again the gamepad object
  81417. GamepadManager.prototype._updateGamepadObjects = function () {
  81418. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  81419. for (var i = 0; i < gamepads.length; i++) {
  81420. var gamepad = gamepads[i];
  81421. if (gamepad) {
  81422. if (!this._babylonGamepads[gamepad.index]) {
  81423. var newGamepad = this._addNewGamepad(gamepad);
  81424. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81425. }
  81426. else {
  81427. // Forced to copy again this object for Chrome for unknown reason
  81428. this._babylonGamepads[i].browserGamepad = gamepad;
  81429. if (!this._babylonGamepads[i].isConnected) {
  81430. this._babylonGamepads[i]._isConnected = true;
  81431. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  81432. }
  81433. }
  81434. }
  81435. }
  81436. };
  81437. return GamepadManager;
  81438. }());
  81439. BABYLON.GamepadManager = GamepadManager;
  81440. })(BABYLON || (BABYLON = {}));
  81441. //# sourceMappingURL=babylon.gamepadManager.js.map
  81442. var BABYLON;
  81443. (function (BABYLON) {
  81444. /**
  81445. * Represents a gamepad control stick position
  81446. */
  81447. var StickValues = /** @class */ (function () {
  81448. /**
  81449. * Initializes the gamepad x and y control stick values
  81450. * @param x The x component of the gamepad control stick value
  81451. * @param y The y component of the gamepad control stick value
  81452. */
  81453. function StickValues(
  81454. /**
  81455. * The x component of the control stick
  81456. */
  81457. x,
  81458. /**
  81459. * The y component of the control stick
  81460. */
  81461. y) {
  81462. this.x = x;
  81463. this.y = y;
  81464. }
  81465. return StickValues;
  81466. }());
  81467. BABYLON.StickValues = StickValues;
  81468. /**
  81469. * Represents a gamepad
  81470. */
  81471. var Gamepad = /** @class */ (function () {
  81472. /**
  81473. * Initializes the gamepad
  81474. * @param id The id of the gamepad
  81475. * @param index The index of the gamepad
  81476. * @param browserGamepad The browser gamepad
  81477. * @param leftStickX The x component of the left joystick
  81478. * @param leftStickY The y component of the left joystick
  81479. * @param rightStickX The x component of the right joystick
  81480. * @param rightStickY The y component of the right joystick
  81481. */
  81482. function Gamepad(
  81483. /**
  81484. * The id of the gamepad
  81485. */
  81486. id,
  81487. /**
  81488. * The index of the gamepad
  81489. */
  81490. index,
  81491. /**
  81492. * The browser gamepad
  81493. */
  81494. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  81495. if (leftStickX === void 0) { leftStickX = 0; }
  81496. if (leftStickY === void 0) { leftStickY = 1; }
  81497. if (rightStickX === void 0) { rightStickX = 2; }
  81498. if (rightStickY === void 0) { rightStickY = 3; }
  81499. this.id = id;
  81500. this.index = index;
  81501. this.browserGamepad = browserGamepad;
  81502. this._leftStick = { x: 0, y: 0 };
  81503. this._rightStick = { x: 0, y: 0 };
  81504. /** @hidden */
  81505. this._isConnected = true;
  81506. /**
  81507. * Specifies whether the left control stick should be Y-inverted
  81508. */
  81509. this._invertLeftStickY = false;
  81510. this.type = Gamepad.GAMEPAD;
  81511. this._leftStickAxisX = leftStickX;
  81512. this._leftStickAxisY = leftStickY;
  81513. this._rightStickAxisX = rightStickX;
  81514. this._rightStickAxisY = rightStickY;
  81515. if (this.browserGamepad.axes.length >= 2) {
  81516. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81517. }
  81518. if (this.browserGamepad.axes.length >= 4) {
  81519. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81520. }
  81521. }
  81522. Object.defineProperty(Gamepad.prototype, "isConnected", {
  81523. /**
  81524. * Specifies if the gamepad has been connected
  81525. */
  81526. get: function () {
  81527. return this._isConnected;
  81528. },
  81529. enumerable: true,
  81530. configurable: true
  81531. });
  81532. /**
  81533. * Callback triggered when the left joystick has changed
  81534. * @param callback
  81535. */
  81536. Gamepad.prototype.onleftstickchanged = function (callback) {
  81537. this._onleftstickchanged = callback;
  81538. };
  81539. /**
  81540. * Callback triggered when the right joystick has changed
  81541. * @param callback
  81542. */
  81543. Gamepad.prototype.onrightstickchanged = function (callback) {
  81544. this._onrightstickchanged = callback;
  81545. };
  81546. Object.defineProperty(Gamepad.prototype, "leftStick", {
  81547. /**
  81548. * Gets the left joystick
  81549. */
  81550. get: function () {
  81551. return this._leftStick;
  81552. },
  81553. /**
  81554. * Sets the left joystick values
  81555. */
  81556. set: function (newValues) {
  81557. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  81558. this._onleftstickchanged(newValues);
  81559. }
  81560. this._leftStick = newValues;
  81561. },
  81562. enumerable: true,
  81563. configurable: true
  81564. });
  81565. Object.defineProperty(Gamepad.prototype, "rightStick", {
  81566. /**
  81567. * Gets the right joystick
  81568. */
  81569. get: function () {
  81570. return this._rightStick;
  81571. },
  81572. /**
  81573. * Sets the right joystick value
  81574. */
  81575. set: function (newValues) {
  81576. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  81577. this._onrightstickchanged(newValues);
  81578. }
  81579. this._rightStick = newValues;
  81580. },
  81581. enumerable: true,
  81582. configurable: true
  81583. });
  81584. /**
  81585. * Updates the gamepad joystick positions
  81586. */
  81587. Gamepad.prototype.update = function () {
  81588. if (this._leftStick) {
  81589. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81590. if (this._invertLeftStickY) {
  81591. this.leftStick.y *= -1;
  81592. }
  81593. }
  81594. if (this._rightStick) {
  81595. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81596. }
  81597. };
  81598. /**
  81599. * Disposes the gamepad
  81600. */
  81601. Gamepad.prototype.dispose = function () {
  81602. };
  81603. /**
  81604. * Represents a gamepad controller
  81605. */
  81606. Gamepad.GAMEPAD = 0;
  81607. /**
  81608. * Represents a generic controller
  81609. */
  81610. Gamepad.GENERIC = 1;
  81611. /**
  81612. * Represents an XBox controller
  81613. */
  81614. Gamepad.XBOX = 2;
  81615. /**
  81616. * Represents a pose-enabled controller
  81617. */
  81618. Gamepad.POSE_ENABLED = 3;
  81619. return Gamepad;
  81620. }());
  81621. BABYLON.Gamepad = Gamepad;
  81622. /**
  81623. * Represents a generic gamepad
  81624. */
  81625. var GenericPad = /** @class */ (function (_super) {
  81626. __extends(GenericPad, _super);
  81627. /**
  81628. * Initializes the generic gamepad
  81629. * @param id The id of the generic gamepad
  81630. * @param index The index of the generic gamepad
  81631. * @param browserGamepad The browser gamepad
  81632. */
  81633. function GenericPad(id, index, browserGamepad) {
  81634. var _this = _super.call(this, id, index, browserGamepad) || this;
  81635. /**
  81636. * Observable triggered when a button has been pressed
  81637. */
  81638. _this.onButtonDownObservable = new BABYLON.Observable();
  81639. /**
  81640. * Observable triggered when a button has been released
  81641. */
  81642. _this.onButtonUpObservable = new BABYLON.Observable();
  81643. _this.type = Gamepad.GENERIC;
  81644. _this._buttons = new Array(browserGamepad.buttons.length);
  81645. return _this;
  81646. }
  81647. /**
  81648. * Callback triggered when a button has been pressed
  81649. * @param callback Called when a button has been pressed
  81650. */
  81651. GenericPad.prototype.onbuttondown = function (callback) {
  81652. this._onbuttondown = callback;
  81653. };
  81654. /**
  81655. * Callback triggered when a button has been released
  81656. * @param callback Called when a button has been released
  81657. */
  81658. GenericPad.prototype.onbuttonup = function (callback) {
  81659. this._onbuttonup = callback;
  81660. };
  81661. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  81662. if (newValue !== currentValue) {
  81663. if (newValue === 1) {
  81664. if (this._onbuttondown) {
  81665. this._onbuttondown(buttonIndex);
  81666. }
  81667. this.onButtonDownObservable.notifyObservers(buttonIndex);
  81668. }
  81669. if (newValue === 0) {
  81670. if (this._onbuttonup) {
  81671. this._onbuttonup(buttonIndex);
  81672. }
  81673. this.onButtonUpObservable.notifyObservers(buttonIndex);
  81674. }
  81675. }
  81676. return newValue;
  81677. };
  81678. /**
  81679. * Updates the generic gamepad
  81680. */
  81681. GenericPad.prototype.update = function () {
  81682. _super.prototype.update.call(this);
  81683. for (var index = 0; index < this._buttons.length; index++) {
  81684. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  81685. }
  81686. };
  81687. /**
  81688. * Disposes the generic gamepad
  81689. */
  81690. GenericPad.prototype.dispose = function () {
  81691. _super.prototype.dispose.call(this);
  81692. this.onButtonDownObservable.clear();
  81693. this.onButtonUpObservable.clear();
  81694. };
  81695. return GenericPad;
  81696. }(Gamepad));
  81697. BABYLON.GenericPad = GenericPad;
  81698. })(BABYLON || (BABYLON = {}));
  81699. //# sourceMappingURL=babylon.gamepad.js.map
  81700. var BABYLON;
  81701. (function (BABYLON) {
  81702. /**
  81703. * Defines supported buttons for XBox360 compatible gamepads
  81704. */
  81705. var Xbox360Button;
  81706. (function (Xbox360Button) {
  81707. /** A */
  81708. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  81709. /** B */
  81710. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  81711. /** X */
  81712. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  81713. /** Y */
  81714. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  81715. /** Start */
  81716. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  81717. /** Back */
  81718. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  81719. /** Left button */
  81720. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  81721. /** Right button */
  81722. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  81723. /** Left stick */
  81724. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  81725. /** Right stick */
  81726. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  81727. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  81728. /** Defines values for XBox360 DPad */
  81729. var Xbox360Dpad;
  81730. (function (Xbox360Dpad) {
  81731. /** Up */
  81732. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  81733. /** Down */
  81734. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  81735. /** Left */
  81736. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  81737. /** Right */
  81738. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  81739. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  81740. /**
  81741. * Defines a XBox360 gamepad
  81742. */
  81743. var Xbox360Pad = /** @class */ (function (_super) {
  81744. __extends(Xbox360Pad, _super);
  81745. /**
  81746. * Creates a new XBox360 gamepad object
  81747. * @param id defines the id of this gamepad
  81748. * @param index defines its index
  81749. * @param gamepad defines the internal HTML gamepad object
  81750. * @param xboxOne defines if it is a XBox One gamepad
  81751. */
  81752. function Xbox360Pad(id, index, gamepad, xboxOne) {
  81753. if (xboxOne === void 0) { xboxOne = false; }
  81754. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  81755. _this._leftTrigger = 0;
  81756. _this._rightTrigger = 0;
  81757. /** Observable raised when a button is pressed */
  81758. _this.onButtonDownObservable = new BABYLON.Observable();
  81759. /** Observable raised when a button is released */
  81760. _this.onButtonUpObservable = new BABYLON.Observable();
  81761. /** Observable raised when a pad is pressed */
  81762. _this.onPadDownObservable = new BABYLON.Observable();
  81763. /** Observable raised when a pad is released */
  81764. _this.onPadUpObservable = new BABYLON.Observable();
  81765. _this._buttonA = 0;
  81766. _this._buttonB = 0;
  81767. _this._buttonX = 0;
  81768. _this._buttonY = 0;
  81769. _this._buttonBack = 0;
  81770. _this._buttonStart = 0;
  81771. _this._buttonLB = 0;
  81772. _this._buttonRB = 0;
  81773. _this._buttonLeftStick = 0;
  81774. _this._buttonRightStick = 0;
  81775. _this._dPadUp = 0;
  81776. _this._dPadDown = 0;
  81777. _this._dPadLeft = 0;
  81778. _this._dPadRight = 0;
  81779. _this._isXboxOnePad = false;
  81780. _this.type = BABYLON.Gamepad.XBOX;
  81781. _this._isXboxOnePad = xboxOne;
  81782. return _this;
  81783. }
  81784. /**
  81785. * Defines the callback to call when left trigger is pressed
  81786. * @param callback defines the callback to use
  81787. */
  81788. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  81789. this._onlefttriggerchanged = callback;
  81790. };
  81791. /**
  81792. * Defines the callback to call when right trigger is pressed
  81793. * @param callback defines the callback to use
  81794. */
  81795. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  81796. this._onrighttriggerchanged = callback;
  81797. };
  81798. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  81799. /**
  81800. * Gets the left trigger value
  81801. */
  81802. get: function () {
  81803. return this._leftTrigger;
  81804. },
  81805. /**
  81806. * Sets the left trigger value
  81807. */
  81808. set: function (newValue) {
  81809. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  81810. this._onlefttriggerchanged(newValue);
  81811. }
  81812. this._leftTrigger = newValue;
  81813. },
  81814. enumerable: true,
  81815. configurable: true
  81816. });
  81817. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  81818. /**
  81819. * Gets the right trigger value
  81820. */
  81821. get: function () {
  81822. return this._rightTrigger;
  81823. },
  81824. /**
  81825. * Sets the right trigger value
  81826. */
  81827. set: function (newValue) {
  81828. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  81829. this._onrighttriggerchanged(newValue);
  81830. }
  81831. this._rightTrigger = newValue;
  81832. },
  81833. enumerable: true,
  81834. configurable: true
  81835. });
  81836. /**
  81837. * Defines the callback to call when a button is pressed
  81838. * @param callback defines the callback to use
  81839. */
  81840. Xbox360Pad.prototype.onbuttondown = function (callback) {
  81841. this._onbuttondown = callback;
  81842. };
  81843. /**
  81844. * Defines the callback to call when a button is released
  81845. * @param callback defines the callback to use
  81846. */
  81847. Xbox360Pad.prototype.onbuttonup = function (callback) {
  81848. this._onbuttonup = callback;
  81849. };
  81850. /**
  81851. * Defines the callback to call when a pad is pressed
  81852. * @param callback defines the callback to use
  81853. */
  81854. Xbox360Pad.prototype.ondpaddown = function (callback) {
  81855. this._ondpaddown = callback;
  81856. };
  81857. /**
  81858. * Defines the callback to call when a pad is released
  81859. * @param callback defines the callback to use
  81860. */
  81861. Xbox360Pad.prototype.ondpadup = function (callback) {
  81862. this._ondpadup = callback;
  81863. };
  81864. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  81865. if (newValue !== currentValue) {
  81866. if (newValue === 1) {
  81867. if (this._onbuttondown) {
  81868. this._onbuttondown(buttonType);
  81869. }
  81870. this.onButtonDownObservable.notifyObservers(buttonType);
  81871. }
  81872. if (newValue === 0) {
  81873. if (this._onbuttonup) {
  81874. this._onbuttonup(buttonType);
  81875. }
  81876. this.onButtonUpObservable.notifyObservers(buttonType);
  81877. }
  81878. }
  81879. return newValue;
  81880. };
  81881. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  81882. if (newValue !== currentValue) {
  81883. if (newValue === 1) {
  81884. if (this._ondpaddown) {
  81885. this._ondpaddown(buttonType);
  81886. }
  81887. this.onPadDownObservable.notifyObservers(buttonType);
  81888. }
  81889. if (newValue === 0) {
  81890. if (this._ondpadup) {
  81891. this._ondpadup(buttonType);
  81892. }
  81893. this.onPadUpObservable.notifyObservers(buttonType);
  81894. }
  81895. }
  81896. return newValue;
  81897. };
  81898. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  81899. /**
  81900. * Gets the value of the `A` button
  81901. */
  81902. get: function () {
  81903. return this._buttonA;
  81904. },
  81905. /**
  81906. * Sets the value of the `A` button
  81907. */
  81908. set: function (value) {
  81909. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  81910. },
  81911. enumerable: true,
  81912. configurable: true
  81913. });
  81914. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  81915. /**
  81916. * Gets the value of the `B` button
  81917. */
  81918. get: function () {
  81919. return this._buttonB;
  81920. },
  81921. /**
  81922. * Sets the value of the `B` button
  81923. */
  81924. set: function (value) {
  81925. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  81926. },
  81927. enumerable: true,
  81928. configurable: true
  81929. });
  81930. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  81931. /**
  81932. * Gets the value of the `X` button
  81933. */
  81934. get: function () {
  81935. return this._buttonX;
  81936. },
  81937. /**
  81938. * Sets the value of the `X` button
  81939. */
  81940. set: function (value) {
  81941. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  81942. },
  81943. enumerable: true,
  81944. configurable: true
  81945. });
  81946. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  81947. /**
  81948. * Gets the value of the `Y` button
  81949. */
  81950. get: function () {
  81951. return this._buttonY;
  81952. },
  81953. /**
  81954. * Sets the value of the `Y` button
  81955. */
  81956. set: function (value) {
  81957. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  81958. },
  81959. enumerable: true,
  81960. configurable: true
  81961. });
  81962. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  81963. /**
  81964. * Gets the value of the `Start` button
  81965. */
  81966. get: function () {
  81967. return this._buttonStart;
  81968. },
  81969. /**
  81970. * Sets the value of the `Start` button
  81971. */
  81972. set: function (value) {
  81973. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  81974. },
  81975. enumerable: true,
  81976. configurable: true
  81977. });
  81978. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  81979. /**
  81980. * Gets the value of the `Back` button
  81981. */
  81982. get: function () {
  81983. return this._buttonBack;
  81984. },
  81985. /**
  81986. * Sets the value of the `Back` button
  81987. */
  81988. set: function (value) {
  81989. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  81990. },
  81991. enumerable: true,
  81992. configurable: true
  81993. });
  81994. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  81995. /**
  81996. * Gets the value of the `Left` button
  81997. */
  81998. get: function () {
  81999. return this._buttonLB;
  82000. },
  82001. /**
  82002. * Sets the value of the `Left` button
  82003. */
  82004. set: function (value) {
  82005. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  82006. },
  82007. enumerable: true,
  82008. configurable: true
  82009. });
  82010. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  82011. /**
  82012. * Gets the value of the `Right` button
  82013. */
  82014. get: function () {
  82015. return this._buttonRB;
  82016. },
  82017. /**
  82018. * Sets the value of the `Right` button
  82019. */
  82020. set: function (value) {
  82021. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  82022. },
  82023. enumerable: true,
  82024. configurable: true
  82025. });
  82026. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  82027. /**
  82028. * Gets the value of the Left joystick
  82029. */
  82030. get: function () {
  82031. return this._buttonLeftStick;
  82032. },
  82033. /**
  82034. * Sets the value of the Left joystick
  82035. */
  82036. set: function (value) {
  82037. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  82038. },
  82039. enumerable: true,
  82040. configurable: true
  82041. });
  82042. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  82043. /**
  82044. * Gets the value of the Right joystick
  82045. */
  82046. get: function () {
  82047. return this._buttonRightStick;
  82048. },
  82049. /**
  82050. * Sets the value of the Right joystick
  82051. */
  82052. set: function (value) {
  82053. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  82054. },
  82055. enumerable: true,
  82056. configurable: true
  82057. });
  82058. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  82059. /**
  82060. * Gets the value of D-pad up
  82061. */
  82062. get: function () {
  82063. return this._dPadUp;
  82064. },
  82065. /**
  82066. * Sets the value of D-pad up
  82067. */
  82068. set: function (value) {
  82069. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  82070. },
  82071. enumerable: true,
  82072. configurable: true
  82073. });
  82074. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  82075. /**
  82076. * Gets the value of D-pad down
  82077. */
  82078. get: function () {
  82079. return this._dPadDown;
  82080. },
  82081. /**
  82082. * Sets the value of D-pad down
  82083. */
  82084. set: function (value) {
  82085. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  82086. },
  82087. enumerable: true,
  82088. configurable: true
  82089. });
  82090. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  82091. /**
  82092. * Gets the value of D-pad left
  82093. */
  82094. get: function () {
  82095. return this._dPadLeft;
  82096. },
  82097. /**
  82098. * Sets the value of D-pad left
  82099. */
  82100. set: function (value) {
  82101. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  82102. },
  82103. enumerable: true,
  82104. configurable: true
  82105. });
  82106. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  82107. /**
  82108. * Gets the value of D-pad right
  82109. */
  82110. get: function () {
  82111. return this._dPadRight;
  82112. },
  82113. /**
  82114. * Sets the value of D-pad right
  82115. */
  82116. set: function (value) {
  82117. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  82118. },
  82119. enumerable: true,
  82120. configurable: true
  82121. });
  82122. /**
  82123. * Force the gamepad to synchronize with device values
  82124. */
  82125. Xbox360Pad.prototype.update = function () {
  82126. _super.prototype.update.call(this);
  82127. if (this._isXboxOnePad) {
  82128. this.buttonA = this.browserGamepad.buttons[0].value;
  82129. this.buttonB = this.browserGamepad.buttons[1].value;
  82130. this.buttonX = this.browserGamepad.buttons[2].value;
  82131. this.buttonY = this.browserGamepad.buttons[3].value;
  82132. this.buttonLB = this.browserGamepad.buttons[4].value;
  82133. this.buttonRB = this.browserGamepad.buttons[5].value;
  82134. this.leftTrigger = this.browserGamepad.axes[2];
  82135. this.rightTrigger = this.browserGamepad.axes[5];
  82136. this.buttonBack = this.browserGamepad.buttons[9].value;
  82137. this.buttonStart = this.browserGamepad.buttons[8].value;
  82138. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  82139. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  82140. this.dPadUp = this.browserGamepad.buttons[11].value;
  82141. this.dPadDown = this.browserGamepad.buttons[12].value;
  82142. this.dPadLeft = this.browserGamepad.buttons[13].value;
  82143. this.dPadRight = this.browserGamepad.buttons[14].value;
  82144. }
  82145. else {
  82146. this.buttonA = this.browserGamepad.buttons[0].value;
  82147. this.buttonB = this.browserGamepad.buttons[1].value;
  82148. this.buttonX = this.browserGamepad.buttons[2].value;
  82149. this.buttonY = this.browserGamepad.buttons[3].value;
  82150. this.buttonLB = this.browserGamepad.buttons[4].value;
  82151. this.buttonRB = this.browserGamepad.buttons[5].value;
  82152. this.leftTrigger = this.browserGamepad.buttons[6].value;
  82153. this.rightTrigger = this.browserGamepad.buttons[7].value;
  82154. this.buttonBack = this.browserGamepad.buttons[8].value;
  82155. this.buttonStart = this.browserGamepad.buttons[9].value;
  82156. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  82157. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  82158. this.dPadUp = this.browserGamepad.buttons[12].value;
  82159. this.dPadDown = this.browserGamepad.buttons[13].value;
  82160. this.dPadLeft = this.browserGamepad.buttons[14].value;
  82161. this.dPadRight = this.browserGamepad.buttons[15].value;
  82162. }
  82163. };
  82164. /**
  82165. * Disposes the gamepad
  82166. */
  82167. Xbox360Pad.prototype.dispose = function () {
  82168. _super.prototype.dispose.call(this);
  82169. this.onButtonDownObservable.clear();
  82170. this.onButtonUpObservable.clear();
  82171. this.onPadDownObservable.clear();
  82172. this.onPadUpObservable.clear();
  82173. };
  82174. return Xbox360Pad;
  82175. }(BABYLON.Gamepad));
  82176. BABYLON.Xbox360Pad = Xbox360Pad;
  82177. })(BABYLON || (BABYLON = {}));
  82178. //# sourceMappingURL=babylon.xboxGamepad.js.map
  82179. var BABYLON;
  82180. (function (BABYLON) {
  82181. /**
  82182. * Defines the types of pose enabled controllers that are supported
  82183. */
  82184. var PoseEnabledControllerType;
  82185. (function (PoseEnabledControllerType) {
  82186. /**
  82187. * HTC Vive
  82188. */
  82189. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  82190. /**
  82191. * Oculus Rift
  82192. */
  82193. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  82194. /**
  82195. * Windows mixed reality
  82196. */
  82197. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  82198. /**
  82199. * Samsung gear VR
  82200. */
  82201. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  82202. /**
  82203. * Google Daydream
  82204. */
  82205. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  82206. /**
  82207. * Generic
  82208. */
  82209. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  82210. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  82211. /**
  82212. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82213. */
  82214. var PoseEnabledControllerHelper = /** @class */ (function () {
  82215. function PoseEnabledControllerHelper() {
  82216. }
  82217. /**
  82218. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82219. * @param vrGamepad the gamepad to initialized
  82220. * @returns a vr controller of the type the gamepad identified as
  82221. */
  82222. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  82223. // Oculus Touch
  82224. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  82225. return new BABYLON.OculusTouchController(vrGamepad);
  82226. }
  82227. // Windows Mixed Reality controllers
  82228. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  82229. return new BABYLON.WindowsMotionController(vrGamepad);
  82230. }
  82231. // HTC Vive
  82232. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  82233. return new BABYLON.ViveController(vrGamepad);
  82234. }
  82235. // Samsung/Oculus Gear VR or Oculus Go
  82236. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  82237. return new BABYLON.GearVRController(vrGamepad);
  82238. }
  82239. // Google Daydream
  82240. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  82241. return new BABYLON.DaydreamController(vrGamepad);
  82242. }
  82243. // Generic
  82244. else {
  82245. return new BABYLON.GenericController(vrGamepad);
  82246. }
  82247. };
  82248. return PoseEnabledControllerHelper;
  82249. }());
  82250. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  82251. /**
  82252. * Defines the PoseEnabledController object that contains state of a vr capable controller
  82253. */
  82254. var PoseEnabledController = /** @class */ (function (_super) {
  82255. __extends(PoseEnabledController, _super);
  82256. /**
  82257. * Creates a new PoseEnabledController from a gamepad
  82258. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  82259. */
  82260. function PoseEnabledController(browserGamepad) {
  82261. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  82262. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82263. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82264. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  82265. /**
  82266. * The device position in babylon space
  82267. */
  82268. _this.devicePosition = BABYLON.Vector3.Zero();
  82269. /**
  82270. * The device rotation in babylon space
  82271. */
  82272. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  82273. /**
  82274. * The scale factor of the device in babylon space
  82275. */
  82276. _this.deviceScaleFactor = 1;
  82277. // Used to convert 6dof controllers to 3dof
  82278. _this._trackPosition = true;
  82279. _this._maxRotationDistFromHeadset = Math.PI / 5;
  82280. _this._draggedRoomRotation = 0;
  82281. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  82282. /**
  82283. * Internal, matrix used to convert room space to babylon space
  82284. * @hidden
  82285. */
  82286. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82287. /**
  82288. * Node to be used when casting a ray from the controller
  82289. * @hidden
  82290. */
  82291. _this._pointingPoseNode = null;
  82292. _this._workingMatrix = BABYLON.Matrix.Identity();
  82293. /**
  82294. * @hidden
  82295. */
  82296. _this._meshAttachedObservable = new BABYLON.Observable();
  82297. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  82298. _this.controllerType = PoseEnabledControllerType.GENERIC;
  82299. _this.position = BABYLON.Vector3.Zero();
  82300. _this.rotationQuaternion = new BABYLON.Quaternion();
  82301. _this._calculatedPosition = BABYLON.Vector3.Zero();
  82302. _this._calculatedRotation = new BABYLON.Quaternion();
  82303. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  82304. return _this;
  82305. }
  82306. /**
  82307. * @hidden
  82308. */
  82309. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  82310. if (this._trackPosition) {
  82311. this._calculatedPosition.copyFrom(fixedPosition);
  82312. this._trackPosition = false;
  82313. }
  82314. };
  82315. /**
  82316. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  82317. */
  82318. PoseEnabledController.prototype.update = function () {
  82319. _super.prototype.update.call(this);
  82320. this._updatePoseAndMesh();
  82321. };
  82322. /**
  82323. * Updates only the pose device and mesh without doing any button event checking
  82324. */
  82325. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  82326. var pose = this.browserGamepad.pose;
  82327. this.updateFromDevice(pose);
  82328. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  82329. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  82330. camera._computeDevicePosition();
  82331. this._deviceToWorld.setTranslation(camera.devicePosition);
  82332. if (camera.deviceRotationQuaternion) {
  82333. var camera = camera;
  82334. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  82335. // Find the radian distance away that the headset is from the controllers rotation
  82336. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  82337. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  82338. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  82339. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  82340. this._draggedRoomRotation += rotationAmount;
  82341. // Rotate controller around headset
  82342. var sin = Math.sin(-rotationAmount);
  82343. var cos = Math.cos(-rotationAmount);
  82344. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  82345. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  82346. }
  82347. }
  82348. }
  82349. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  82350. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  82351. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82352. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  82353. if (this._mesh) {
  82354. this._mesh.position.copyFrom(this.devicePosition);
  82355. if (this._mesh.rotationQuaternion) {
  82356. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  82357. }
  82358. }
  82359. };
  82360. /**
  82361. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  82362. * @param poseData raw pose fromthe device
  82363. */
  82364. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  82365. if (poseData) {
  82366. this.rawPose = poseData;
  82367. if (poseData.position) {
  82368. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  82369. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  82370. this._deviceRoomPosition.z *= -1;
  82371. }
  82372. if (this._trackPosition) {
  82373. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  82374. }
  82375. this._calculatedPosition.addInPlace(this.position);
  82376. }
  82377. var pose = this.rawPose;
  82378. if (poseData.orientation && pose.orientation) {
  82379. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  82380. if (this._mesh) {
  82381. if (this._mesh.getScene().useRightHandedSystem) {
  82382. this._deviceRoomRotationQuaternion.z *= -1;
  82383. this._deviceRoomRotationQuaternion.w *= -1;
  82384. }
  82385. else {
  82386. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  82387. }
  82388. }
  82389. // if the camera is set, rotate to the camera's rotation
  82390. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  82391. }
  82392. }
  82393. };
  82394. /**
  82395. * Attaches a mesh to the controller
  82396. * @param mesh the mesh to be attached
  82397. */
  82398. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  82399. if (this._mesh) {
  82400. this._mesh.parent = null;
  82401. }
  82402. this._mesh = mesh;
  82403. if (this._poseControlledCamera) {
  82404. this._mesh.parent = this._poseControlledCamera;
  82405. }
  82406. if (!this._mesh.rotationQuaternion) {
  82407. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  82408. }
  82409. // 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
  82410. this._updatePoseAndMesh();
  82411. if (this._pointingPoseNode) {
  82412. var parents = [];
  82413. var obj = this._pointingPoseNode;
  82414. while (obj.parent) {
  82415. parents.push(obj.parent);
  82416. obj = obj.parent;
  82417. }
  82418. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  82419. }
  82420. this._meshAttachedObservable.notifyObservers(mesh);
  82421. };
  82422. /**
  82423. * Attaches the controllers mesh to a camera
  82424. * @param camera the camera the mesh should be attached to
  82425. */
  82426. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  82427. this._poseControlledCamera = camera;
  82428. if (this._mesh) {
  82429. this._mesh.parent = this._poseControlledCamera;
  82430. }
  82431. };
  82432. /**
  82433. * Disposes of the controller
  82434. */
  82435. PoseEnabledController.prototype.dispose = function () {
  82436. if (this._mesh) {
  82437. this._mesh.dispose();
  82438. }
  82439. this._mesh = null;
  82440. _super.prototype.dispose.call(this);
  82441. };
  82442. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  82443. /**
  82444. * The mesh that is attached to the controller
  82445. */
  82446. get: function () {
  82447. return this._mesh;
  82448. },
  82449. enumerable: true,
  82450. configurable: true
  82451. });
  82452. /**
  82453. * Gets the ray of the controller in the direction the controller is pointing
  82454. * @param length the length the resulting ray should be
  82455. * @returns a ray in the direction the controller is pointing
  82456. */
  82457. PoseEnabledController.prototype.getForwardRay = function (length) {
  82458. if (length === void 0) { length = 100; }
  82459. if (!this.mesh) {
  82460. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  82461. }
  82462. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  82463. var origin = m.getTranslation();
  82464. var forward = new BABYLON.Vector3(0, 0, -1);
  82465. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82466. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82467. return new BABYLON.Ray(origin, direction, length);
  82468. };
  82469. /**
  82470. * Name of the child mesh that can be used to cast a ray from the controller
  82471. */
  82472. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  82473. return PoseEnabledController;
  82474. }(BABYLON.Gamepad));
  82475. BABYLON.PoseEnabledController = PoseEnabledController;
  82476. })(BABYLON || (BABYLON = {}));
  82477. //# sourceMappingURL=babylon.poseEnabledController.js.map
  82478. var BABYLON;
  82479. (function (BABYLON) {
  82480. /**
  82481. * Defines the WebVRController object that represents controllers tracked in 3D space
  82482. */
  82483. var WebVRController = /** @class */ (function (_super) {
  82484. __extends(WebVRController, _super);
  82485. /**
  82486. * Creates a new WebVRController from a gamepad
  82487. * @param vrGamepad the gamepad that the WebVRController should be created from
  82488. */
  82489. function WebVRController(vrGamepad) {
  82490. var _this = _super.call(this, vrGamepad) || this;
  82491. // Observables
  82492. /**
  82493. * Fired when the trigger state has changed
  82494. */
  82495. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  82496. /**
  82497. * Fired when the main button state has changed
  82498. */
  82499. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  82500. /**
  82501. * Fired when the secondary button state has changed
  82502. */
  82503. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  82504. /**
  82505. * Fired when the pad state has changed
  82506. */
  82507. _this.onPadStateChangedObservable = new BABYLON.Observable();
  82508. /**
  82509. * Fired when controllers stick values have changed
  82510. */
  82511. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  82512. /**
  82513. * X and Y axis corrisponding to the controllers joystick
  82514. */
  82515. _this.pad = { x: 0, y: 0 };
  82516. // avoid GC, store state in a tmp object
  82517. _this._changes = {
  82518. pressChanged: false,
  82519. touchChanged: false,
  82520. valueChanged: false,
  82521. changed: false
  82522. };
  82523. _this._buttons = new Array(vrGamepad.buttons.length);
  82524. _this.hand = vrGamepad.hand;
  82525. return _this;
  82526. }
  82527. /**
  82528. * Fired when a controller button's state has changed
  82529. * @param callback the callback containing the button that was modified
  82530. */
  82531. WebVRController.prototype.onButtonStateChange = function (callback) {
  82532. this._onButtonStateChange = callback;
  82533. };
  82534. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  82535. /**
  82536. * The default controller model for the controller
  82537. */
  82538. get: function () {
  82539. return this._defaultModel;
  82540. },
  82541. enumerable: true,
  82542. configurable: true
  82543. });
  82544. /**
  82545. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  82546. */
  82547. WebVRController.prototype.update = function () {
  82548. _super.prototype.update.call(this);
  82549. for (var index = 0; index < this._buttons.length; index++) {
  82550. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  82551. }
  82552. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  82553. this.pad.x = this.leftStick.x;
  82554. this.pad.y = this.leftStick.y;
  82555. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  82556. }
  82557. };
  82558. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  82559. if (!newState) {
  82560. newState = {
  82561. pressed: false,
  82562. touched: false,
  82563. value: 0
  82564. };
  82565. }
  82566. if (!currentState) {
  82567. this._buttons[buttonIndex] = {
  82568. pressed: newState.pressed,
  82569. touched: newState.touched,
  82570. value: newState.value
  82571. };
  82572. return;
  82573. }
  82574. this._checkChanges(newState, currentState);
  82575. if (this._changes.changed) {
  82576. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  82577. this._handleButtonChange(buttonIndex, newState, this._changes);
  82578. }
  82579. this._buttons[buttonIndex].pressed = newState.pressed;
  82580. this._buttons[buttonIndex].touched = newState.touched;
  82581. // oculus triggers are never 0, thou not touched.
  82582. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  82583. };
  82584. WebVRController.prototype._checkChanges = function (newState, currentState) {
  82585. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  82586. this._changes.touchChanged = newState.touched !== currentState.touched;
  82587. this._changes.valueChanged = newState.value !== currentState.value;
  82588. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  82589. return this._changes;
  82590. };
  82591. /**
  82592. * Disposes of th webVRCOntroller
  82593. */
  82594. WebVRController.prototype.dispose = function () {
  82595. _super.prototype.dispose.call(this);
  82596. this.onTriggerStateChangedObservable.clear();
  82597. this.onMainButtonStateChangedObservable.clear();
  82598. this.onSecondaryButtonStateChangedObservable.clear();
  82599. this.onPadStateChangedObservable.clear();
  82600. this.onPadValuesChangedObservable.clear();
  82601. };
  82602. return WebVRController;
  82603. }(BABYLON.PoseEnabledController));
  82604. BABYLON.WebVRController = WebVRController;
  82605. })(BABYLON || (BABYLON = {}));
  82606. //# sourceMappingURL=babylon.webVRController.js.map
  82607. var BABYLON;
  82608. (function (BABYLON) {
  82609. /**
  82610. * Oculus Touch Controller
  82611. */
  82612. var OculusTouchController = /** @class */ (function (_super) {
  82613. __extends(OculusTouchController, _super);
  82614. /**
  82615. * Creates a new OculusTouchController from a gamepad
  82616. * @param vrGamepad the gamepad that the controller should be created from
  82617. */
  82618. function OculusTouchController(vrGamepad) {
  82619. var _this = _super.call(this, vrGamepad) || this;
  82620. /**
  82621. * Fired when the secondary trigger on this controller is modified
  82622. */
  82623. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  82624. /**
  82625. * Fired when the thumb rest on this controller is modified
  82626. */
  82627. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  82628. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  82629. return _this;
  82630. }
  82631. /**
  82632. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82633. * @param scene scene in which to add meshes
  82634. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82635. */
  82636. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82637. var _this = this;
  82638. var meshName;
  82639. // Hand
  82640. if (this.hand === 'left') {
  82641. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  82642. }
  82643. else { // Right is the default if no hand is specified
  82644. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  82645. }
  82646. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  82647. /*
  82648. Parent Mesh name: oculus_touch_left
  82649. - body
  82650. - trigger
  82651. - thumbstick
  82652. - grip
  82653. - button_y
  82654. - button_x
  82655. - button_enter
  82656. */
  82657. _this._defaultModel = newMeshes[1];
  82658. _this.attachToMesh(_this._defaultModel);
  82659. if (meshLoaded) {
  82660. meshLoaded(_this._defaultModel);
  82661. }
  82662. });
  82663. };
  82664. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  82665. /**
  82666. * Fired when the A button on this controller is modified
  82667. */
  82668. get: function () {
  82669. if (this.hand === 'right') {
  82670. return this.onMainButtonStateChangedObservable;
  82671. }
  82672. else {
  82673. throw new Error('No A button on left hand');
  82674. }
  82675. },
  82676. enumerable: true,
  82677. configurable: true
  82678. });
  82679. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  82680. /**
  82681. * Fired when the B button on this controller is modified
  82682. */
  82683. get: function () {
  82684. if (this.hand === 'right') {
  82685. return this.onSecondaryButtonStateChangedObservable;
  82686. }
  82687. else {
  82688. throw new Error('No B button on left hand');
  82689. }
  82690. },
  82691. enumerable: true,
  82692. configurable: true
  82693. });
  82694. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  82695. /**
  82696. * Fired when the X button on this controller is modified
  82697. */
  82698. get: function () {
  82699. if (this.hand === 'left') {
  82700. return this.onMainButtonStateChangedObservable;
  82701. }
  82702. else {
  82703. throw new Error('No X button on right hand');
  82704. }
  82705. },
  82706. enumerable: true,
  82707. configurable: true
  82708. });
  82709. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  82710. /**
  82711. * Fired when the Y button on this controller is modified
  82712. */
  82713. get: function () {
  82714. if (this.hand === 'left') {
  82715. return this.onSecondaryButtonStateChangedObservable;
  82716. }
  82717. else {
  82718. throw new Error('No Y button on right hand');
  82719. }
  82720. },
  82721. enumerable: true,
  82722. configurable: true
  82723. });
  82724. /**
  82725. * Called once for each button that changed state since the last frame
  82726. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  82727. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  82728. * 2) secondary trigger (same)
  82729. * 3) A (right) X (left), touch, pressed = value
  82730. * 4) B / Y
  82731. * 5) thumb rest
  82732. * @param buttonIdx Which button index changed
  82733. * @param state New state of the button
  82734. * @param changes Which properties on the state changed since last frame
  82735. */
  82736. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82737. var notifyObject = state; //{ state: state, changes: changes };
  82738. var triggerDirection = this.hand === 'right' ? -1 : 1;
  82739. switch (buttonIdx) {
  82740. case 0:
  82741. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82742. return;
  82743. case 1: // index trigger
  82744. if (this._defaultModel) {
  82745. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  82746. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  82747. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  82748. }
  82749. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82750. return;
  82751. case 2: // secondary trigger
  82752. if (this._defaultModel) {
  82753. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  82754. }
  82755. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  82756. return;
  82757. case 3:
  82758. if (this._defaultModel) {
  82759. if (notifyObject.pressed) {
  82760. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  82761. }
  82762. else {
  82763. (this._defaultModel.getChildren()[1]).position.y = 0;
  82764. }
  82765. }
  82766. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82767. return;
  82768. case 4:
  82769. if (this._defaultModel) {
  82770. if (notifyObject.pressed) {
  82771. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82772. }
  82773. else {
  82774. (this._defaultModel.getChildren()[2]).position.y = 0;
  82775. }
  82776. }
  82777. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82778. return;
  82779. case 5:
  82780. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  82781. return;
  82782. }
  82783. };
  82784. /**
  82785. * Base Url for the controller model.
  82786. */
  82787. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  82788. /**
  82789. * File name for the left controller model.
  82790. */
  82791. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  82792. /**
  82793. * File name for the right controller model.
  82794. */
  82795. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  82796. return OculusTouchController;
  82797. }(BABYLON.WebVRController));
  82798. BABYLON.OculusTouchController = OculusTouchController;
  82799. })(BABYLON || (BABYLON = {}));
  82800. //# sourceMappingURL=babylon.oculusTouchController.js.map
  82801. var BABYLON;
  82802. (function (BABYLON) {
  82803. /**
  82804. * Vive Controller
  82805. */
  82806. var ViveController = /** @class */ (function (_super) {
  82807. __extends(ViveController, _super);
  82808. /**
  82809. * Creates a new ViveController from a gamepad
  82810. * @param vrGamepad the gamepad that the controller should be created from
  82811. */
  82812. function ViveController(vrGamepad) {
  82813. var _this = _super.call(this, vrGamepad) || this;
  82814. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  82815. _this._invertLeftStickY = true;
  82816. return _this;
  82817. }
  82818. /**
  82819. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82820. * @param scene scene in which to add meshes
  82821. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82822. */
  82823. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82824. var _this = this;
  82825. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  82826. /*
  82827. Parent Mesh name: ViveWand
  82828. - body
  82829. - r_gripper
  82830. - l_gripper
  82831. - menu_button
  82832. - system_button
  82833. - trackpad
  82834. - trigger
  82835. - LED
  82836. */
  82837. _this._defaultModel = newMeshes[1];
  82838. _this.attachToMesh(_this._defaultModel);
  82839. if (meshLoaded) {
  82840. meshLoaded(_this._defaultModel);
  82841. }
  82842. });
  82843. };
  82844. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  82845. /**
  82846. * Fired when the left button on this controller is modified
  82847. */
  82848. get: function () {
  82849. return this.onMainButtonStateChangedObservable;
  82850. },
  82851. enumerable: true,
  82852. configurable: true
  82853. });
  82854. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  82855. /**
  82856. * Fired when the right button on this controller is modified
  82857. */
  82858. get: function () {
  82859. return this.onMainButtonStateChangedObservable;
  82860. },
  82861. enumerable: true,
  82862. configurable: true
  82863. });
  82864. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  82865. /**
  82866. * Fired when the menu button on this controller is modified
  82867. */
  82868. get: function () {
  82869. return this.onSecondaryButtonStateChangedObservable;
  82870. },
  82871. enumerable: true,
  82872. configurable: true
  82873. });
  82874. /**
  82875. * Called once for each button that changed state since the last frame
  82876. * Vive mapping:
  82877. * 0: touchpad
  82878. * 1: trigger
  82879. * 2: left AND right buttons
  82880. * 3: menu button
  82881. * @param buttonIdx Which button index changed
  82882. * @param state New state of the button
  82883. * @param changes Which properties on the state changed since last frame
  82884. */
  82885. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82886. var notifyObject = state; //{ state: state, changes: changes };
  82887. switch (buttonIdx) {
  82888. case 0:
  82889. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82890. return;
  82891. case 1: // index trigger
  82892. if (this._defaultModel) {
  82893. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  82894. }
  82895. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82896. return;
  82897. case 2: // left AND right button
  82898. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82899. return;
  82900. case 3:
  82901. if (this._defaultModel) {
  82902. if (notifyObject.pressed) {
  82903. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82904. }
  82905. else {
  82906. (this._defaultModel.getChildren()[2]).position.y = 0;
  82907. }
  82908. }
  82909. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82910. return;
  82911. }
  82912. };
  82913. /**
  82914. * Base Url for the controller model.
  82915. */
  82916. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  82917. /**
  82918. * File name for the controller model.
  82919. */
  82920. ViveController.MODEL_FILENAME = 'wand.babylon';
  82921. return ViveController;
  82922. }(BABYLON.WebVRController));
  82923. BABYLON.ViveController = ViveController;
  82924. })(BABYLON || (BABYLON = {}));
  82925. //# sourceMappingURL=babylon.viveController.js.map
  82926. var BABYLON;
  82927. (function (BABYLON) {
  82928. /**
  82929. * Generic Controller
  82930. */
  82931. var GenericController = /** @class */ (function (_super) {
  82932. __extends(GenericController, _super);
  82933. /**
  82934. * Creates a new GenericController from a gamepad
  82935. * @param vrGamepad the gamepad that the controller should be created from
  82936. */
  82937. function GenericController(vrGamepad) {
  82938. return _super.call(this, vrGamepad) || this;
  82939. }
  82940. /**
  82941. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82942. * @param scene scene in which to add meshes
  82943. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82944. */
  82945. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82946. var _this = this;
  82947. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  82948. _this._defaultModel = newMeshes[1];
  82949. _this.attachToMesh(_this._defaultModel);
  82950. if (meshLoaded) {
  82951. meshLoaded(_this._defaultModel);
  82952. }
  82953. });
  82954. };
  82955. /**
  82956. * Called once for each button that changed state since the last frame
  82957. * @param buttonIdx Which button index changed
  82958. * @param state New state of the button
  82959. * @param changes Which properties on the state changed since last frame
  82960. */
  82961. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82962. console.log("Button id: " + buttonIdx + "state: ");
  82963. console.dir(state);
  82964. };
  82965. /**
  82966. * Base Url for the controller model.
  82967. */
  82968. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82969. /**
  82970. * File name for the controller model.
  82971. */
  82972. GenericController.MODEL_FILENAME = 'generic.babylon';
  82973. return GenericController;
  82974. }(BABYLON.WebVRController));
  82975. BABYLON.GenericController = GenericController;
  82976. })(BABYLON || (BABYLON = {}));
  82977. //# sourceMappingURL=babylon.genericController.js.map
  82978. var BABYLON;
  82979. (function (BABYLON) {
  82980. /**
  82981. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  82982. */
  82983. var LoadedMeshInfo = /** @class */ (function () {
  82984. function LoadedMeshInfo() {
  82985. /**
  82986. * Map of the button meshes contained in the controller
  82987. */
  82988. this.buttonMeshes = {};
  82989. /**
  82990. * Map of the axis meshes contained in the controller
  82991. */
  82992. this.axisMeshes = {};
  82993. }
  82994. return LoadedMeshInfo;
  82995. }());
  82996. /**
  82997. * Defines the WindowsMotionController object that the state of the windows motion controller
  82998. */
  82999. var WindowsMotionController = /** @class */ (function (_super) {
  83000. __extends(WindowsMotionController, _super);
  83001. /**
  83002. * Creates a new WindowsMotionController from a gamepad
  83003. * @param vrGamepad the gamepad that the controller should be created from
  83004. */
  83005. function WindowsMotionController(vrGamepad) {
  83006. var _this = _super.call(this, vrGamepad) || this;
  83007. _this._mapping = {
  83008. // Semantic button names
  83009. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  83010. // A mapping of the button name to glTF model node name
  83011. // that should be transformed by button value.
  83012. buttonMeshNames: {
  83013. 'trigger': 'SELECT',
  83014. 'menu': 'MENU',
  83015. 'grip': 'GRASP',
  83016. 'thumbstick': 'THUMBSTICK_PRESS',
  83017. 'trackpad': 'TOUCHPAD_PRESS'
  83018. },
  83019. // This mapping is used to translate from the Motion Controller to Babylon semantics
  83020. buttonObservableNames: {
  83021. 'trigger': 'onTriggerStateChangedObservable',
  83022. 'menu': 'onSecondaryButtonStateChangedObservable',
  83023. 'grip': 'onMainButtonStateChangedObservable',
  83024. 'thumbstick': 'onPadStateChangedObservable',
  83025. 'trackpad': 'onTrackpadChangedObservable'
  83026. },
  83027. // A mapping of the axis name to glTF model node name
  83028. // that should be transformed by axis value.
  83029. // This array mirrors the browserGamepad.axes array, such that
  83030. // the mesh corresponding to axis 0 is in this array index 0.
  83031. axisMeshNames: [
  83032. 'THUMBSTICK_X',
  83033. 'THUMBSTICK_Y',
  83034. 'TOUCHPAD_TOUCH_X',
  83035. 'TOUCHPAD_TOUCH_Y'
  83036. ],
  83037. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  83038. };
  83039. /**
  83040. * Fired when the trackpad on this controller is clicked
  83041. */
  83042. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  83043. /**
  83044. * Fired when the trackpad on this controller is modified
  83045. */
  83046. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  83047. /**
  83048. * The current x and y values of this controller's trackpad
  83049. */
  83050. _this.trackpad = { x: 0, y: 0 };
  83051. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  83052. _this._loadedMeshInfo = null;
  83053. return _this;
  83054. }
  83055. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  83056. /**
  83057. * Fired when the trigger on this controller is modified
  83058. */
  83059. get: function () {
  83060. return this.onTriggerStateChangedObservable;
  83061. },
  83062. enumerable: true,
  83063. configurable: true
  83064. });
  83065. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  83066. /**
  83067. * Fired when the menu button on this controller is modified
  83068. */
  83069. get: function () {
  83070. return this.onSecondaryButtonStateChangedObservable;
  83071. },
  83072. enumerable: true,
  83073. configurable: true
  83074. });
  83075. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  83076. /**
  83077. * Fired when the grip button on this controller is modified
  83078. */
  83079. get: function () {
  83080. return this.onMainButtonStateChangedObservable;
  83081. },
  83082. enumerable: true,
  83083. configurable: true
  83084. });
  83085. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  83086. /**
  83087. * Fired when the thumbstick button on this controller is modified
  83088. */
  83089. get: function () {
  83090. return this.onPadStateChangedObservable;
  83091. },
  83092. enumerable: true,
  83093. configurable: true
  83094. });
  83095. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  83096. /**
  83097. * Fired when the touchpad button on this controller is modified
  83098. */
  83099. get: function () {
  83100. return this.onTrackpadChangedObservable;
  83101. },
  83102. enumerable: true,
  83103. configurable: true
  83104. });
  83105. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  83106. /**
  83107. * Fired when the touchpad values on this controller are modified
  83108. */
  83109. get: function () {
  83110. return this.onTrackpadValuesChangedObservable;
  83111. },
  83112. enumerable: true,
  83113. configurable: true
  83114. });
  83115. WindowsMotionController.prototype._updateTrackpad = function () {
  83116. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  83117. this.trackpad.x = this.browserGamepad["axes"][2];
  83118. this.trackpad.y = this.browserGamepad["axes"][3];
  83119. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  83120. }
  83121. };
  83122. /**
  83123. * Called once per frame by the engine.
  83124. */
  83125. WindowsMotionController.prototype.update = function () {
  83126. _super.prototype.update.call(this);
  83127. if (this.browserGamepad.axes) {
  83128. this._updateTrackpad();
  83129. // Only need to animate axes if there is a loaded mesh
  83130. if (this._loadedMeshInfo) {
  83131. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  83132. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  83133. }
  83134. }
  83135. }
  83136. };
  83137. /**
  83138. * Called once for each button that changed state since the last frame
  83139. * @param buttonIdx Which button index changed
  83140. * @param state New state of the button
  83141. * @param changes Which properties on the state changed since last frame
  83142. */
  83143. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83144. var buttonName = this._mapping.buttons[buttonIdx];
  83145. if (!buttonName) {
  83146. return;
  83147. }
  83148. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  83149. this._updateTrackpad();
  83150. // Only emit events for buttons that we know how to map from index to name
  83151. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  83152. if (observable) {
  83153. observable.notifyObservers(state);
  83154. }
  83155. this._lerpButtonTransform(buttonName, state.value);
  83156. };
  83157. /**
  83158. * Moves the buttons on the controller mesh based on their current state
  83159. * @param buttonName the name of the button to move
  83160. * @param buttonValue the value of the button which determines the buttons new position
  83161. */
  83162. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  83163. // If there is no loaded mesh, there is nothing to transform.
  83164. if (!this._loadedMeshInfo) {
  83165. return;
  83166. }
  83167. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  83168. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83169. return;
  83170. }
  83171. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  83172. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  83173. };
  83174. /**
  83175. * Moves the axis on the controller mesh based on its current state
  83176. * @param axis the index of the axis
  83177. * @param axisValue the value of the axis which determines the meshes new position
  83178. * @hidden
  83179. */
  83180. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  83181. if (!this._loadedMeshInfo) {
  83182. return;
  83183. }
  83184. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  83185. if (!meshInfo) {
  83186. return;
  83187. }
  83188. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83189. return;
  83190. }
  83191. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  83192. var lerpValue = axisValue * 0.5 + 0.5;
  83193. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  83194. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  83195. };
  83196. /**
  83197. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83198. * @param scene scene in which to add meshes
  83199. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83200. */
  83201. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  83202. var _this = this;
  83203. if (forceDefault === void 0) { forceDefault = false; }
  83204. var path;
  83205. var filename;
  83206. // Checking if GLB loader is present
  83207. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  83208. // Determine the device specific folder based on the ID suffix
  83209. var device = 'default';
  83210. if (this.id && !forceDefault) {
  83211. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  83212. device = ((match && match[0]) || device);
  83213. }
  83214. // Hand
  83215. if (this.hand === 'left') {
  83216. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  83217. }
  83218. else { // Right is the default if no hand is specified
  83219. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  83220. }
  83221. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  83222. }
  83223. else {
  83224. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  83225. path = BABYLON.GenericController.MODEL_BASE_URL;
  83226. filename = BABYLON.GenericController.MODEL_FILENAME;
  83227. }
  83228. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  83229. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  83230. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  83231. if (!_this._loadedMeshInfo) {
  83232. return;
  83233. }
  83234. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  83235. _this.attachToMesh(_this._defaultModel);
  83236. if (meshLoaded) {
  83237. meshLoaded(_this._defaultModel);
  83238. }
  83239. }, null, function (scene, message) {
  83240. BABYLON.Tools.Log(message);
  83241. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  83242. if (!forceDefault) {
  83243. _this.initControllerMesh(scene, meshLoaded, true);
  83244. }
  83245. });
  83246. };
  83247. /**
  83248. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  83249. * can be transformed by button presses and axes values, based on this._mapping.
  83250. *
  83251. * @param scene scene in which the meshes exist
  83252. * @param meshes list of meshes that make up the controller model to process
  83253. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  83254. */
  83255. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  83256. var loadedMeshInfo = null;
  83257. // Create a new mesh to contain the glTF hierarchy
  83258. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  83259. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  83260. var childMesh = null;
  83261. for (var i = 0; i < meshes.length; i++) {
  83262. var mesh = meshes[i];
  83263. if (!mesh.parent) {
  83264. // Exclude controller meshes from picking results
  83265. mesh.isPickable = false;
  83266. // Handle root node, attach to the new parentMesh
  83267. childMesh = mesh;
  83268. break;
  83269. }
  83270. }
  83271. if (childMesh) {
  83272. childMesh.setParent(parentMesh);
  83273. // Create our mesh info. Note that this method will always return non-null.
  83274. loadedMeshInfo = this.createMeshInfo(parentMesh);
  83275. }
  83276. else {
  83277. BABYLON.Tools.Warn('Could not find root node in model file.');
  83278. }
  83279. return loadedMeshInfo;
  83280. };
  83281. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  83282. var loadedMeshInfo = new LoadedMeshInfo();
  83283. var i;
  83284. loadedMeshInfo.rootNode = rootNode;
  83285. // Reset the caches
  83286. loadedMeshInfo.buttonMeshes = {};
  83287. loadedMeshInfo.axisMeshes = {};
  83288. // Button Meshes
  83289. for (i = 0; i < this._mapping.buttons.length; i++) {
  83290. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  83291. if (!buttonMeshName) {
  83292. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  83293. continue;
  83294. }
  83295. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  83296. if (!buttonMesh) {
  83297. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  83298. continue;
  83299. }
  83300. var buttonMeshInfo = {
  83301. index: i,
  83302. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  83303. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  83304. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  83305. };
  83306. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  83307. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  83308. }
  83309. else {
  83310. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  83311. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  83312. '(VALUE: ' + !!buttonMeshInfo.value +
  83313. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  83314. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  83315. ')');
  83316. }
  83317. }
  83318. // Axis Meshes
  83319. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  83320. var axisMeshName = this._mapping.axisMeshNames[i];
  83321. if (!axisMeshName) {
  83322. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  83323. continue;
  83324. }
  83325. var axisMesh = getChildByName(rootNode, axisMeshName);
  83326. if (!axisMesh) {
  83327. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  83328. continue;
  83329. }
  83330. var axisMeshInfo = {
  83331. index: i,
  83332. value: getImmediateChildByName(axisMesh, 'VALUE'),
  83333. min: getImmediateChildByName(axisMesh, 'MIN'),
  83334. max: getImmediateChildByName(axisMesh, 'MAX')
  83335. };
  83336. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  83337. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  83338. }
  83339. else {
  83340. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  83341. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  83342. '(VALUE: ' + !!axisMeshInfo.value +
  83343. ', MIN: ' + !!axisMeshInfo.min +
  83344. ', MAX:' + !!axisMeshInfo.max +
  83345. ')');
  83346. }
  83347. }
  83348. // Pointing Ray
  83349. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  83350. if (!loadedMeshInfo.pointingPoseNode) {
  83351. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  83352. }
  83353. else {
  83354. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  83355. }
  83356. return loadedMeshInfo;
  83357. // Look through all children recursively. This will return null if no mesh exists with the given name.
  83358. function getChildByName(node, name) {
  83359. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  83360. }
  83361. // Look through only immediate children. This will return null if no mesh exists with the given name.
  83362. function getImmediateChildByName(node, name) {
  83363. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  83364. }
  83365. };
  83366. /**
  83367. * Gets the ray of the controller in the direction the controller is pointing
  83368. * @param length the length the resulting ray should be
  83369. * @returns a ray in the direction the controller is pointing
  83370. */
  83371. WindowsMotionController.prototype.getForwardRay = function (length) {
  83372. if (length === void 0) { length = 100; }
  83373. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  83374. return _super.prototype.getForwardRay.call(this, length);
  83375. }
  83376. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  83377. var origin = m.getTranslation();
  83378. var forward = new BABYLON.Vector3(0, 0, -1);
  83379. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83380. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83381. return new BABYLON.Ray(origin, direction, length);
  83382. };
  83383. /**
  83384. * Disposes of the controller
  83385. */
  83386. WindowsMotionController.prototype.dispose = function () {
  83387. _super.prototype.dispose.call(this);
  83388. this.onTrackpadChangedObservable.clear();
  83389. };
  83390. /**
  83391. * The base url used to load the left and right controller models
  83392. */
  83393. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  83394. /**
  83395. * The name of the left controller model file
  83396. */
  83397. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  83398. /**
  83399. * The name of the right controller model file
  83400. */
  83401. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  83402. /**
  83403. * The controller name prefix for this controller type
  83404. */
  83405. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  83406. /**
  83407. * The controller id pattern for this controller type
  83408. */
  83409. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  83410. return WindowsMotionController;
  83411. }(BABYLON.WebVRController));
  83412. BABYLON.WindowsMotionController = WindowsMotionController;
  83413. })(BABYLON || (BABYLON = {}));
  83414. //# sourceMappingURL=babylon.windowsMotionController.js.map
  83415. var BABYLON;
  83416. (function (BABYLON) {
  83417. /**
  83418. * Gear VR Controller
  83419. */
  83420. var GearVRController = /** @class */ (function (_super) {
  83421. __extends(GearVRController, _super);
  83422. /**
  83423. * Creates a new GearVRController from a gamepad
  83424. * @param vrGamepad the gamepad that the controller should be created from
  83425. */
  83426. function GearVRController(vrGamepad) {
  83427. var _this = _super.call(this, vrGamepad) || this;
  83428. _this._buttonIndexToObservableNameMap = [
  83429. 'onTrackpadChangedObservable',
  83430. 'onTriggerStateChangedObservable' // Trigger
  83431. ];
  83432. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  83433. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  83434. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  83435. _this._disableTrackPosition(_this._calculatedPosition);
  83436. return _this;
  83437. }
  83438. /**
  83439. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83440. * @param scene scene in which to add meshes
  83441. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83442. */
  83443. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83444. var _this = this;
  83445. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  83446. // Offset the controller so it will rotate around the users wrist
  83447. var mesh = new BABYLON.Mesh("", scene);
  83448. newMeshes[1].parent = mesh;
  83449. newMeshes[1].position.z = -0.15;
  83450. _this._defaultModel = mesh;
  83451. _this.attachToMesh(_this._defaultModel);
  83452. if (meshLoaded) {
  83453. meshLoaded(_this._defaultModel);
  83454. }
  83455. });
  83456. };
  83457. /**
  83458. * Called once for each button that changed state since the last frame
  83459. * @param buttonIdx Which button index changed
  83460. * @param state New state of the button
  83461. * @param changes Which properties on the state changed since last frame
  83462. */
  83463. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83464. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  83465. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  83466. // Only emit events for buttons that we know how to map from index to observable
  83467. var observable = this[observableName];
  83468. if (observable) {
  83469. observable.notifyObservers(state);
  83470. }
  83471. }
  83472. };
  83473. /**
  83474. * Base Url for the controller model.
  83475. */
  83476. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83477. /**
  83478. * File name for the controller model.
  83479. */
  83480. GearVRController.MODEL_FILENAME = 'generic.babylon';
  83481. /**
  83482. * Gamepad Id prefix used to identify this controller.
  83483. */
  83484. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  83485. return GearVRController;
  83486. }(BABYLON.WebVRController));
  83487. BABYLON.GearVRController = GearVRController;
  83488. })(BABYLON || (BABYLON = {}));
  83489. //# sourceMappingURL=babylon.gearVRController.js.map
  83490. var BABYLON;
  83491. (function (BABYLON) {
  83492. /**
  83493. * Google Daydream controller
  83494. */
  83495. var DaydreamController = /** @class */ (function (_super) {
  83496. __extends(DaydreamController, _super);
  83497. /**
  83498. * Creates a new DaydreamController from a gamepad
  83499. * @param vrGamepad the gamepad that the controller should be created from
  83500. */
  83501. function DaydreamController(vrGamepad) {
  83502. var _this = _super.call(this, vrGamepad) || this;
  83503. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  83504. return _this;
  83505. }
  83506. /**
  83507. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83508. * @param scene scene in which to add meshes
  83509. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83510. */
  83511. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83512. var _this = this;
  83513. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  83514. _this._defaultModel = newMeshes[1];
  83515. _this.attachToMesh(_this._defaultModel);
  83516. if (meshLoaded) {
  83517. meshLoaded(_this._defaultModel);
  83518. }
  83519. });
  83520. };
  83521. /**
  83522. * Called once for each button that changed state since the last frame
  83523. * @param buttonIdx Which button index changed
  83524. * @param state New state of the button
  83525. * @param changes Which properties on the state changed since last frame
  83526. */
  83527. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83528. // Daydream controller only has 1 GamepadButton (on the trackpad).
  83529. if (buttonIdx === 0) {
  83530. var observable = this.onTriggerStateChangedObservable;
  83531. if (observable) {
  83532. observable.notifyObservers(state);
  83533. }
  83534. }
  83535. else {
  83536. // If the app or home buttons are ever made available
  83537. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  83538. }
  83539. };
  83540. /**
  83541. * Base Url for the controller model.
  83542. */
  83543. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83544. /**
  83545. * File name for the controller model.
  83546. */
  83547. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  83548. /**
  83549. * Gamepad Id prefix used to identify Daydream Controller.
  83550. */
  83551. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  83552. return DaydreamController;
  83553. }(BABYLON.WebVRController));
  83554. BABYLON.DaydreamController = DaydreamController;
  83555. })(BABYLON || (BABYLON = {}));
  83556. //# sourceMappingURL=babylon.daydreamController.js.map
  83557. var BABYLON;
  83558. (function (BABYLON) {
  83559. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  83560. get: function () {
  83561. if (!this._gamepadManager) {
  83562. this._gamepadManager = new BABYLON.GamepadManager(this);
  83563. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  83564. if (!component) {
  83565. component = new GamepadSystemSceneComponent(this);
  83566. this._addComponent(component);
  83567. }
  83568. }
  83569. return this._gamepadManager;
  83570. },
  83571. enumerable: true,
  83572. configurable: true
  83573. });
  83574. /**
  83575. * Adds a gamepad to the free camera inputs manager
  83576. */
  83577. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  83578. this.add(new BABYLON.FreeCameraGamepadInput());
  83579. return this;
  83580. };
  83581. /**
  83582. * Adds a gamepad to the arc rotate camera inputs manager
  83583. */
  83584. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  83585. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  83586. return this;
  83587. };
  83588. /**
  83589. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  83590. */
  83591. var GamepadSystemSceneComponent = /** @class */ (function () {
  83592. /**
  83593. * Creates a new instance of the component for the given scene
  83594. * @param scene Defines the scene to register the component in
  83595. */
  83596. function GamepadSystemSceneComponent(scene) {
  83597. /**
  83598. * The component name helpfull to identify the component in the list of scene components.
  83599. */
  83600. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  83601. this.scene = scene;
  83602. }
  83603. /**
  83604. * Registers the component in a given scene
  83605. */
  83606. GamepadSystemSceneComponent.prototype.register = function () {
  83607. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  83608. };
  83609. /**
  83610. * Rebuilds the elements related to this component in case of
  83611. * context lost for instance.
  83612. */
  83613. GamepadSystemSceneComponent.prototype.rebuild = function () {
  83614. // Nothing to do for gamepads
  83615. };
  83616. /**
  83617. * Disposes the component and the associated ressources
  83618. */
  83619. GamepadSystemSceneComponent.prototype.dispose = function () {
  83620. var gamepadManager = this.scene._gamepadManager;
  83621. if (gamepadManager) {
  83622. gamepadManager.dispose();
  83623. this.scene._gamepadManager = null;
  83624. }
  83625. };
  83626. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  83627. var gamepadManager = this.scene._gamepadManager;
  83628. if (gamepadManager && gamepadManager._isMonitoring) {
  83629. gamepadManager._checkGamepadsStatus();
  83630. }
  83631. };
  83632. return GamepadSystemSceneComponent;
  83633. }());
  83634. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  83635. })(BABYLON || (BABYLON = {}));
  83636. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  83637. var BABYLON;
  83638. (function (BABYLON) {
  83639. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  83640. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  83641. });
  83642. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  83643. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  83644. });
  83645. /**
  83646. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  83647. * an arc rotate version arcFollowCamera are available.
  83648. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83649. */
  83650. var FollowCamera = /** @class */ (function (_super) {
  83651. __extends(FollowCamera, _super);
  83652. /**
  83653. * Instantiates the follow camera.
  83654. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83655. * @param name Define the name of the camera in the scene
  83656. * @param position Define the position of the camera
  83657. * @param scene Define the scene the camera belong to
  83658. * @param lockedTarget Define the target of the camera
  83659. */
  83660. function FollowCamera(name, position, scene, lockedTarget) {
  83661. if (lockedTarget === void 0) { lockedTarget = null; }
  83662. var _this = _super.call(this, name, position, scene) || this;
  83663. /**
  83664. * Distance the follow camera should follow an object at
  83665. */
  83666. _this.radius = 12;
  83667. /**
  83668. * Define a rotation offset between the camera and the object it follows
  83669. */
  83670. _this.rotationOffset = 0;
  83671. /**
  83672. * Define a height offset between the camera and the object it follows.
  83673. * It can help following an object from the top (like a car chaing a plane)
  83674. */
  83675. _this.heightOffset = 4;
  83676. /**
  83677. * Define how fast the camera can accelerate to follow it s target.
  83678. */
  83679. _this.cameraAcceleration = 0.05;
  83680. /**
  83681. * Define the speed limit of the camera following an object.
  83682. */
  83683. _this.maxCameraSpeed = 20;
  83684. _this.lockedTarget = lockedTarget;
  83685. return _this;
  83686. }
  83687. FollowCamera.prototype._follow = function (cameraTarget) {
  83688. if (!cameraTarget) {
  83689. return;
  83690. }
  83691. var yRotation;
  83692. if (cameraTarget.rotationQuaternion) {
  83693. var rotMatrix = new BABYLON.Matrix();
  83694. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  83695. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  83696. }
  83697. else {
  83698. yRotation = cameraTarget.rotation.y;
  83699. }
  83700. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  83701. var targetPosition = cameraTarget.getAbsolutePosition();
  83702. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  83703. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  83704. var dx = targetX - this.position.x;
  83705. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  83706. var dz = (targetZ) - this.position.z;
  83707. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  83708. var vy = dy * this.cameraAcceleration;
  83709. var vz = dz * this.cameraAcceleration * 2;
  83710. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  83711. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83712. }
  83713. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  83714. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83715. }
  83716. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  83717. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83718. }
  83719. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  83720. this.setTarget(targetPosition);
  83721. };
  83722. /** @hidden */
  83723. FollowCamera.prototype._checkInputs = function () {
  83724. _super.prototype._checkInputs.call(this);
  83725. if (this.lockedTarget) {
  83726. this._follow(this.lockedTarget);
  83727. }
  83728. };
  83729. /**
  83730. * Gets the camera class name.
  83731. * @returns the class name
  83732. */
  83733. FollowCamera.prototype.getClassName = function () {
  83734. return "FollowCamera";
  83735. };
  83736. __decorate([
  83737. BABYLON.serialize()
  83738. ], FollowCamera.prototype, "radius", void 0);
  83739. __decorate([
  83740. BABYLON.serialize()
  83741. ], FollowCamera.prototype, "rotationOffset", void 0);
  83742. __decorate([
  83743. BABYLON.serialize()
  83744. ], FollowCamera.prototype, "heightOffset", void 0);
  83745. __decorate([
  83746. BABYLON.serialize()
  83747. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  83748. __decorate([
  83749. BABYLON.serialize()
  83750. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  83751. __decorate([
  83752. BABYLON.serializeAsMeshReference("lockedTargetId")
  83753. ], FollowCamera.prototype, "lockedTarget", void 0);
  83754. return FollowCamera;
  83755. }(BABYLON.TargetCamera));
  83756. BABYLON.FollowCamera = FollowCamera;
  83757. /**
  83758. * Arc Rotate version of the follow camera.
  83759. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  83760. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83761. */
  83762. var ArcFollowCamera = /** @class */ (function (_super) {
  83763. __extends(ArcFollowCamera, _super);
  83764. /**
  83765. * Instantiates a new ArcFollowCamera
  83766. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83767. * @param name Define the name of the camera
  83768. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  83769. * @param beta Define the rotation angle of the camera around the elevation axis
  83770. * @param radius Define the radius of the camera from its target point
  83771. * @param target Define the target of the camera
  83772. * @param scene Define the scene the camera belongs to
  83773. */
  83774. function ArcFollowCamera(name,
  83775. /** The longitudinal angle of the camera */
  83776. alpha,
  83777. /** The latitudinal angle of the camera */
  83778. beta,
  83779. /** The radius of the camera from its target */
  83780. radius,
  83781. /** Define the camera target (the messh it should follow) */
  83782. target, scene) {
  83783. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  83784. _this.alpha = alpha;
  83785. _this.beta = beta;
  83786. _this.radius = radius;
  83787. _this.target = target;
  83788. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  83789. _this._follow();
  83790. return _this;
  83791. }
  83792. ArcFollowCamera.prototype._follow = function () {
  83793. if (!this.target) {
  83794. return;
  83795. }
  83796. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  83797. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  83798. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  83799. var targetPosition = this.target.getAbsolutePosition();
  83800. this.position = targetPosition.add(this._cartesianCoordinates);
  83801. this.setTarget(targetPosition);
  83802. };
  83803. /** @hidden */
  83804. ArcFollowCamera.prototype._checkInputs = function () {
  83805. _super.prototype._checkInputs.call(this);
  83806. this._follow();
  83807. };
  83808. /**
  83809. * Returns the class name of the object.
  83810. * It is mostly used internally for serialization purposes.
  83811. */
  83812. ArcFollowCamera.prototype.getClassName = function () {
  83813. return "ArcFollowCamera";
  83814. };
  83815. return ArcFollowCamera;
  83816. }(BABYLON.TargetCamera));
  83817. BABYLON.ArcFollowCamera = ArcFollowCamera;
  83818. })(BABYLON || (BABYLON = {}));
  83819. //# sourceMappingURL=babylon.followCamera.js.map
  83820. var BABYLON;
  83821. (function (BABYLON) {
  83822. /**
  83823. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  83824. * which still works and will still be found in many Playgrounds.
  83825. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83826. */
  83827. var UniversalCamera = /** @class */ (function (_super) {
  83828. __extends(UniversalCamera, _super);
  83829. /**
  83830. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  83831. * which still works and will still be found in many Playgrounds.
  83832. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83833. * @param name Define the name of the camera in the scene
  83834. * @param position Define the start position of the camera in the scene
  83835. * @param scene Define the scene the camera belongs to
  83836. */
  83837. function UniversalCamera(name, position, scene) {
  83838. var _this = _super.call(this, name, position, scene) || this;
  83839. _this.inputs.addGamepad();
  83840. return _this;
  83841. }
  83842. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  83843. /**
  83844. * Defines the gamepad rotation sensiblity.
  83845. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  83846. */
  83847. get: function () {
  83848. var gamepad = this.inputs.attached["gamepad"];
  83849. if (gamepad) {
  83850. return gamepad.gamepadAngularSensibility;
  83851. }
  83852. return 0;
  83853. },
  83854. set: function (value) {
  83855. var gamepad = this.inputs.attached["gamepad"];
  83856. if (gamepad) {
  83857. gamepad.gamepadAngularSensibility = value;
  83858. }
  83859. },
  83860. enumerable: true,
  83861. configurable: true
  83862. });
  83863. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  83864. /**
  83865. * Defines the gamepad move sensiblity.
  83866. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  83867. */
  83868. get: function () {
  83869. var gamepad = this.inputs.attached["gamepad"];
  83870. if (gamepad) {
  83871. return gamepad.gamepadMoveSensibility;
  83872. }
  83873. return 0;
  83874. },
  83875. set: function (value) {
  83876. var gamepad = this.inputs.attached["gamepad"];
  83877. if (gamepad) {
  83878. gamepad.gamepadMoveSensibility = value;
  83879. }
  83880. },
  83881. enumerable: true,
  83882. configurable: true
  83883. });
  83884. /**
  83885. * Gets the current object class name.
  83886. * @return the class name
  83887. */
  83888. UniversalCamera.prototype.getClassName = function () {
  83889. return "UniversalCamera";
  83890. };
  83891. return UniversalCamera;
  83892. }(BABYLON.TouchCamera));
  83893. BABYLON.UniversalCamera = UniversalCamera;
  83894. })(BABYLON || (BABYLON = {}));
  83895. //# sourceMappingURL=babylon.universalCamera.js.map
  83896. var BABYLON;
  83897. (function (BABYLON) {
  83898. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  83899. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  83900. });
  83901. /**
  83902. * This represents a FPS type of camera. This is only here for back compat purpose.
  83903. * Please use the UniversalCamera instead as both are identical.
  83904. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83905. */
  83906. var GamepadCamera = /** @class */ (function (_super) {
  83907. __extends(GamepadCamera, _super);
  83908. /**
  83909. * Instantiates a new Gamepad Camera
  83910. * This represents a FPS type of camera. This is only here for back compat purpose.
  83911. * Please use the UniversalCamera instead as both are identical.
  83912. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83913. * @param name Define the name of the camera in the scene
  83914. * @param position Define the start position of the camera in the scene
  83915. * @param scene Define the scene the camera belongs to
  83916. */
  83917. function GamepadCamera(name, position, scene) {
  83918. return _super.call(this, name, position, scene) || this;
  83919. }
  83920. /**
  83921. * Gets the current object class name.
  83922. * @return the class name
  83923. */
  83924. GamepadCamera.prototype.getClassName = function () {
  83925. return "GamepadCamera";
  83926. };
  83927. return GamepadCamera;
  83928. }(BABYLON.UniversalCamera));
  83929. BABYLON.GamepadCamera = GamepadCamera;
  83930. })(BABYLON || (BABYLON = {}));
  83931. //# sourceMappingURL=babylon.gamepadCamera.js.map
  83932. var BABYLON;
  83933. (function (BABYLON) {
  83934. /**
  83935. * PostProcessRenderPipelineManager class
  83936. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83937. */
  83938. var PostProcessRenderPipelineManager = /** @class */ (function () {
  83939. /**
  83940. * Initializes a PostProcessRenderPipelineManager
  83941. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83942. */
  83943. function PostProcessRenderPipelineManager() {
  83944. this._renderPipelines = {};
  83945. }
  83946. /**
  83947. * Adds a pipeline to the manager
  83948. * @param renderPipeline The pipeline to add
  83949. */
  83950. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  83951. this._renderPipelines[renderPipeline._name] = renderPipeline;
  83952. };
  83953. /**
  83954. * Attaches a camera to the pipeline
  83955. * @param renderPipelineName The name of the pipeline to attach to
  83956. * @param cameras the camera to attach
  83957. * @param unique if the camera can be attached multiple times to the pipeline
  83958. */
  83959. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  83960. if (unique === void 0) { unique = false; }
  83961. var renderPipeline = this._renderPipelines[renderPipelineName];
  83962. if (!renderPipeline) {
  83963. return;
  83964. }
  83965. renderPipeline._attachCameras(cameras, unique);
  83966. };
  83967. /**
  83968. * Detaches a camera from the pipeline
  83969. * @param renderPipelineName The name of the pipeline to detach from
  83970. * @param cameras the camera to detach
  83971. */
  83972. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  83973. var renderPipeline = this._renderPipelines[renderPipelineName];
  83974. if (!renderPipeline) {
  83975. return;
  83976. }
  83977. renderPipeline._detachCameras(cameras);
  83978. };
  83979. /**
  83980. * Enables an effect by name on a pipeline
  83981. * @param renderPipelineName the name of the pipeline to enable the effect in
  83982. * @param renderEffectName the name of the effect to enable
  83983. * @param cameras the cameras that the effect should be enabled on
  83984. */
  83985. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  83986. var renderPipeline = this._renderPipelines[renderPipelineName];
  83987. if (!renderPipeline) {
  83988. return;
  83989. }
  83990. renderPipeline._enableEffect(renderEffectName, cameras);
  83991. };
  83992. /**
  83993. * Disables an effect by name on a pipeline
  83994. * @param renderPipelineName the name of the pipeline to disable the effect in
  83995. * @param renderEffectName the name of the effect to disable
  83996. * @param cameras the cameras that the effect should be disabled on
  83997. */
  83998. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  83999. var renderPipeline = this._renderPipelines[renderPipelineName];
  84000. if (!renderPipeline) {
  84001. return;
  84002. }
  84003. renderPipeline._disableEffect(renderEffectName, cameras);
  84004. };
  84005. /**
  84006. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  84007. */
  84008. PostProcessRenderPipelineManager.prototype.update = function () {
  84009. for (var renderPipelineName in this._renderPipelines) {
  84010. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84011. var pipeline = this._renderPipelines[renderPipelineName];
  84012. if (!pipeline.isSupported) {
  84013. pipeline.dispose();
  84014. delete this._renderPipelines[renderPipelineName];
  84015. }
  84016. else {
  84017. pipeline._update();
  84018. }
  84019. }
  84020. }
  84021. };
  84022. /** @hidden */
  84023. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  84024. for (var renderPipelineName in this._renderPipelines) {
  84025. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84026. var pipeline = this._renderPipelines[renderPipelineName];
  84027. pipeline._rebuild();
  84028. }
  84029. }
  84030. };
  84031. /**
  84032. * Disposes of the manager and pipelines
  84033. */
  84034. PostProcessRenderPipelineManager.prototype.dispose = function () {
  84035. for (var renderPipelineName in this._renderPipelines) {
  84036. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84037. var pipeline = this._renderPipelines[renderPipelineName];
  84038. pipeline.dispose();
  84039. }
  84040. }
  84041. };
  84042. return PostProcessRenderPipelineManager;
  84043. }());
  84044. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  84045. })(BABYLON || (BABYLON = {}));
  84046. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  84047. var BABYLON;
  84048. (function (BABYLON) {
  84049. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  84050. get: function () {
  84051. if (!this._postProcessRenderPipelineManager) {
  84052. // Register the G Buffer component to the scene.
  84053. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  84054. if (!component) {
  84055. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  84056. this._addComponent(component);
  84057. }
  84058. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  84059. }
  84060. return this._postProcessRenderPipelineManager;
  84061. },
  84062. enumerable: true,
  84063. configurable: true
  84064. });
  84065. /**
  84066. * Defines the Render Pipeline scene component responsible to rendering pipelines
  84067. */
  84068. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  84069. /**
  84070. * Creates a new instance of the component for the given scene
  84071. * @param scene Defines the scene to register the component in
  84072. */
  84073. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  84074. /**
  84075. * The component name helpfull to identify the component in the list of scene components.
  84076. */
  84077. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  84078. this.scene = scene;
  84079. }
  84080. /**
  84081. * Registers the component in a given scene
  84082. */
  84083. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  84084. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  84085. };
  84086. /**
  84087. * Rebuilds the elements related to this component in case of
  84088. * context lost for instance.
  84089. */
  84090. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  84091. if (this.scene._postProcessRenderPipelineManager) {
  84092. this.scene._postProcessRenderPipelineManager._rebuild();
  84093. }
  84094. };
  84095. /**
  84096. * Disposes the component and the associated ressources
  84097. */
  84098. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  84099. if (this.scene._postProcessRenderPipelineManager) {
  84100. this.scene._postProcessRenderPipelineManager.dispose();
  84101. }
  84102. };
  84103. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84104. if (this.scene._postProcessRenderPipelineManager) {
  84105. this.scene._postProcessRenderPipelineManager.update();
  84106. }
  84107. };
  84108. return PostProcessRenderPipelineManagerSceneComponent;
  84109. }());
  84110. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  84111. })(BABYLON || (BABYLON = {}));
  84112. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  84113. var BABYLON;
  84114. (function (BABYLON) {
  84115. /**
  84116. * This represents a set of one or more post processes in Babylon.
  84117. * A post process can be used to apply a shader to a texture after it is rendered.
  84118. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84119. */
  84120. var PostProcessRenderEffect = /** @class */ (function () {
  84121. /**
  84122. * Instantiates a post process render effect.
  84123. * A post process can be used to apply a shader to a texture after it is rendered.
  84124. * @param engine The engine the effect is tied to
  84125. * @param name The name of the effect
  84126. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  84127. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  84128. */
  84129. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  84130. this._name = name;
  84131. this._singleInstance = singleInstance || true;
  84132. this._getPostProcesses = getPostProcesses;
  84133. this._cameras = {};
  84134. this._indicesForCamera = {};
  84135. this._postProcesses = {};
  84136. }
  84137. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  84138. /**
  84139. * Checks if all the post processes in the effect are supported.
  84140. */
  84141. get: function () {
  84142. for (var index in this._postProcesses) {
  84143. if (this._postProcesses.hasOwnProperty(index)) {
  84144. var pps = this._postProcesses[index];
  84145. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  84146. if (!pps[ppIndex].isSupported) {
  84147. return false;
  84148. }
  84149. }
  84150. }
  84151. }
  84152. return true;
  84153. },
  84154. enumerable: true,
  84155. configurable: true
  84156. });
  84157. /**
  84158. * Updates the current state of the effect
  84159. * @hidden
  84160. */
  84161. PostProcessRenderEffect.prototype._update = function () {
  84162. };
  84163. /**
  84164. * Attaches the effect on cameras
  84165. * @param cameras The camera to attach to.
  84166. * @hidden
  84167. */
  84168. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  84169. var _this = this;
  84170. var cameraKey;
  84171. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84172. if (!cams) {
  84173. return;
  84174. }
  84175. for (var i = 0; i < cams.length; i++) {
  84176. var camera = cams[i];
  84177. var cameraName = camera.name;
  84178. if (this._singleInstance) {
  84179. cameraKey = 0;
  84180. }
  84181. else {
  84182. cameraKey = cameraName;
  84183. }
  84184. if (!this._postProcesses[cameraKey]) {
  84185. var postProcess = this._getPostProcesses();
  84186. if (postProcess) {
  84187. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  84188. }
  84189. }
  84190. if (!this._indicesForCamera[cameraName]) {
  84191. this._indicesForCamera[cameraName] = [];
  84192. }
  84193. this._postProcesses[cameraKey].forEach(function (postProcess) {
  84194. var index = camera.attachPostProcess(postProcess);
  84195. _this._indicesForCamera[cameraName].push(index);
  84196. });
  84197. if (!this._cameras[cameraName]) {
  84198. this._cameras[cameraName] = camera;
  84199. }
  84200. }
  84201. };
  84202. /**
  84203. * Detatches the effect on cameras
  84204. * @param cameras The camera to detatch from.
  84205. * @hidden
  84206. */
  84207. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  84208. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84209. if (!cams) {
  84210. return;
  84211. }
  84212. for (var i = 0; i < cams.length; i++) {
  84213. var camera = cams[i];
  84214. var cameraName = camera.name;
  84215. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84216. camera.detachPostProcess(postProcess);
  84217. });
  84218. if (this._cameras[cameraName]) {
  84219. //this._indicesForCamera.splice(index, 1);
  84220. this._cameras[cameraName] = null;
  84221. }
  84222. }
  84223. };
  84224. /**
  84225. * Enables the effect on given cameras
  84226. * @param cameras The camera to enable.
  84227. * @hidden
  84228. */
  84229. PostProcessRenderEffect.prototype._enable = function (cameras) {
  84230. var _this = this;
  84231. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84232. if (!cams) {
  84233. return;
  84234. }
  84235. for (var i = 0; i < cams.length; i++) {
  84236. var camera = cams[i];
  84237. var cameraName = camera.name;
  84238. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  84239. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  84240. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84241. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  84242. });
  84243. }
  84244. }
  84245. }
  84246. };
  84247. /**
  84248. * Disables the effect on the given cameras
  84249. * @param cameras The camera to disable.
  84250. * @hidden
  84251. */
  84252. PostProcessRenderEffect.prototype._disable = function (cameras) {
  84253. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84254. if (!cams) {
  84255. return;
  84256. }
  84257. for (var i = 0; i < cams.length; i++) {
  84258. var camera = cams[i];
  84259. var cameraName = camera.name;
  84260. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84261. camera.detachPostProcess(postProcess);
  84262. });
  84263. }
  84264. };
  84265. /**
  84266. * Gets a list of the post processes contained in the effect.
  84267. * @param camera The camera to get the post processes on.
  84268. * @returns The list of the post processes in the effect.
  84269. */
  84270. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  84271. if (this._singleInstance) {
  84272. return this._postProcesses[0];
  84273. }
  84274. else {
  84275. if (!camera) {
  84276. return null;
  84277. }
  84278. return this._postProcesses[camera.name];
  84279. }
  84280. };
  84281. return PostProcessRenderEffect;
  84282. }());
  84283. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  84284. })(BABYLON || (BABYLON = {}));
  84285. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  84286. var BABYLON;
  84287. (function (BABYLON) {
  84288. /**
  84289. * PostProcessRenderPipeline
  84290. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84291. */
  84292. var PostProcessRenderPipeline = /** @class */ (function () {
  84293. /**
  84294. * Initializes a PostProcessRenderPipeline
  84295. * @param engine engine to add the pipeline to
  84296. * @param name name of the pipeline
  84297. */
  84298. function PostProcessRenderPipeline(engine, name) {
  84299. this.engine = engine;
  84300. this._name = name;
  84301. this._renderEffects = {};
  84302. this._renderEffectsForIsolatedPass = new Array();
  84303. this._cameras = [];
  84304. }
  84305. /**
  84306. * "PostProcessRenderPipeline"
  84307. * @returns "PostProcessRenderPipeline"
  84308. */
  84309. PostProcessRenderPipeline.prototype.getClassName = function () {
  84310. return "PostProcessRenderPipeline";
  84311. };
  84312. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  84313. /**
  84314. * If all the render effects in the pipeline are support
  84315. */
  84316. get: function () {
  84317. for (var renderEffectName in this._renderEffects) {
  84318. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84319. if (!this._renderEffects[renderEffectName].isSupported) {
  84320. return false;
  84321. }
  84322. }
  84323. }
  84324. return true;
  84325. },
  84326. enumerable: true,
  84327. configurable: true
  84328. });
  84329. /**
  84330. * Adds an effect to the pipeline
  84331. * @param renderEffect the effect to add
  84332. */
  84333. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  84334. this._renderEffects[renderEffect._name] = renderEffect;
  84335. };
  84336. // private
  84337. /** @hidden */
  84338. PostProcessRenderPipeline.prototype._rebuild = function () {
  84339. };
  84340. /** @hidden */
  84341. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  84342. var renderEffects = this._renderEffects[renderEffectName];
  84343. if (!renderEffects) {
  84344. return;
  84345. }
  84346. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84347. };
  84348. /** @hidden */
  84349. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  84350. var renderEffects = this._renderEffects[renderEffectName];
  84351. if (!renderEffects) {
  84352. return;
  84353. }
  84354. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84355. };
  84356. /** @hidden */
  84357. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  84358. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84359. if (!cams) {
  84360. return;
  84361. }
  84362. var indicesToDelete = [];
  84363. var i;
  84364. for (i = 0; i < cams.length; i++) {
  84365. var camera = cams[i];
  84366. var cameraName = camera.name;
  84367. if (this._cameras.indexOf(camera) === -1) {
  84368. this._cameras[cameraName] = camera;
  84369. }
  84370. else if (unique) {
  84371. indicesToDelete.push(i);
  84372. }
  84373. }
  84374. for (i = 0; i < indicesToDelete.length; i++) {
  84375. cameras.splice(indicesToDelete[i], 1);
  84376. }
  84377. for (var renderEffectName in this._renderEffects) {
  84378. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84379. this._renderEffects[renderEffectName]._attachCameras(cams);
  84380. }
  84381. }
  84382. };
  84383. /** @hidden */
  84384. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  84385. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84386. if (!cams) {
  84387. return;
  84388. }
  84389. for (var renderEffectName in this._renderEffects) {
  84390. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84391. this._renderEffects[renderEffectName]._detachCameras(cams);
  84392. }
  84393. }
  84394. for (var i = 0; i < cams.length; i++) {
  84395. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  84396. }
  84397. };
  84398. /** @hidden */
  84399. PostProcessRenderPipeline.prototype._update = function () {
  84400. for (var renderEffectName in this._renderEffects) {
  84401. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84402. this._renderEffects[renderEffectName]._update();
  84403. }
  84404. }
  84405. for (var i = 0; i < this._cameras.length; i++) {
  84406. var cameraName = this._cameras[i].name;
  84407. if (this._renderEffectsForIsolatedPass[cameraName]) {
  84408. this._renderEffectsForIsolatedPass[cameraName]._update();
  84409. }
  84410. }
  84411. };
  84412. /** @hidden */
  84413. PostProcessRenderPipeline.prototype._reset = function () {
  84414. this._renderEffects = {};
  84415. this._renderEffectsForIsolatedPass = new Array();
  84416. };
  84417. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  84418. // 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)
  84419. var effectKeys = Object.keys(this._renderEffects);
  84420. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  84421. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  84422. if (postProcesses) {
  84423. postProcesses[0].samples = sampleCount;
  84424. return true;
  84425. }
  84426. }
  84427. return false;
  84428. };
  84429. /**
  84430. * Disposes of the pipeline
  84431. */
  84432. PostProcessRenderPipeline.prototype.dispose = function () {
  84433. // Must be implemented by children
  84434. };
  84435. __decorate([
  84436. BABYLON.serialize()
  84437. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  84438. return PostProcessRenderPipeline;
  84439. }());
  84440. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  84441. })(BABYLON || (BABYLON = {}));
  84442. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  84443. var BABYLON;
  84444. (function (BABYLON) {
  84445. /**
  84446. * This represents a depth renderer in Babylon.
  84447. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  84448. */
  84449. var DepthRenderer = /** @class */ (function () {
  84450. /**
  84451. * Instantiates a depth renderer
  84452. * @param scene The scene the renderer belongs to
  84453. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  84454. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  84455. */
  84456. function DepthRenderer(scene, type, camera) {
  84457. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  84458. if (camera === void 0) { camera = null; }
  84459. var _this = this;
  84460. /**
  84461. * Specifiess that the depth renderer will only be used within
  84462. * the camera it is created for.
  84463. * This can help forcing its rendering during the camera processing.
  84464. */
  84465. this.useOnlyInActiveCamera = false;
  84466. this._scene = scene;
  84467. // Register the G Buffer component to the scene.
  84468. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  84469. if (!component) {
  84470. component = new BABYLON.DepthRendererSceneComponent(scene);
  84471. scene._addComponent(component);
  84472. }
  84473. this._camera = camera;
  84474. var engine = scene.getEngine();
  84475. // Render target
  84476. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  84477. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84478. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84479. this._depthMap.refreshRate = 1;
  84480. this._depthMap.renderParticles = false;
  84481. this._depthMap.renderList = null;
  84482. // Camera to get depth map from to support multiple concurrent cameras
  84483. this._depthMap.activeCamera = this._camera;
  84484. this._depthMap.ignoreCameraViewport = true;
  84485. this._depthMap.useCameraPostProcesses = false;
  84486. // set default depth value to 1.0 (far away)
  84487. this._depthMap.onClearObservable.add(function (engine) {
  84488. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  84489. });
  84490. // Custom render function
  84491. var renderSubMesh = function (subMesh) {
  84492. var mesh = subMesh.getRenderingMesh();
  84493. var scene = _this._scene;
  84494. var engine = scene.getEngine();
  84495. var material = subMesh.getMaterial();
  84496. if (!material) {
  84497. return;
  84498. }
  84499. // Culling and reverse (right handed system)
  84500. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84501. // Managing instances
  84502. var batch = mesh._getInstancesRenderList(subMesh._id);
  84503. if (batch.mustReturn) {
  84504. return;
  84505. }
  84506. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84507. var camera = _this._camera || scene.activeCamera;
  84508. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  84509. engine.enableEffect(_this._effect);
  84510. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84511. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84512. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  84513. // Alpha test
  84514. if (material && material.needAlphaTesting()) {
  84515. var alphaTexture = material.getAlphaTestTexture();
  84516. if (alphaTexture) {
  84517. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84518. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84519. }
  84520. }
  84521. // Bones
  84522. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84523. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84524. }
  84525. // Draw
  84526. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84527. }
  84528. };
  84529. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84530. var index;
  84531. if (depthOnlySubMeshes.length) {
  84532. engine.setColorWrite(false);
  84533. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84534. renderSubMesh(depthOnlySubMeshes.data[index]);
  84535. }
  84536. engine.setColorWrite(true);
  84537. }
  84538. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84539. renderSubMesh(opaqueSubMeshes.data[index]);
  84540. }
  84541. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84542. renderSubMesh(alphaTestSubMeshes.data[index]);
  84543. }
  84544. };
  84545. }
  84546. /**
  84547. * Creates the depth rendering effect and checks if the effect is ready.
  84548. * @param subMesh The submesh to be used to render the depth map of
  84549. * @param useInstances If multiple world instances should be used
  84550. * @returns if the depth renderer is ready to render the depth map
  84551. */
  84552. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  84553. var material = subMesh.getMaterial();
  84554. if (material.disableDepthWrite) {
  84555. return false;
  84556. }
  84557. var defines = [];
  84558. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84559. var mesh = subMesh.getMesh();
  84560. // Alpha test
  84561. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  84562. defines.push("#define ALPHATEST");
  84563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84564. attribs.push(BABYLON.VertexBuffer.UVKind);
  84565. defines.push("#define UV1");
  84566. }
  84567. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84568. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84569. defines.push("#define UV2");
  84570. }
  84571. }
  84572. // Bones
  84573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84574. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84575. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84576. if (mesh.numBoneInfluencers > 4) {
  84577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84579. }
  84580. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84581. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84582. }
  84583. else {
  84584. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84585. }
  84586. // Instances
  84587. if (useInstances) {
  84588. defines.push("#define INSTANCES");
  84589. attribs.push("world0");
  84590. attribs.push("world1");
  84591. attribs.push("world2");
  84592. attribs.push("world3");
  84593. }
  84594. // Get correct effect
  84595. var join = defines.join("\n");
  84596. if (this._cachedDefines !== join) {
  84597. this._cachedDefines = join;
  84598. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  84599. }
  84600. return this._effect.isReady();
  84601. };
  84602. /**
  84603. * Gets the texture which the depth map will be written to.
  84604. * @returns The depth map texture
  84605. */
  84606. DepthRenderer.prototype.getDepthMap = function () {
  84607. return this._depthMap;
  84608. };
  84609. /**
  84610. * Disposes of the depth renderer.
  84611. */
  84612. DepthRenderer.prototype.dispose = function () {
  84613. this._depthMap.dispose();
  84614. };
  84615. return DepthRenderer;
  84616. }());
  84617. BABYLON.DepthRenderer = DepthRenderer;
  84618. })(BABYLON || (BABYLON = {}));
  84619. //# sourceMappingURL=babylon.depthRenderer.js.map
  84620. var BABYLON;
  84621. (function (BABYLON) {
  84622. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  84623. camera = camera || this.activeCamera;
  84624. if (!camera) {
  84625. throw "No camera available to enable depth renderer";
  84626. }
  84627. if (!this._depthRenderer) {
  84628. this._depthRenderer = {};
  84629. }
  84630. if (!this._depthRenderer[camera.id]) {
  84631. var textureType = 0;
  84632. if (this.getEngine().getCaps().textureHalfFloatRender) {
  84633. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84634. }
  84635. else if (this.getEngine().getCaps().textureFloatRender) {
  84636. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84637. }
  84638. else {
  84639. throw "Depth renderer does not support int texture type";
  84640. }
  84641. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  84642. }
  84643. return this._depthRenderer[camera.id];
  84644. };
  84645. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  84646. camera = camera || this.activeCamera;
  84647. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  84648. return;
  84649. }
  84650. this._depthRenderer[camera.id].dispose();
  84651. delete this._depthRenderer[camera.id];
  84652. };
  84653. /**
  84654. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  84655. * in several rendering techniques.
  84656. */
  84657. var DepthRendererSceneComponent = /** @class */ (function () {
  84658. /**
  84659. * Creates a new instance of the component for the given scene
  84660. * @param scene Defines the scene to register the component in
  84661. */
  84662. function DepthRendererSceneComponent(scene) {
  84663. /**
  84664. * The component name helpfull to identify the component in the list of scene components.
  84665. */
  84666. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  84667. this.scene = scene;
  84668. }
  84669. /**
  84670. * Registers the component in a given scene
  84671. */
  84672. DepthRendererSceneComponent.prototype.register = function () {
  84673. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  84674. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  84675. };
  84676. /**
  84677. * Rebuilds the elements related to this component in case of
  84678. * context lost for instance.
  84679. */
  84680. DepthRendererSceneComponent.prototype.rebuild = function () {
  84681. // Nothing to do for this component
  84682. };
  84683. /**
  84684. * Disposes the component and the associated ressources
  84685. */
  84686. DepthRendererSceneComponent.prototype.dispose = function () {
  84687. for (var key in this.scene._depthRenderer) {
  84688. this.scene._depthRenderer[key].dispose();
  84689. }
  84690. };
  84691. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84692. if (this.scene._depthRenderer) {
  84693. for (var key in this.scene._depthRenderer) {
  84694. var depthRenderer = this.scene._depthRenderer[key];
  84695. if (!depthRenderer.useOnlyInActiveCamera) {
  84696. renderTargets.push(depthRenderer.getDepthMap());
  84697. }
  84698. }
  84699. }
  84700. };
  84701. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  84702. if (this.scene._depthRenderer) {
  84703. for (var key in this.scene._depthRenderer) {
  84704. var depthRenderer = this.scene._depthRenderer[key];
  84705. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  84706. renderTargets.push(depthRenderer.getDepthMap());
  84707. }
  84708. }
  84709. }
  84710. };
  84711. return DepthRendererSceneComponent;
  84712. }());
  84713. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  84714. })(BABYLON || (BABYLON = {}));
  84715. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  84716. var BABYLON;
  84717. (function (BABYLON) {
  84718. /**
  84719. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  84720. */
  84721. var GeometryBufferRenderer = /** @class */ (function () {
  84722. /**
  84723. * Creates a new G Buffer for the scene
  84724. * @param scene The scene the buffer belongs to
  84725. * @param ratio How big is the buffer related to the main canvas.
  84726. */
  84727. function GeometryBufferRenderer(scene, ratio) {
  84728. if (ratio === void 0) { ratio = 1; }
  84729. /**
  84730. * Dictionary used to store the previous transformation matrices of each rendered mesh
  84731. * in order to compute objects velocities when enableVelocity is set to "true"
  84732. * @hidden
  84733. */
  84734. this._previousTransformationMatrices = {};
  84735. this._enablePosition = false;
  84736. this._enableVelocity = false;
  84737. this._positionIndex = -1;
  84738. this._velocityIndex = -1;
  84739. this._scene = scene;
  84740. this._ratio = ratio;
  84741. // Register the G Buffer component to the scene.
  84742. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  84743. if (!component) {
  84744. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  84745. scene._addComponent(component);
  84746. }
  84747. // Render target
  84748. this._createRenderTargets();
  84749. }
  84750. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  84751. /**
  84752. * Set the render list (meshes to be rendered) used in the G buffer.
  84753. */
  84754. set: function (meshes) {
  84755. this._multiRenderTarget.renderList = meshes;
  84756. },
  84757. enumerable: true,
  84758. configurable: true
  84759. });
  84760. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  84761. /**
  84762. * Gets wether or not G buffer are supported by the running hardware.
  84763. * This requires draw buffer supports
  84764. */
  84765. get: function () {
  84766. return this._multiRenderTarget.isSupported;
  84767. },
  84768. enumerable: true,
  84769. configurable: true
  84770. });
  84771. /**
  84772. * Returns the index of the given texture type in the G-Buffer textures array
  84773. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  84774. * @returns the index of the given texture type in the G-Buffer textures array
  84775. */
  84776. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  84777. switch (textureType) {
  84778. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  84779. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  84780. default: return -1;
  84781. }
  84782. };
  84783. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  84784. /**
  84785. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  84786. */
  84787. get: function () {
  84788. return this._enablePosition;
  84789. },
  84790. /**
  84791. * Sets whether or not objects positions are enabled for the G buffer.
  84792. */
  84793. set: function (enable) {
  84794. this._enablePosition = enable;
  84795. this.dispose();
  84796. this._createRenderTargets();
  84797. },
  84798. enumerable: true,
  84799. configurable: true
  84800. });
  84801. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  84802. /**
  84803. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  84804. */
  84805. get: function () {
  84806. return this._enableVelocity;
  84807. },
  84808. /**
  84809. * Sets wether or not objects velocities are enabled for the G buffer.
  84810. */
  84811. set: function (enable) {
  84812. this._enableVelocity = enable;
  84813. this.dispose();
  84814. this._createRenderTargets();
  84815. },
  84816. enumerable: true,
  84817. configurable: true
  84818. });
  84819. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  84820. /**
  84821. * Gets the scene associated with the buffer.
  84822. */
  84823. get: function () {
  84824. return this._scene;
  84825. },
  84826. enumerable: true,
  84827. configurable: true
  84828. });
  84829. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  84830. /**
  84831. * Gets the ratio used by the buffer during its creation.
  84832. * How big is the buffer related to the main canvas.
  84833. */
  84834. get: function () {
  84835. return this._ratio;
  84836. },
  84837. enumerable: true,
  84838. configurable: true
  84839. });
  84840. /**
  84841. * Checks wether everything is ready to render a submesh to the G buffer.
  84842. * @param subMesh the submesh to check readiness for
  84843. * @param useInstances is the mesh drawn using instance or not
  84844. * @returns true if ready otherwise false
  84845. */
  84846. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  84847. var material = subMesh.getMaterial();
  84848. if (material && material.disableDepthWrite) {
  84849. return false;
  84850. }
  84851. var defines = [];
  84852. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84853. var mesh = subMesh.getMesh();
  84854. // Alpha test
  84855. if (material && material.needAlphaTesting()) {
  84856. defines.push("#define ALPHATEST");
  84857. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84858. attribs.push(BABYLON.VertexBuffer.UVKind);
  84859. defines.push("#define UV1");
  84860. }
  84861. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84862. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84863. defines.push("#define UV2");
  84864. }
  84865. }
  84866. // Buffers
  84867. if (this._enablePosition) {
  84868. defines.push("#define POSITION");
  84869. defines.push("#define POSITION_INDEX " + this._positionIndex);
  84870. }
  84871. if (this._enableVelocity) {
  84872. defines.push("#define VELOCITY");
  84873. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  84874. }
  84875. // Bones
  84876. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84877. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84878. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84879. if (mesh.numBoneInfluencers > 4) {
  84880. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84881. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84882. }
  84883. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84884. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84885. }
  84886. else {
  84887. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84888. }
  84889. // Instances
  84890. if (useInstances) {
  84891. defines.push("#define INSTANCES");
  84892. attribs.push("world0");
  84893. attribs.push("world1");
  84894. attribs.push("world2");
  84895. attribs.push("world3");
  84896. }
  84897. // Setup textures count
  84898. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  84899. // Get correct effect
  84900. var join = defines.join("\n");
  84901. if (this._cachedDefines !== join) {
  84902. this._cachedDefines = join;
  84903. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  84904. }
  84905. return this._effect.isReady();
  84906. };
  84907. /**
  84908. * Gets the current underlying G Buffer.
  84909. * @returns the buffer
  84910. */
  84911. GeometryBufferRenderer.prototype.getGBuffer = function () {
  84912. return this._multiRenderTarget;
  84913. };
  84914. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  84915. /**
  84916. * Gets the number of samples used to render the buffer (anti aliasing).
  84917. */
  84918. get: function () {
  84919. return this._multiRenderTarget.samples;
  84920. },
  84921. /**
  84922. * Sets the number of samples used to render the buffer (anti aliasing).
  84923. */
  84924. set: function (value) {
  84925. this._multiRenderTarget.samples = value;
  84926. },
  84927. enumerable: true,
  84928. configurable: true
  84929. });
  84930. /**
  84931. * Disposes the renderer and frees up associated resources.
  84932. */
  84933. GeometryBufferRenderer.prototype.dispose = function () {
  84934. this.getGBuffer().dispose();
  84935. };
  84936. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  84937. var _this = this;
  84938. var engine = this._scene.getEngine();
  84939. var count = 2;
  84940. if (this._enablePosition) {
  84941. this._positionIndex = count;
  84942. count++;
  84943. }
  84944. if (this._enableVelocity) {
  84945. this._velocityIndex = count;
  84946. count++;
  84947. }
  84948. 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 });
  84949. if (!this.isSupported) {
  84950. return;
  84951. }
  84952. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84953. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84954. this._multiRenderTarget.refreshRate = 1;
  84955. this._multiRenderTarget.renderParticles = false;
  84956. this._multiRenderTarget.renderList = null;
  84957. // set default depth value to 1.0 (far away)
  84958. this._multiRenderTarget.onClearObservable.add(function (engine) {
  84959. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  84960. });
  84961. // Custom render function
  84962. var renderSubMesh = function (subMesh) {
  84963. var mesh = subMesh.getRenderingMesh();
  84964. var scene = _this._scene;
  84965. var engine = scene.getEngine();
  84966. var material = subMesh.getMaterial();
  84967. if (!material) {
  84968. return;
  84969. }
  84970. // Velocity
  84971. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  84972. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  84973. }
  84974. // Culling
  84975. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84976. // Managing instances
  84977. var batch = mesh._getInstancesRenderList(subMesh._id);
  84978. if (batch.mustReturn) {
  84979. return;
  84980. }
  84981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84982. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  84983. engine.enableEffect(_this._effect);
  84984. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84985. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84986. _this._effect.setMatrix("view", scene.getViewMatrix());
  84987. // Alpha test
  84988. if (material && material.needAlphaTesting()) {
  84989. var alphaTexture = material.getAlphaTestTexture();
  84990. if (alphaTexture) {
  84991. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84992. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84993. }
  84994. }
  84995. // Bones
  84996. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84997. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84998. }
  84999. // Velocity
  85000. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  85001. // Draw
  85002. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  85003. }
  85004. // Velocity
  85005. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  85006. };
  85007. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85008. var index;
  85009. if (depthOnlySubMeshes.length) {
  85010. engine.setColorWrite(false);
  85011. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85012. renderSubMesh(depthOnlySubMeshes.data[index]);
  85013. }
  85014. engine.setColorWrite(true);
  85015. }
  85016. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85017. renderSubMesh(opaqueSubMeshes.data[index]);
  85018. }
  85019. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85020. renderSubMesh(alphaTestSubMeshes.data[index]);
  85021. }
  85022. };
  85023. };
  85024. /**
  85025. * Constant used to retrieve the position texture index in the G-Buffer textures array
  85026. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  85027. */
  85028. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  85029. /**
  85030. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  85031. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  85032. */
  85033. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  85034. return GeometryBufferRenderer;
  85035. }());
  85036. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  85037. })(BABYLON || (BABYLON = {}));
  85038. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  85039. var BABYLON;
  85040. (function (BABYLON) {
  85041. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  85042. get: function () {
  85043. this._geometryBufferRenderer;
  85044. },
  85045. set: function (value) {
  85046. if (value && value.isSupported) {
  85047. this._geometryBufferRenderer = value;
  85048. }
  85049. },
  85050. enumerable: true,
  85051. configurable: true
  85052. });
  85053. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  85054. if (ratio === void 0) { ratio = 1; }
  85055. if (this._geometryBufferRenderer) {
  85056. return this._geometryBufferRenderer;
  85057. }
  85058. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  85059. if (!this._geometryBufferRenderer.isSupported) {
  85060. this._geometryBufferRenderer = null;
  85061. }
  85062. return this._geometryBufferRenderer;
  85063. };
  85064. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  85065. if (!this._geometryBufferRenderer) {
  85066. return;
  85067. }
  85068. this._geometryBufferRenderer.dispose();
  85069. this._geometryBufferRenderer = null;
  85070. };
  85071. /**
  85072. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  85073. * in several rendering techniques.
  85074. */
  85075. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  85076. /**
  85077. * Creates a new instance of the component for the given scene
  85078. * @param scene Defines the scene to register the component in
  85079. */
  85080. function GeometryBufferRendererSceneComponent(scene) {
  85081. /**
  85082. * The component name helpful to identify the component in the list of scene components.
  85083. */
  85084. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  85085. this.scene = scene;
  85086. }
  85087. /**
  85088. * Registers the component in a given scene
  85089. */
  85090. GeometryBufferRendererSceneComponent.prototype.register = function () {
  85091. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  85092. };
  85093. /**
  85094. * Rebuilds the elements related to this component in case of
  85095. * context lost for instance.
  85096. */
  85097. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  85098. // Nothing to do for this component
  85099. };
  85100. /**
  85101. * Disposes the component and the associated ressources
  85102. */
  85103. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  85104. // Nothing to do for this component
  85105. };
  85106. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85107. if (this.scene._geometryBufferRenderer) {
  85108. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  85109. }
  85110. };
  85111. return GeometryBufferRendererSceneComponent;
  85112. }());
  85113. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  85114. })(BABYLON || (BABYLON = {}));
  85115. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  85116. var BABYLON;
  85117. (function (BABYLON) {
  85118. /**
  85119. * Render pipeline to produce ssao effect
  85120. */
  85121. var SSAORenderingPipeline = /** @class */ (function (_super) {
  85122. __extends(SSAORenderingPipeline, _super);
  85123. /**
  85124. * @constructor
  85125. * @param name - The rendering pipeline name
  85126. * @param scene - The scene linked to this pipeline
  85127. * @param 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 }
  85128. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  85129. */
  85130. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  85131. var _this = _super.call(this, scene.getEngine(), name) || this;
  85132. // Members
  85133. /**
  85134. * @ignore
  85135. * The PassPostProcess id in the pipeline that contains the original scene color
  85136. */
  85137. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85138. /**
  85139. * @ignore
  85140. * The SSAO PostProcess id in the pipeline
  85141. */
  85142. _this.SSAORenderEffect = "SSAORenderEffect";
  85143. /**
  85144. * @ignore
  85145. * The horizontal blur PostProcess id in the pipeline
  85146. */
  85147. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85148. /**
  85149. * @ignore
  85150. * The vertical blur PostProcess id in the pipeline
  85151. */
  85152. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85153. /**
  85154. * @ignore
  85155. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85156. */
  85157. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85158. /**
  85159. * The output strength of the SSAO post-process. Default value is 1.0.
  85160. */
  85161. _this.totalStrength = 1.0;
  85162. /**
  85163. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  85164. */
  85165. _this.radius = 0.0001;
  85166. /**
  85167. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  85168. * Must not be equal to fallOff and superior to fallOff.
  85169. * Default value is 0.975
  85170. */
  85171. _this.area = 0.0075;
  85172. /**
  85173. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  85174. * Must not be equal to area and inferior to area.
  85175. * Default value is 0.0
  85176. */
  85177. _this.fallOff = 0.000001;
  85178. /**
  85179. * The base color of the SSAO post-process
  85180. * The final result is "base + ssao" between [0, 1]
  85181. */
  85182. _this.base = 0.5;
  85183. _this._firstUpdate = true;
  85184. _this._scene = scene;
  85185. // Set up assets
  85186. _this._createRandomTexture();
  85187. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85188. var ssaoRatio = ratio.ssaoRatio || ratio;
  85189. var combineRatio = ratio.combineRatio || ratio;
  85190. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85191. _this._createSSAOPostProcess(ssaoRatio);
  85192. _this._createBlurPostProcess(ssaoRatio);
  85193. _this._createSSAOCombinePostProcess(combineRatio);
  85194. // Set up pipeline
  85195. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85196. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85197. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85198. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85200. // Finish
  85201. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85202. if (cameras) {
  85203. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85204. }
  85205. return _this;
  85206. }
  85207. // Public Methods
  85208. /**
  85209. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85210. */
  85211. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85212. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85213. for (var i = 0; i < this._scene.cameras.length; i++) {
  85214. var camera = this._scene.cameras[i];
  85215. this._originalColorPostProcess.dispose(camera);
  85216. this._ssaoPostProcess.dispose(camera);
  85217. this._blurHPostProcess.dispose(camera);
  85218. this._blurVPostProcess.dispose(camera);
  85219. this._ssaoCombinePostProcess.dispose(camera);
  85220. }
  85221. this._randomTexture.dispose();
  85222. if (disableDepthRender) {
  85223. this._scene.disableDepthRenderer();
  85224. }
  85225. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85226. _super.prototype.dispose.call(this);
  85227. };
  85228. // Private Methods
  85229. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  85230. var _this = this;
  85231. var size = 16;
  85232. 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);
  85233. 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);
  85234. this._blurHPostProcess.onActivateObservable.add(function () {
  85235. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  85236. _this._blurHPostProcess.kernel = size * dw;
  85237. });
  85238. this._blurVPostProcess.onActivateObservable.add(function () {
  85239. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  85240. _this._blurVPostProcess.kernel = size * dw;
  85241. });
  85242. };
  85243. /** @hidden */
  85244. SSAORenderingPipeline.prototype._rebuild = function () {
  85245. this._firstUpdate = true;
  85246. _super.prototype._rebuild.call(this);
  85247. };
  85248. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85249. var _this = this;
  85250. var numSamples = 16;
  85251. var sampleSphere = [
  85252. 0.5381, 0.1856, -0.4319,
  85253. 0.1379, 0.2486, 0.4430,
  85254. 0.3371, 0.5679, -0.0057,
  85255. -0.6999, -0.0451, -0.0019,
  85256. 0.0689, -0.1598, -0.8547,
  85257. 0.0560, 0.0069, -0.1843,
  85258. -0.0146, 0.1402, 0.0762,
  85259. 0.0100, -0.1924, -0.0344,
  85260. -0.3577, -0.5301, -0.4358,
  85261. -0.3169, 0.1063, 0.0158,
  85262. 0.0103, -0.5869, 0.0046,
  85263. -0.0897, -0.4940, 0.3287,
  85264. 0.7119, -0.0154, -0.0918,
  85265. -0.0533, 0.0596, -0.5411,
  85266. 0.0352, -0.0631, 0.5460,
  85267. -0.4776, 0.2847, -0.0271
  85268. ];
  85269. var samplesFactor = 1.0 / numSamples;
  85270. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  85271. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85272. "area", "fallOff", "base", "range", "viewport"
  85273. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85274. this._ssaoPostProcess.onApply = function (effect) {
  85275. if (_this._firstUpdate) {
  85276. effect.setArray3("sampleSphere", sampleSphere);
  85277. effect.setFloat("samplesFactor", samplesFactor);
  85278. effect.setFloat("randTextureTiles", 4.0);
  85279. }
  85280. effect.setFloat("totalStrength", _this.totalStrength);
  85281. effect.setFloat("radius", _this.radius);
  85282. effect.setFloat("area", _this.area);
  85283. effect.setFloat("fallOff", _this.fallOff);
  85284. effect.setFloat("base", _this.base);
  85285. effect.setTexture("textureSampler", _this._depthTexture);
  85286. effect.setTexture("randomSampler", _this._randomTexture);
  85287. };
  85288. };
  85289. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85290. var _this = this;
  85291. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85292. this._ssaoCombinePostProcess.onApply = function (effect) {
  85293. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  85294. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85295. };
  85296. };
  85297. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  85298. var size = 512;
  85299. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85300. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85301. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85302. var context = this._randomTexture.getContext();
  85303. var rand = function (min, max) {
  85304. return Math.random() * (max - min) + min;
  85305. };
  85306. var randVector = BABYLON.Vector3.Zero();
  85307. for (var x = 0; x < size; x++) {
  85308. for (var y = 0; y < size; y++) {
  85309. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  85310. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  85311. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  85312. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85313. context.fillRect(x, y, 1, 1);
  85314. }
  85315. }
  85316. this._randomTexture.update(false);
  85317. };
  85318. __decorate([
  85319. BABYLON.serialize()
  85320. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  85321. __decorate([
  85322. BABYLON.serialize()
  85323. ], SSAORenderingPipeline.prototype, "radius", void 0);
  85324. __decorate([
  85325. BABYLON.serialize()
  85326. ], SSAORenderingPipeline.prototype, "area", void 0);
  85327. __decorate([
  85328. BABYLON.serialize()
  85329. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  85330. __decorate([
  85331. BABYLON.serialize()
  85332. ], SSAORenderingPipeline.prototype, "base", void 0);
  85333. return SSAORenderingPipeline;
  85334. }(BABYLON.PostProcessRenderPipeline));
  85335. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  85336. })(BABYLON || (BABYLON = {}));
  85337. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  85338. var BABYLON;
  85339. (function (BABYLON) {
  85340. /**
  85341. * Render pipeline to produce ssao effect
  85342. */
  85343. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  85344. __extends(SSAO2RenderingPipeline, _super);
  85345. /**
  85346. * @constructor
  85347. * @param name The rendering pipeline name
  85348. * @param scene The scene linked to this pipeline
  85349. * @param 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 }
  85350. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85351. */
  85352. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  85353. var _this = _super.call(this, scene.getEngine(), name) || this;
  85354. // Members
  85355. /**
  85356. * @ignore
  85357. * The PassPostProcess id in the pipeline that contains the original scene color
  85358. */
  85359. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85360. /**
  85361. * @ignore
  85362. * The SSAO PostProcess id in the pipeline
  85363. */
  85364. _this.SSAORenderEffect = "SSAORenderEffect";
  85365. /**
  85366. * @ignore
  85367. * The horizontal blur PostProcess id in the pipeline
  85368. */
  85369. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85370. /**
  85371. * @ignore
  85372. * The vertical blur PostProcess id in the pipeline
  85373. */
  85374. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85375. /**
  85376. * @ignore
  85377. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85378. */
  85379. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85380. /**
  85381. * The output strength of the SSAO post-process. Default value is 1.0.
  85382. */
  85383. _this.totalStrength = 1.0;
  85384. /**
  85385. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  85386. */
  85387. _this.maxZ = 100.0;
  85388. /**
  85389. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  85390. */
  85391. _this.minZAspect = 0.2;
  85392. _this._samples = 8;
  85393. _this._textureSamples = 1;
  85394. _this._expensiveBlur = true;
  85395. /**
  85396. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  85397. */
  85398. _this.radius = 2.0;
  85399. /**
  85400. * The base color of the SSAO post-process
  85401. * The final result is "base + ssao" between [0, 1]
  85402. */
  85403. _this.base = 0;
  85404. _this._firstUpdate = true;
  85405. _this._bits = new Uint32Array(1);
  85406. _this._scene = scene;
  85407. _this._ratio = ratio;
  85408. if (!_this.isSupported) {
  85409. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  85410. return _this;
  85411. }
  85412. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  85413. var blurRatio = _this._ratio.blurRatio || ratio;
  85414. // Set up assets
  85415. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  85416. _this._createRandomTexture();
  85417. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  85418. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  85419. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85420. _this._originalColorPostProcess.samples = _this.textureSamples;
  85421. _this._createSSAOPostProcess(1.0);
  85422. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  85423. _this._createSSAOCombinePostProcess(blurRatio);
  85424. // Set up pipeline
  85425. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85430. // Finish
  85431. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85432. if (cameras) {
  85433. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85434. }
  85435. return _this;
  85436. }
  85437. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  85438. get: function () {
  85439. return this._samples;
  85440. },
  85441. /**
  85442. * Number of samples used for the SSAO calculations. Default value is 8
  85443. */
  85444. set: function (n) {
  85445. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  85446. this._samples = n;
  85447. this._sampleSphere = this._generateHemisphere();
  85448. this._firstUpdate = true;
  85449. },
  85450. enumerable: true,
  85451. configurable: true
  85452. });
  85453. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  85454. get: function () {
  85455. return this._textureSamples;
  85456. },
  85457. /**
  85458. * Number of samples to use for antialiasing
  85459. */
  85460. set: function (n) {
  85461. this._textureSamples = n;
  85462. this._originalColorPostProcess.samples = n;
  85463. this._blurHPostProcess.samples = n;
  85464. this._blurVPostProcess.samples = n;
  85465. this._ssaoPostProcess.samples = n;
  85466. this._ssaoCombinePostProcess.samples = n;
  85467. },
  85468. enumerable: true,
  85469. configurable: true
  85470. });
  85471. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  85472. get: function () {
  85473. return this._expensiveBlur;
  85474. },
  85475. /**
  85476. * If bilateral blur should be used
  85477. */
  85478. set: function (b) {
  85479. 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"]);
  85480. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  85481. this._expensiveBlur = b;
  85482. this._firstUpdate = true;
  85483. },
  85484. enumerable: true,
  85485. configurable: true
  85486. });
  85487. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  85488. /**
  85489. * Support test.
  85490. */
  85491. get: function () {
  85492. var engine = BABYLON.Engine.LastCreatedEngine;
  85493. if (!engine) {
  85494. return false;
  85495. }
  85496. return engine.getCaps().drawBuffersExtension;
  85497. },
  85498. enumerable: true,
  85499. configurable: true
  85500. });
  85501. // Public Methods
  85502. /**
  85503. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85504. */
  85505. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  85506. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  85507. for (var i = 0; i < this._scene.cameras.length; i++) {
  85508. var camera = this._scene.cameras[i];
  85509. this._originalColorPostProcess.dispose(camera);
  85510. this._ssaoPostProcess.dispose(camera);
  85511. this._blurHPostProcess.dispose(camera);
  85512. this._blurVPostProcess.dispose(camera);
  85513. this._ssaoCombinePostProcess.dispose(camera);
  85514. }
  85515. this._randomTexture.dispose();
  85516. if (disableGeometryBufferRenderer) {
  85517. this._scene.disableGeometryBufferRenderer();
  85518. }
  85519. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85520. _super.prototype.dispose.call(this);
  85521. };
  85522. // Private Methods
  85523. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  85524. var _this = this;
  85525. this._samplerOffsets = [];
  85526. var expensive = this.expensiveBlur;
  85527. for (var i = -8; i < 8; i++) {
  85528. this._samplerOffsets.push(i * 2 + 0.5);
  85529. }
  85530. 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");
  85531. this._blurHPostProcess.onApply = function (effect) {
  85532. if (!_this._scene.activeCamera) {
  85533. return;
  85534. }
  85535. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  85536. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85537. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85538. effect.setFloat("radius", _this.radius);
  85539. effect.setTexture("depthSampler", _this._depthTexture);
  85540. if (_this._firstUpdate) {
  85541. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85542. }
  85543. };
  85544. 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");
  85545. this._blurVPostProcess.onApply = function (effect) {
  85546. if (!_this._scene.activeCamera) {
  85547. return;
  85548. }
  85549. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  85550. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85551. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85552. effect.setFloat("radius", _this.radius);
  85553. effect.setTexture("depthSampler", _this._depthTexture);
  85554. if (_this._firstUpdate) {
  85555. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85556. _this._firstUpdate = false;
  85557. }
  85558. };
  85559. this._blurHPostProcess.samples = this.textureSamples;
  85560. this._blurVPostProcess.samples = this.textureSamples;
  85561. };
  85562. /** @hidden */
  85563. SSAO2RenderingPipeline.prototype._rebuild = function () {
  85564. this._firstUpdate = true;
  85565. _super.prototype._rebuild.call(this);
  85566. };
  85567. //Van der Corput radical inverse
  85568. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  85569. this._bits[0] = i;
  85570. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  85571. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  85572. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  85573. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  85574. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  85575. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  85576. };
  85577. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  85578. return [i / n, this._radicalInverse_VdC(i)];
  85579. };
  85580. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  85581. var phi = v * 2.0 * Math.PI;
  85582. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  85583. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  85584. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  85585. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  85586. };
  85587. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  85588. var numSamples = this.samples;
  85589. var result = [];
  85590. var vector;
  85591. var i = 0;
  85592. while (i < numSamples) {
  85593. if (numSamples < 16) {
  85594. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  85595. }
  85596. else {
  85597. var rand = this._hammersley(i, numSamples);
  85598. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  85599. }
  85600. result.push(vector.x, vector.y, vector.z);
  85601. i++;
  85602. }
  85603. return result;
  85604. };
  85605. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85606. var _this = this;
  85607. var numSamples = this.samples;
  85608. this._sampleSphere = this._generateHemisphere();
  85609. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  85610. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85611. "base", "range", "projection", "near", "far", "texelSize",
  85612. "xViewport", "yViewport", "maxZ", "minZAspect"
  85613. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85614. this._ssaoPostProcess.onApply = function (effect) {
  85615. if (_this._firstUpdate) {
  85616. effect.setArray3("sampleSphere", _this._sampleSphere);
  85617. effect.setFloat("randTextureTiles", 32.0);
  85618. }
  85619. if (!_this._scene.activeCamera) {
  85620. return;
  85621. }
  85622. effect.setFloat("samplesFactor", 1 / _this.samples);
  85623. effect.setFloat("totalStrength", _this.totalStrength);
  85624. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  85625. effect.setFloat("radius", _this.radius);
  85626. effect.setFloat("maxZ", _this.maxZ);
  85627. effect.setFloat("minZAspect", _this.minZAspect);
  85628. effect.setFloat("base", _this.base);
  85629. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85630. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85631. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  85632. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  85633. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  85634. effect.setTexture("textureSampler", _this._depthTexture);
  85635. effect.setTexture("normalSampler", _this._normalTexture);
  85636. effect.setTexture("randomSampler", _this._randomTexture);
  85637. };
  85638. this._ssaoPostProcess.samples = this.textureSamples;
  85639. };
  85640. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85641. var _this = this;
  85642. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85643. this._ssaoCombinePostProcess.onApply = function (effect) {
  85644. var viewport = _this._scene.activeCamera.viewport;
  85645. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  85646. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85647. };
  85648. this._ssaoCombinePostProcess.samples = this.textureSamples;
  85649. };
  85650. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  85651. var size = 128;
  85652. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85653. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85654. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85655. var context = this._randomTexture.getContext();
  85656. var rand = function (min, max) {
  85657. return Math.random() * (max - min) + min;
  85658. };
  85659. var randVector = BABYLON.Vector3.Zero();
  85660. for (var x = 0; x < size; x++) {
  85661. for (var y = 0; y < size; y++) {
  85662. randVector.x = rand(0.0, 1.0);
  85663. randVector.y = rand(0.0, 1.0);
  85664. randVector.z = 0.0;
  85665. randVector.normalize();
  85666. randVector.scaleInPlace(255);
  85667. randVector.x = Math.floor(randVector.x);
  85668. randVector.y = Math.floor(randVector.y);
  85669. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85670. context.fillRect(x, y, 1, 1);
  85671. }
  85672. }
  85673. this._randomTexture.update(false);
  85674. };
  85675. /**
  85676. * Serialize the rendering pipeline (Used when exporting)
  85677. * @returns the serialized object
  85678. */
  85679. SSAO2RenderingPipeline.prototype.serialize = function () {
  85680. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85681. serializationObject.customType = "SSAO2RenderingPipeline";
  85682. return serializationObject;
  85683. };
  85684. /**
  85685. * Parse the serialized pipeline
  85686. * @param source Source pipeline.
  85687. * @param scene The scene to load the pipeline to.
  85688. * @param rootUrl The URL of the serialized pipeline.
  85689. * @returns An instantiated pipeline from the serialized object.
  85690. */
  85691. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  85692. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85693. };
  85694. __decorate([
  85695. BABYLON.serialize()
  85696. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  85697. __decorate([
  85698. BABYLON.serialize()
  85699. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  85700. __decorate([
  85701. BABYLON.serialize()
  85702. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  85703. __decorate([
  85704. BABYLON.serialize("samples")
  85705. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  85706. __decorate([
  85707. BABYLON.serialize("textureSamples")
  85708. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  85709. __decorate([
  85710. BABYLON.serialize()
  85711. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  85712. __decorate([
  85713. BABYLON.serialize("expensiveBlur")
  85714. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  85715. __decorate([
  85716. BABYLON.serialize()
  85717. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  85718. __decorate([
  85719. BABYLON.serialize()
  85720. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  85721. return SSAO2RenderingPipeline;
  85722. }(BABYLON.PostProcessRenderPipeline));
  85723. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  85724. })(BABYLON || (BABYLON = {}));
  85725. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  85726. var BABYLON;
  85727. (function (BABYLON) {
  85728. /**
  85729. * BABYLON.JS Chromatic Aberration GLSL Shader
  85730. * Author: Olivier Guyot
  85731. * Separates very slightly R, G and B colors on the edges of the screen
  85732. * Inspired by Francois Tarlier & Martins Upitis
  85733. */
  85734. var LensRenderingPipeline = /** @class */ (function (_super) {
  85735. __extends(LensRenderingPipeline, _super);
  85736. /**
  85737. * @constructor
  85738. *
  85739. * Effect parameters are as follow:
  85740. * {
  85741. * chromatic_aberration: number; // from 0 to x (1 for realism)
  85742. * edge_blur: number; // from 0 to x (1 for realism)
  85743. * distortion: number; // from 0 to x (1 for realism)
  85744. * grain_amount: number; // from 0 to 1
  85745. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  85746. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  85747. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  85748. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  85749. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  85750. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  85751. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  85752. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  85753. * }
  85754. * Note: if an effect parameter is unset, effect is disabled
  85755. *
  85756. * @param name The rendering pipeline name
  85757. * @param parameters - An object containing all parameters (see above)
  85758. * @param scene The scene linked to this pipeline
  85759. * @param 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)
  85760. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85761. */
  85762. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  85763. if (ratio === void 0) { ratio = 1.0; }
  85764. var _this = _super.call(this, scene.getEngine(), name) || this;
  85765. // Lens effects can be of the following:
  85766. // - chromatic aberration (slight shift of RGB colors)
  85767. // - blur on the edge of the lens
  85768. // - lens distortion
  85769. // - depth-of-field blur & highlights enhancing
  85770. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  85771. // - grain effect (noise or custom texture)
  85772. // Two additional texture samplers are needed:
  85773. // - depth map (for depth-of-field)
  85774. // - grain texture
  85775. /**
  85776. * @ignore
  85777. * The chromatic aberration PostProcess id in the pipeline
  85778. */
  85779. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  85780. /**
  85781. * @ignore
  85782. * The highlights enhancing PostProcess id in the pipeline
  85783. */
  85784. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  85785. /**
  85786. * @ignore
  85787. * The depth-of-field PostProcess id in the pipeline
  85788. */
  85789. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  85790. _this._scene = scene;
  85791. // Fetch texture samplers
  85792. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85793. if (parameters.grain_texture) {
  85794. _this._grainTexture = parameters.grain_texture;
  85795. }
  85796. else {
  85797. _this._createGrainTexture();
  85798. }
  85799. // save parameters
  85800. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  85801. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  85802. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  85803. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  85804. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  85805. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  85806. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  85807. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  85808. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  85809. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  85810. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  85811. // Create effects
  85812. _this._createChromaticAberrationPostProcess(ratio);
  85813. _this._createHighlightsPostProcess(ratio);
  85814. _this._createDepthOfFieldPostProcess(ratio / 4);
  85815. // Set up pipeline
  85816. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  85817. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  85818. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  85819. if (_this._highlightsGain === -1) {
  85820. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  85821. }
  85822. // Finish
  85823. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85824. if (cameras) {
  85825. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85826. }
  85827. return _this;
  85828. }
  85829. // public methods (self explanatory)
  85830. /**
  85831. * Sets the amount of blur at the edges
  85832. * @param amount blur amount
  85833. */
  85834. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  85835. /**
  85836. * Sets edge blur to 0
  85837. */
  85838. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  85839. /**
  85840. * Sets the amout of grain
  85841. * @param amount Amount of grain
  85842. */
  85843. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  85844. /**
  85845. * Set grain amount to 0
  85846. */
  85847. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  85848. /**
  85849. * Sets the chromatic aberration amount
  85850. * @param amount amount of chromatic aberration
  85851. */
  85852. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  85853. /**
  85854. * Sets chromatic aberration amount to 0
  85855. */
  85856. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  85857. /**
  85858. * Sets the EdgeDistortion amount
  85859. * @param amount amount of EdgeDistortion
  85860. */
  85861. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  85862. /**
  85863. * Sets edge distortion to 0
  85864. */
  85865. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  85866. /**
  85867. * Sets the FocusDistance amount
  85868. * @param amount amount of FocusDistance
  85869. */
  85870. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  85871. /**
  85872. * Disables depth of field
  85873. */
  85874. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  85875. /**
  85876. * Sets the Aperture amount
  85877. * @param amount amount of Aperture
  85878. */
  85879. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  85880. /**
  85881. * Sets the DarkenOutOfFocus amount
  85882. * @param amount amount of DarkenOutOfFocus
  85883. */
  85884. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  85885. /**
  85886. * Creates a pentagon bokeh effect
  85887. */
  85888. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  85889. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  85890. };
  85891. /**
  85892. * Disables the pentagon bokeh effect
  85893. */
  85894. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  85895. this._highlightsPostProcess.updateEffect();
  85896. };
  85897. /**
  85898. * Enables noise blur
  85899. */
  85900. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  85901. /**
  85902. * Disables noise blur
  85903. */
  85904. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  85905. /**
  85906. * Sets the HighlightsGain amount
  85907. * @param amount amount of HighlightsGain
  85908. */
  85909. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  85910. this._highlightsGain = amount;
  85911. };
  85912. /**
  85913. * Sets the HighlightsThreshold amount
  85914. * @param amount amount of HighlightsThreshold
  85915. */
  85916. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  85917. if (this._highlightsGain === -1) {
  85918. this._highlightsGain = 1.0;
  85919. }
  85920. this._highlightsThreshold = amount;
  85921. };
  85922. /**
  85923. * Disables highlights
  85924. */
  85925. LensRenderingPipeline.prototype.disableHighlights = function () {
  85926. this._highlightsGain = -1;
  85927. };
  85928. /**
  85929. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  85930. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  85931. */
  85932. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85933. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85934. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85935. this._chromaticAberrationPostProcess = null;
  85936. this._highlightsPostProcess = null;
  85937. this._depthOfFieldPostProcess = null;
  85938. this._grainTexture.dispose();
  85939. if (disableDepthRender) {
  85940. this._scene.disableDepthRenderer();
  85941. }
  85942. };
  85943. // colors shifting and distortion
  85944. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  85945. var _this = this;
  85946. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  85947. [], // samplers
  85948. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85949. this._chromaticAberrationPostProcess.onApply = function (effect) {
  85950. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  85951. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85952. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85953. effect.setFloat('radialIntensity', 1);
  85954. effect.setFloat2('direction', 17, 17);
  85955. effect.setFloat2('centerPosition', 0.5, 0.5);
  85956. };
  85957. };
  85958. // highlights enhancing
  85959. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  85960. var _this = this;
  85961. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  85962. [], // samplers
  85963. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  85964. this._highlightsPostProcess.onApply = function (effect) {
  85965. effect.setFloat('gain', _this._highlightsGain);
  85966. effect.setFloat('threshold', _this._highlightsThreshold);
  85967. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  85968. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85969. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85970. };
  85971. };
  85972. // colors shifting and distortion
  85973. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  85974. var _this = this;
  85975. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  85976. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  85977. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  85978. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85979. this._depthOfFieldPostProcess.onApply = function (effect) {
  85980. effect.setTexture("depthSampler", _this._depthTexture);
  85981. effect.setTexture("grainSampler", _this._grainTexture);
  85982. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  85983. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  85984. effect.setFloat('grain_amount', _this._grainAmount);
  85985. effect.setBool('blur_noise', _this._blurNoise);
  85986. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85987. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  85988. effect.setFloat('distortion', _this._distortion);
  85989. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  85990. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  85991. effect.setFloat('aperture', _this._dofAperture);
  85992. effect.setFloat('darken', _this._dofDarken);
  85993. effect.setFloat('edge_blur', _this._edgeBlur);
  85994. effect.setBool('highlights', (_this._highlightsGain !== -1));
  85995. if (_this._scene.activeCamera) {
  85996. effect.setFloat('near', _this._scene.activeCamera.minZ);
  85997. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  85998. }
  85999. };
  86000. };
  86001. // creates a black and white random noise texture, 512x512
  86002. LensRenderingPipeline.prototype._createGrainTexture = function () {
  86003. var size = 512;
  86004. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86005. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86006. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86007. var context = this._grainTexture.getContext();
  86008. var rand = function (min, max) {
  86009. return Math.random() * (max - min) + min;
  86010. };
  86011. var value;
  86012. for (var x = 0; x < size; x++) {
  86013. for (var y = 0; y < size; y++) {
  86014. value = Math.floor(rand(0.42, 0.58) * 255);
  86015. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  86016. context.fillRect(x, y, 1, 1);
  86017. }
  86018. }
  86019. this._grainTexture.update(false);
  86020. };
  86021. return LensRenderingPipeline;
  86022. }(BABYLON.PostProcessRenderPipeline));
  86023. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  86024. })(BABYLON || (BABYLON = {}));
  86025. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  86026. var BABYLON;
  86027. (function (BABYLON) {
  86028. /**
  86029. * Standard rendering pipeline
  86030. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86031. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  86032. */
  86033. var StandardRenderingPipeline = /** @class */ (function (_super) {
  86034. __extends(StandardRenderingPipeline, _super);
  86035. /**
  86036. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86037. * @constructor
  86038. * @param name The rendering pipeline name
  86039. * @param scene The scene linked to this pipeline
  86040. * @param 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)
  86041. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  86042. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86043. */
  86044. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  86045. if (originalPostProcess === void 0) { originalPostProcess = null; }
  86046. var _this = _super.call(this, scene.getEngine(), name) || this;
  86047. /**
  86048. * Post-process used to down scale an image x4
  86049. */
  86050. _this.downSampleX4PostProcess = null;
  86051. /**
  86052. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  86053. */
  86054. _this.brightPassPostProcess = null;
  86055. /**
  86056. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  86057. */
  86058. _this.blurHPostProcesses = [];
  86059. /**
  86060. * Post-process array storing all the vertical blur post-processes used by the pipeline
  86061. */
  86062. _this.blurVPostProcesses = [];
  86063. /**
  86064. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  86065. */
  86066. _this.textureAdderPostProcess = null;
  86067. /**
  86068. * Post-process used to create volumetric lighting effect
  86069. */
  86070. _this.volumetricLightPostProcess = null;
  86071. /**
  86072. * Post-process used to smooth the previous volumetric light post-process on the X axis
  86073. */
  86074. _this.volumetricLightSmoothXPostProcess = null;
  86075. /**
  86076. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  86077. */
  86078. _this.volumetricLightSmoothYPostProcess = null;
  86079. /**
  86080. * Post-process used to merge the volumetric light effect and the real scene color
  86081. */
  86082. _this.volumetricLightMergePostProces = null;
  86083. /**
  86084. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  86085. */
  86086. _this.volumetricLightFinalPostProcess = null;
  86087. /**
  86088. * Base post-process used to calculate the average luminance of the final image for HDR
  86089. */
  86090. _this.luminancePostProcess = null;
  86091. /**
  86092. * Post-processes used to create down sample post-processes in order to get
  86093. * the average luminance of the final image for HDR
  86094. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  86095. */
  86096. _this.luminanceDownSamplePostProcesses = [];
  86097. /**
  86098. * Post-process used to create a HDR effect (light adaptation)
  86099. */
  86100. _this.hdrPostProcess = null;
  86101. /**
  86102. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  86103. */
  86104. _this.textureAdderFinalPostProcess = null;
  86105. /**
  86106. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  86107. */
  86108. _this.lensFlareFinalPostProcess = null;
  86109. /**
  86110. * Post-process used to merge the final HDR post-process and the real scene color
  86111. */
  86112. _this.hdrFinalPostProcess = null;
  86113. /**
  86114. * Post-process used to create a lens flare effect
  86115. */
  86116. _this.lensFlarePostProcess = null;
  86117. /**
  86118. * Post-process that merges the result of the lens flare post-process and the real scene color
  86119. */
  86120. _this.lensFlareComposePostProcess = null;
  86121. /**
  86122. * Post-process used to create a motion blur effect
  86123. */
  86124. _this.motionBlurPostProcess = null;
  86125. /**
  86126. * Post-process used to create a depth of field effect
  86127. */
  86128. _this.depthOfFieldPostProcess = null;
  86129. /**
  86130. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  86131. */
  86132. _this.fxaaPostProcess = null;
  86133. // Values
  86134. /**
  86135. * Represents the brightness threshold in order to configure the illuminated surfaces
  86136. */
  86137. _this.brightThreshold = 1.0;
  86138. /**
  86139. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  86140. */
  86141. _this.blurWidth = 512.0;
  86142. /**
  86143. * Sets if the blur for highlighted surfaces must be only horizontal
  86144. */
  86145. _this.horizontalBlur = false;
  86146. /**
  86147. * Sets the overall exposure used by the pipeline
  86148. */
  86149. _this.exposure = 1.0;
  86150. /**
  86151. * Texture used typically to simulate "dirty" on camera lens
  86152. */
  86153. _this.lensTexture = null;
  86154. /**
  86155. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  86156. */
  86157. _this.volumetricLightCoefficient = 0.2;
  86158. /**
  86159. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  86160. */
  86161. _this.volumetricLightPower = 4.0;
  86162. /**
  86163. * Used the set the blur intensity to smooth the volumetric lights
  86164. */
  86165. _this.volumetricLightBlurScale = 64.0;
  86166. /**
  86167. * Light (spot or directional) used to generate the volumetric lights rays
  86168. * The source light must have a shadow generate so the pipeline can get its
  86169. * depth map
  86170. */
  86171. _this.sourceLight = null;
  86172. /**
  86173. * For eye adaptation, represents the minimum luminance the eye can see
  86174. */
  86175. _this.hdrMinimumLuminance = 1.0;
  86176. /**
  86177. * For eye adaptation, represents the decrease luminance speed
  86178. */
  86179. _this.hdrDecreaseRate = 0.5;
  86180. /**
  86181. * For eye adaptation, represents the increase luminance speed
  86182. */
  86183. _this.hdrIncreaseRate = 0.5;
  86184. /**
  86185. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  86186. */
  86187. _this.lensColorTexture = null;
  86188. /**
  86189. * The overall strengh for the lens flare effect
  86190. */
  86191. _this.lensFlareStrength = 20.0;
  86192. /**
  86193. * Dispersion coefficient for lens flare ghosts
  86194. */
  86195. _this.lensFlareGhostDispersal = 1.4;
  86196. /**
  86197. * Main lens flare halo width
  86198. */
  86199. _this.lensFlareHaloWidth = 0.7;
  86200. /**
  86201. * Based on the lens distortion effect, defines how much the lens flare result
  86202. * is distorted
  86203. */
  86204. _this.lensFlareDistortionStrength = 16.0;
  86205. /**
  86206. * Lens star texture must be used to simulate rays on the flares and is available
  86207. * in the documentation
  86208. */
  86209. _this.lensStarTexture = null;
  86210. /**
  86211. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  86212. * flare effect by taking account of the dirt texture
  86213. */
  86214. _this.lensFlareDirtTexture = null;
  86215. /**
  86216. * Represents the focal length for the depth of field effect
  86217. */
  86218. _this.depthOfFieldDistance = 10.0;
  86219. /**
  86220. * Represents the blur intensity for the blurred part of the depth of field effect
  86221. */
  86222. _this.depthOfFieldBlurWidth = 64.0;
  86223. /**
  86224. * For motion blur, defines how much the image is blurred by the movement
  86225. */
  86226. _this.motionStrength = 1.0;
  86227. /**
  86228. * List of animations for the pipeline (IAnimatable implementation)
  86229. */
  86230. _this.animations = [];
  86231. _this._currentDepthOfFieldSource = null;
  86232. _this._hdrCurrentLuminance = 1.0;
  86233. // Getters and setters
  86234. _this._bloomEnabled = false;
  86235. _this._depthOfFieldEnabled = false;
  86236. _this._vlsEnabled = false;
  86237. _this._lensFlareEnabled = false;
  86238. _this._hdrEnabled = false;
  86239. _this._motionBlurEnabled = false;
  86240. _this._fxaaEnabled = false;
  86241. _this._motionBlurSamples = 64.0;
  86242. _this._volumetricLightStepsCount = 50.0;
  86243. _this._samples = 1;
  86244. _this._cameras = cameras || [];
  86245. // Initialize
  86246. _this._scene = scene;
  86247. _this._basePostProcess = originalPostProcess;
  86248. _this._ratio = ratio;
  86249. // Misc
  86250. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86251. // Finish
  86252. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86253. _this._buildPipeline();
  86254. return _this;
  86255. }
  86256. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  86257. /**
  86258. * @ignore
  86259. * Specifies if the bloom pipeline is enabled
  86260. */
  86261. get: function () {
  86262. return this._bloomEnabled;
  86263. },
  86264. set: function (enabled) {
  86265. if (this._bloomEnabled === enabled) {
  86266. return;
  86267. }
  86268. this._bloomEnabled = enabled;
  86269. this._buildPipeline();
  86270. },
  86271. enumerable: true,
  86272. configurable: true
  86273. });
  86274. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  86275. /**
  86276. * @ignore
  86277. * Specifies if the depth of field pipeline is enabed
  86278. */
  86279. get: function () {
  86280. return this._depthOfFieldEnabled;
  86281. },
  86282. set: function (enabled) {
  86283. if (this._depthOfFieldEnabled === enabled) {
  86284. return;
  86285. }
  86286. this._depthOfFieldEnabled = enabled;
  86287. this._buildPipeline();
  86288. },
  86289. enumerable: true,
  86290. configurable: true
  86291. });
  86292. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  86293. /**
  86294. * @ignore
  86295. * Specifies if the lens flare pipeline is enabed
  86296. */
  86297. get: function () {
  86298. return this._lensFlareEnabled;
  86299. },
  86300. set: function (enabled) {
  86301. if (this._lensFlareEnabled === enabled) {
  86302. return;
  86303. }
  86304. this._lensFlareEnabled = enabled;
  86305. this._buildPipeline();
  86306. },
  86307. enumerable: true,
  86308. configurable: true
  86309. });
  86310. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  86311. /**
  86312. * @ignore
  86313. * Specifies if the HDR pipeline is enabled
  86314. */
  86315. get: function () {
  86316. return this._hdrEnabled;
  86317. },
  86318. set: function (enabled) {
  86319. if (this._hdrEnabled === enabled) {
  86320. return;
  86321. }
  86322. this._hdrEnabled = enabled;
  86323. this._buildPipeline();
  86324. },
  86325. enumerable: true,
  86326. configurable: true
  86327. });
  86328. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  86329. /**
  86330. * @ignore
  86331. * Specifies if the volumetric lights scattering effect is enabled
  86332. */
  86333. get: function () {
  86334. return this._vlsEnabled;
  86335. },
  86336. set: function (enabled) {
  86337. if (this._vlsEnabled === enabled) {
  86338. return;
  86339. }
  86340. if (enabled) {
  86341. var geometry = this._scene.enableGeometryBufferRenderer();
  86342. if (!geometry) {
  86343. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  86344. return;
  86345. }
  86346. }
  86347. this._vlsEnabled = enabled;
  86348. this._buildPipeline();
  86349. },
  86350. enumerable: true,
  86351. configurable: true
  86352. });
  86353. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  86354. /**
  86355. * @ignore
  86356. * Specifies if the motion blur effect is enabled
  86357. */
  86358. get: function () {
  86359. return this._motionBlurEnabled;
  86360. },
  86361. set: function (enabled) {
  86362. if (this._motionBlurEnabled === enabled) {
  86363. return;
  86364. }
  86365. this._motionBlurEnabled = enabled;
  86366. this._buildPipeline();
  86367. },
  86368. enumerable: true,
  86369. configurable: true
  86370. });
  86371. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  86372. /**
  86373. * Specifies if anti-aliasing is enabled
  86374. */
  86375. get: function () {
  86376. return this._fxaaEnabled;
  86377. },
  86378. set: function (enabled) {
  86379. if (this._fxaaEnabled === enabled) {
  86380. return;
  86381. }
  86382. this._fxaaEnabled = enabled;
  86383. this._buildPipeline();
  86384. },
  86385. enumerable: true,
  86386. configurable: true
  86387. });
  86388. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  86389. /**
  86390. * Specifies the number of steps used to calculate the volumetric lights
  86391. * Typically in interval [50, 200]
  86392. */
  86393. get: function () {
  86394. return this._volumetricLightStepsCount;
  86395. },
  86396. set: function (count) {
  86397. if (this.volumetricLightPostProcess) {
  86398. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  86399. }
  86400. this._volumetricLightStepsCount = count;
  86401. },
  86402. enumerable: true,
  86403. configurable: true
  86404. });
  86405. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  86406. /**
  86407. * Specifies the number of samples used for the motion blur effect
  86408. * Typically in interval [16, 64]
  86409. */
  86410. get: function () {
  86411. return this._motionBlurSamples;
  86412. },
  86413. set: function (samples) {
  86414. if (this.motionBlurPostProcess) {
  86415. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  86416. }
  86417. this._motionBlurSamples = samples;
  86418. },
  86419. enumerable: true,
  86420. configurable: true
  86421. });
  86422. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  86423. /**
  86424. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86425. */
  86426. get: function () {
  86427. return this._samples;
  86428. },
  86429. set: function (sampleCount) {
  86430. if (this._samples === sampleCount) {
  86431. return;
  86432. }
  86433. this._samples = sampleCount;
  86434. this._buildPipeline();
  86435. },
  86436. enumerable: true,
  86437. configurable: true
  86438. });
  86439. StandardRenderingPipeline.prototype._buildPipeline = function () {
  86440. var _this = this;
  86441. var ratio = this._ratio;
  86442. var scene = this._scene;
  86443. this._disposePostProcesses();
  86444. this._reset();
  86445. // Create pass post-process
  86446. if (!this._basePostProcess) {
  86447. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  86448. this.originalPostProcess.onApply = function (effect) {
  86449. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  86450. };
  86451. }
  86452. else {
  86453. this.originalPostProcess = this._basePostProcess;
  86454. }
  86455. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  86456. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  86457. }
  86458. this._currentDepthOfFieldSource = this.originalPostProcess;
  86459. if (this._bloomEnabled) {
  86460. // Create down sample X4 post-process
  86461. this._createDownSampleX4PostProcess(scene, ratio / 2);
  86462. // Create bright pass post-process
  86463. this._createBrightPassPostProcess(scene, ratio / 2);
  86464. // Create gaussian blur post-processes (down sampling blurs)
  86465. this._createBlurPostProcesses(scene, ratio / 4, 1);
  86466. // Create texture adder post-process
  86467. this._createTextureAdderPostProcess(scene, ratio);
  86468. // Create depth-of-field source post-process
  86469. 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);
  86470. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  86471. }
  86472. if (this._vlsEnabled) {
  86473. // Create volumetric light
  86474. this._createVolumetricLightPostProcess(scene, ratio);
  86475. // Create volumetric light final post-process
  86476. 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);
  86477. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  86478. }
  86479. if (this._lensFlareEnabled) {
  86480. // Create lens flare post-process
  86481. this._createLensFlarePostProcess(scene, ratio);
  86482. // Create depth-of-field source post-process post lens-flare and disable it now
  86483. 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);
  86484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  86485. }
  86486. if (this._hdrEnabled) {
  86487. // Create luminance
  86488. this._createLuminancePostProcesses(scene, this._floatTextureType);
  86489. // Create HDR
  86490. this._createHdrPostProcess(scene, ratio);
  86491. // Create depth-of-field source post-process post hdr and disable it now
  86492. 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);
  86493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  86494. }
  86495. if (this._depthOfFieldEnabled) {
  86496. // Create gaussian blur used by depth-of-field
  86497. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  86498. // Create depth-of-field post-process
  86499. this._createDepthOfFieldPostProcess(scene, ratio);
  86500. }
  86501. if (this._motionBlurEnabled) {
  86502. // Create motion blur post-process
  86503. this._createMotionBlurPostProcess(scene, ratio);
  86504. }
  86505. if (this._fxaaEnabled) {
  86506. // Create fxaa post-process
  86507. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86508. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  86509. }
  86510. if (this._cameras !== null) {
  86511. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86512. }
  86513. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  86514. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86515. }
  86516. };
  86517. // Down Sample X4 Post-Processs
  86518. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  86519. var _this = this;
  86520. var downSampleX4Offsets = new Array(32);
  86521. 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);
  86522. this.downSampleX4PostProcess.onApply = function (effect) {
  86523. var id = 0;
  86524. var width = _this.downSampleX4PostProcess.width;
  86525. var height = _this.downSampleX4PostProcess.height;
  86526. for (var i = -2; i < 2; i++) {
  86527. for (var j = -2; j < 2; j++) {
  86528. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  86529. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  86530. id += 2;
  86531. }
  86532. }
  86533. effect.setArray2("dsOffsets", downSampleX4Offsets);
  86534. };
  86535. // Add to pipeline
  86536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  86537. };
  86538. // Brightpass Post-Process
  86539. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  86540. var _this = this;
  86541. var brightOffsets = new Array(8);
  86542. 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);
  86543. this.brightPassPostProcess.onApply = function (effect) {
  86544. var sU = (1.0 / _this.brightPassPostProcess.width);
  86545. var sV = (1.0 / _this.brightPassPostProcess.height);
  86546. brightOffsets[0] = -0.5 * sU;
  86547. brightOffsets[1] = 0.5 * sV;
  86548. brightOffsets[2] = 0.5 * sU;
  86549. brightOffsets[3] = 0.5 * sV;
  86550. brightOffsets[4] = -0.5 * sU;
  86551. brightOffsets[5] = -0.5 * sV;
  86552. brightOffsets[6] = 0.5 * sU;
  86553. brightOffsets[7] = -0.5 * sV;
  86554. effect.setArray2("dsOffsets", brightOffsets);
  86555. effect.setFloat("brightThreshold", _this.brightThreshold);
  86556. };
  86557. // Add to pipeline
  86558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  86559. };
  86560. // Create blur H&V post-processes
  86561. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  86562. var _this = this;
  86563. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  86564. var engine = scene.getEngine();
  86565. 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);
  86566. 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);
  86567. blurX.onActivateObservable.add(function () {
  86568. var dw = blurX.width / engine.getRenderWidth();
  86569. blurX.kernel = _this[blurWidthKey] * dw;
  86570. });
  86571. blurY.onActivateObservable.add(function () {
  86572. var dw = blurY.height / engine.getRenderHeight();
  86573. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  86574. });
  86575. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  86576. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  86577. this.blurHPostProcesses.push(blurX);
  86578. this.blurVPostProcesses.push(blurY);
  86579. };
  86580. // Create texture adder post-process
  86581. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  86582. var _this = this;
  86583. 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);
  86584. this.textureAdderPostProcess.onApply = function (effect) {
  86585. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  86586. effect.setTexture("lensSampler", _this.lensTexture);
  86587. effect.setFloat("exposure", _this.exposure);
  86588. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  86589. };
  86590. // Add to pipeline
  86591. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  86592. };
  86593. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  86594. var _this = this;
  86595. var geometryRenderer = scene.enableGeometryBufferRenderer();
  86596. geometryRenderer.enablePosition = true;
  86597. var geometry = geometryRenderer.getGBuffer();
  86598. // Base post-process
  86599. 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));
  86600. var depthValues = BABYLON.Vector2.Zero();
  86601. this.volumetricLightPostProcess.onApply = function (effect) {
  86602. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  86603. var generator = _this.sourceLight.getShadowGenerator();
  86604. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  86605. effect.setTexture("positionSampler", geometry.textures[2]);
  86606. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  86607. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  86608. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  86609. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  86610. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  86611. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  86612. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  86613. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  86614. effect.setVector2("depthValues", depthValues);
  86615. }
  86616. };
  86617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  86618. // Smooth
  86619. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  86620. // Merge
  86621. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  86622. this.volumetricLightMergePostProces.onApply = function (effect) {
  86623. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  86624. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  86625. };
  86626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  86627. };
  86628. // Create luminance
  86629. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  86630. var _this = this;
  86631. // Create luminance
  86632. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  86633. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  86634. var offsets = [];
  86635. this.luminancePostProcess.onApply = function (effect) {
  86636. var sU = (1.0 / _this.luminancePostProcess.width);
  86637. var sV = (1.0 / _this.luminancePostProcess.height);
  86638. offsets[0] = -0.5 * sU;
  86639. offsets[1] = 0.5 * sV;
  86640. offsets[2] = 0.5 * sU;
  86641. offsets[3] = 0.5 * sV;
  86642. offsets[4] = -0.5 * sU;
  86643. offsets[5] = -0.5 * sV;
  86644. offsets[6] = 0.5 * sU;
  86645. offsets[7] = -0.5 * sV;
  86646. effect.setArray2("lumOffsets", offsets);
  86647. };
  86648. // Add to pipeline
  86649. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  86650. // Create down sample luminance
  86651. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  86652. var size = Math.pow(3, i);
  86653. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  86654. if (i === 0) {
  86655. defines += "#define FINAL_DOWN_SAMPLER";
  86656. }
  86657. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  86658. this.luminanceDownSamplePostProcesses.push(postProcess);
  86659. }
  86660. // Create callbacks and add effects
  86661. var lastLuminance = this.luminancePostProcess;
  86662. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  86663. var downSampleOffsets = new Array(18);
  86664. pp.onApply = function (effect) {
  86665. if (!lastLuminance) {
  86666. return;
  86667. }
  86668. var id = 0;
  86669. for (var x = -1; x < 2; x++) {
  86670. for (var y = -1; y < 2; y++) {
  86671. downSampleOffsets[id] = x / lastLuminance.width;
  86672. downSampleOffsets[id + 1] = y / lastLuminance.height;
  86673. id += 2;
  86674. }
  86675. }
  86676. effect.setArray2("dsOffsets", downSampleOffsets);
  86677. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  86678. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86679. lastLuminance = _this.luminancePostProcess;
  86680. }
  86681. else {
  86682. lastLuminance = pp;
  86683. }
  86684. };
  86685. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86686. pp.onAfterRender = function (effect) {
  86687. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  86688. 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);
  86689. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  86690. };
  86691. }
  86692. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  86693. });
  86694. };
  86695. // Create HDR post-process
  86696. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  86697. var _this = this;
  86698. 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);
  86699. var outputLiminance = 1;
  86700. var time = 0;
  86701. var lastTime = 0;
  86702. this.hdrPostProcess.onApply = function (effect) {
  86703. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  86704. time += scene.getEngine().getDeltaTime();
  86705. if (outputLiminance < 0) {
  86706. outputLiminance = _this._hdrCurrentLuminance;
  86707. }
  86708. else {
  86709. var dt = (lastTime - time) / 1000.0;
  86710. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  86711. outputLiminance += _this.hdrDecreaseRate * dt;
  86712. }
  86713. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  86714. outputLiminance -= _this.hdrIncreaseRate * dt;
  86715. }
  86716. else {
  86717. outputLiminance = _this._hdrCurrentLuminance;
  86718. }
  86719. }
  86720. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  86721. effect.setFloat("averageLuminance", outputLiminance);
  86722. lastTime = time;
  86723. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  86724. };
  86725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  86726. };
  86727. // Create lens flare post-process
  86728. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  86729. var _this = this;
  86730. 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);
  86731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  86732. this._createBlurPostProcesses(scene, ratio / 4, 2);
  86733. 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);
  86734. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  86735. var resolution = new BABYLON.Vector2(0, 0);
  86736. // Lens flare
  86737. this.lensFlarePostProcess.onApply = function (effect) {
  86738. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  86739. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  86740. effect.setFloat("strength", _this.lensFlareStrength);
  86741. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  86742. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  86743. // Shift
  86744. resolution.x = _this.lensFlarePostProcess.width;
  86745. resolution.y = _this.lensFlarePostProcess.height;
  86746. effect.setVector2("resolution", resolution);
  86747. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  86748. };
  86749. // Compose
  86750. 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);
  86751. 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);
  86752. this.lensFlareComposePostProcess.onApply = function (effect) {
  86753. if (!_this._scene.activeCamera) {
  86754. return;
  86755. }
  86756. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86757. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  86758. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  86759. // Lens start rotation matrix
  86760. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  86761. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  86762. 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));
  86763. camRot *= 4.0;
  86764. 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);
  86765. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  86766. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  86767. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  86768. };
  86769. };
  86770. // Create depth-of-field post-process
  86771. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  86772. var _this = this;
  86773. 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);
  86774. this.depthOfFieldPostProcess.onApply = function (effect) {
  86775. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86776. effect.setTexture("depthSampler", _this._getDepthTexture());
  86777. effect.setFloat("distance", _this.depthOfFieldDistance);
  86778. };
  86779. // Add to pipeline
  86780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  86781. };
  86782. // Create motion blur post-process
  86783. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  86784. var _this = this;
  86785. 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);
  86786. var motionScale = 0;
  86787. var prevViewProjection = BABYLON.Matrix.Identity();
  86788. var invViewProjection = BABYLON.Matrix.Identity();
  86789. var viewProjection = BABYLON.Matrix.Identity();
  86790. var screenSize = BABYLON.Vector2.Zero();
  86791. this.motionBlurPostProcess.onApply = function (effect) {
  86792. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  86793. viewProjection.invertToRef(invViewProjection);
  86794. effect.setMatrix("inverseViewProjection", invViewProjection);
  86795. effect.setMatrix("prevViewProjection", prevViewProjection);
  86796. prevViewProjection = viewProjection;
  86797. screenSize.x = _this.motionBlurPostProcess.width;
  86798. screenSize.y = _this.motionBlurPostProcess.height;
  86799. effect.setVector2("screenSize", screenSize);
  86800. motionScale = scene.getEngine().getFps() / 60.0;
  86801. effect.setFloat("motionScale", motionScale);
  86802. effect.setFloat("motionStrength", _this.motionStrength);
  86803. effect.setTexture("depthSampler", _this._getDepthTexture());
  86804. };
  86805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  86806. };
  86807. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  86808. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  86809. var renderer = this._scene.enableGeometryBufferRenderer();
  86810. return renderer.getGBuffer().textures[0];
  86811. }
  86812. return this._scene.enableDepthRenderer().getDepthMap();
  86813. };
  86814. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  86815. for (var i = 0; i < this._cameras.length; i++) {
  86816. var camera = this._cameras[i];
  86817. if (this.originalPostProcess) {
  86818. this.originalPostProcess.dispose(camera);
  86819. }
  86820. if (this.downSampleX4PostProcess) {
  86821. this.downSampleX4PostProcess.dispose(camera);
  86822. }
  86823. if (this.brightPassPostProcess) {
  86824. this.brightPassPostProcess.dispose(camera);
  86825. }
  86826. if (this.textureAdderPostProcess) {
  86827. this.textureAdderPostProcess.dispose(camera);
  86828. }
  86829. if (this.textureAdderFinalPostProcess) {
  86830. this.textureAdderFinalPostProcess.dispose(camera);
  86831. }
  86832. if (this.volumetricLightPostProcess) {
  86833. this.volumetricLightPostProcess.dispose(camera);
  86834. }
  86835. if (this.volumetricLightSmoothXPostProcess) {
  86836. this.volumetricLightSmoothXPostProcess.dispose(camera);
  86837. }
  86838. if (this.volumetricLightSmoothYPostProcess) {
  86839. this.volumetricLightSmoothYPostProcess.dispose(camera);
  86840. }
  86841. if (this.volumetricLightMergePostProces) {
  86842. this.volumetricLightMergePostProces.dispose(camera);
  86843. }
  86844. if (this.volumetricLightFinalPostProcess) {
  86845. this.volumetricLightFinalPostProcess.dispose(camera);
  86846. }
  86847. if (this.lensFlarePostProcess) {
  86848. this.lensFlarePostProcess.dispose(camera);
  86849. }
  86850. if (this.lensFlareComposePostProcess) {
  86851. this.lensFlareComposePostProcess.dispose(camera);
  86852. }
  86853. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  86854. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  86855. }
  86856. if (this.luminancePostProcess) {
  86857. this.luminancePostProcess.dispose(camera);
  86858. }
  86859. if (this.hdrPostProcess) {
  86860. this.hdrPostProcess.dispose(camera);
  86861. }
  86862. if (this.hdrFinalPostProcess) {
  86863. this.hdrFinalPostProcess.dispose(camera);
  86864. }
  86865. if (this.depthOfFieldPostProcess) {
  86866. this.depthOfFieldPostProcess.dispose(camera);
  86867. }
  86868. if (this.motionBlurPostProcess) {
  86869. this.motionBlurPostProcess.dispose(camera);
  86870. }
  86871. if (this.fxaaPostProcess) {
  86872. this.fxaaPostProcess.dispose(camera);
  86873. }
  86874. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  86875. this.blurHPostProcesses[j].dispose(camera);
  86876. }
  86877. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  86878. this.blurVPostProcesses[j].dispose(camera);
  86879. }
  86880. }
  86881. this.originalPostProcess = null;
  86882. this.downSampleX4PostProcess = null;
  86883. this.brightPassPostProcess = null;
  86884. this.textureAdderPostProcess = null;
  86885. this.textureAdderFinalPostProcess = null;
  86886. this.volumetricLightPostProcess = null;
  86887. this.volumetricLightSmoothXPostProcess = null;
  86888. this.volumetricLightSmoothYPostProcess = null;
  86889. this.volumetricLightMergePostProces = null;
  86890. this.volumetricLightFinalPostProcess = null;
  86891. this.lensFlarePostProcess = null;
  86892. this.lensFlareComposePostProcess = null;
  86893. this.luminancePostProcess = null;
  86894. this.hdrPostProcess = null;
  86895. this.hdrFinalPostProcess = null;
  86896. this.depthOfFieldPostProcess = null;
  86897. this.motionBlurPostProcess = null;
  86898. this.fxaaPostProcess = null;
  86899. this.luminanceDownSamplePostProcesses = [];
  86900. this.blurHPostProcesses = [];
  86901. this.blurVPostProcesses = [];
  86902. };
  86903. /**
  86904. * Dispose of the pipeline and stop all post processes
  86905. */
  86906. StandardRenderingPipeline.prototype.dispose = function () {
  86907. this._disposePostProcesses();
  86908. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86909. _super.prototype.dispose.call(this);
  86910. };
  86911. /**
  86912. * Serialize the rendering pipeline (Used when exporting)
  86913. * @returns the serialized object
  86914. */
  86915. StandardRenderingPipeline.prototype.serialize = function () {
  86916. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86917. if (this.sourceLight) {
  86918. serializationObject.sourceLightId = this.sourceLight.id;
  86919. }
  86920. serializationObject.customType = "StandardRenderingPipeline";
  86921. return serializationObject;
  86922. };
  86923. /**
  86924. * Parse the serialized pipeline
  86925. * @param source Source pipeline.
  86926. * @param scene The scene to load the pipeline to.
  86927. * @param rootUrl The URL of the serialized pipeline.
  86928. * @returns An instantiated pipeline from the serialized object.
  86929. */
  86930. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86931. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  86932. if (source.sourceLightId) {
  86933. p.sourceLight = scene.getLightByID(source.sourceLightId);
  86934. }
  86935. return p;
  86936. };
  86937. /**
  86938. * Luminance steps
  86939. */
  86940. StandardRenderingPipeline.LuminanceSteps = 6;
  86941. __decorate([
  86942. BABYLON.serialize()
  86943. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  86944. __decorate([
  86945. BABYLON.serialize()
  86946. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  86947. __decorate([
  86948. BABYLON.serialize()
  86949. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  86950. __decorate([
  86951. BABYLON.serialize()
  86952. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  86953. __decorate([
  86954. BABYLON.serializeAsTexture("lensTexture")
  86955. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  86956. __decorate([
  86957. BABYLON.serialize()
  86958. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  86959. __decorate([
  86960. BABYLON.serialize()
  86961. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  86962. __decorate([
  86963. BABYLON.serialize()
  86964. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  86965. __decorate([
  86966. BABYLON.serialize()
  86967. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  86968. __decorate([
  86969. BABYLON.serialize()
  86970. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  86971. __decorate([
  86972. BABYLON.serialize()
  86973. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  86974. __decorate([
  86975. BABYLON.serializeAsTexture("lensColorTexture")
  86976. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  86977. __decorate([
  86978. BABYLON.serialize()
  86979. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  86980. __decorate([
  86981. BABYLON.serialize()
  86982. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  86983. __decorate([
  86984. BABYLON.serialize()
  86985. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  86986. __decorate([
  86987. BABYLON.serialize()
  86988. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  86989. __decorate([
  86990. BABYLON.serializeAsTexture("lensStarTexture")
  86991. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  86992. __decorate([
  86993. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  86994. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  86995. __decorate([
  86996. BABYLON.serialize()
  86997. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  86998. __decorate([
  86999. BABYLON.serialize()
  87000. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  87001. __decorate([
  87002. BABYLON.serialize()
  87003. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  87004. __decorate([
  87005. BABYLON.serialize()
  87006. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  87007. __decorate([
  87008. BABYLON.serialize()
  87009. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  87010. __decorate([
  87011. BABYLON.serialize()
  87012. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  87013. __decorate([
  87014. BABYLON.serialize()
  87015. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  87016. __decorate([
  87017. BABYLON.serialize()
  87018. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  87019. __decorate([
  87020. BABYLON.serialize()
  87021. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  87022. __decorate([
  87023. BABYLON.serialize()
  87024. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  87025. __decorate([
  87026. BABYLON.serialize()
  87027. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  87028. __decorate([
  87029. BABYLON.serialize()
  87030. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  87031. __decorate([
  87032. BABYLON.serialize()
  87033. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  87034. __decorate([
  87035. BABYLON.serialize()
  87036. ], StandardRenderingPipeline.prototype, "samples", null);
  87037. return StandardRenderingPipeline;
  87038. }(BABYLON.PostProcessRenderPipeline));
  87039. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  87040. })(BABYLON || (BABYLON = {}));
  87041. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  87042. var BABYLON;
  87043. (function (BABYLON) {
  87044. /**
  87045. * Fxaa post process
  87046. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  87047. */
  87048. var FxaaPostProcess = /** @class */ (function (_super) {
  87049. __extends(FxaaPostProcess, _super);
  87050. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87051. if (camera === void 0) { camera = null; }
  87052. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87053. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  87054. var defines = _this._getDefines();
  87055. _this.updateEffect(defines);
  87056. _this.onApplyObservable.add(function (effect) {
  87057. var texelSize = _this.texelSize;
  87058. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  87059. });
  87060. return _this;
  87061. }
  87062. FxaaPostProcess.prototype._getDefines = function () {
  87063. var engine = this.getEngine();
  87064. if (!engine) {
  87065. return null;
  87066. }
  87067. var glInfo = engine.getGlInfo();
  87068. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  87069. return "#define MALI 1\n";
  87070. }
  87071. return null;
  87072. };
  87073. return FxaaPostProcess;
  87074. }(BABYLON.PostProcess));
  87075. BABYLON.FxaaPostProcess = FxaaPostProcess;
  87076. })(BABYLON || (BABYLON = {}));
  87077. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  87078. var BABYLON;
  87079. (function (BABYLON) {
  87080. /**
  87081. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  87082. */
  87083. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  87084. __extends(ChromaticAberrationPostProcess, _super);
  87085. /**
  87086. * Creates a new instance ChromaticAberrationPostProcess
  87087. * @param name The name of the effect.
  87088. * @param screenWidth The width of the screen to apply the effect on.
  87089. * @param screenHeight The height of the screen to apply the effect on.
  87090. * @param options The required width/height ratio to downsize to before computing the render pass.
  87091. * @param camera The camera to apply the render pass to.
  87092. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87093. * @param engine The engine which the post process will be applied. (default: current engine)
  87094. * @param reusable If the post process can be reused on the same frame. (default: false)
  87095. * @param textureType Type of textures used when performing the post process. (default: 0)
  87096. * @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)
  87097. */
  87098. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87099. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87100. if (blockCompilation === void 0) { blockCompilation = false; }
  87101. 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;
  87102. /**
  87103. * The amount of seperation of rgb channels (default: 30)
  87104. */
  87105. _this.aberrationAmount = 30;
  87106. /**
  87107. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  87108. */
  87109. _this.radialIntensity = 0;
  87110. /**
  87111. * 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))
  87112. */
  87113. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  87114. /**
  87115. * 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))
  87116. */
  87117. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  87118. _this.onApplyObservable.add(function (effect) {
  87119. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  87120. effect.setFloat('screen_width', screenWidth);
  87121. effect.setFloat('screen_height', screenHeight);
  87122. effect.setFloat('radialIntensity', _this.radialIntensity);
  87123. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  87124. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  87125. });
  87126. return _this;
  87127. }
  87128. return ChromaticAberrationPostProcess;
  87129. }(BABYLON.PostProcess));
  87130. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  87131. })(BABYLON || (BABYLON = {}));
  87132. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  87133. var BABYLON;
  87134. (function (BABYLON) {
  87135. /**
  87136. * The GrainPostProcess adds noise to the image at mid luminance levels
  87137. */
  87138. var GrainPostProcess = /** @class */ (function (_super) {
  87139. __extends(GrainPostProcess, _super);
  87140. /**
  87141. * Creates a new instance of @see GrainPostProcess
  87142. * @param name The name of the effect.
  87143. * @param options The required width/height ratio to downsize to before computing the render pass.
  87144. * @param camera The camera to apply the render pass to.
  87145. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87146. * @param engine The engine which the post process will be applied. (default: current engine)
  87147. * @param reusable If the post process can be reused on the same frame. (default: false)
  87148. * @param textureType Type of textures used when performing the post process. (default: 0)
  87149. * @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)
  87150. */
  87151. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87152. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87153. if (blockCompilation === void 0) { blockCompilation = false; }
  87154. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87155. /**
  87156. * The intensity of the grain added (default: 30)
  87157. */
  87158. _this.intensity = 30;
  87159. /**
  87160. * If the grain should be randomized on every frame
  87161. */
  87162. _this.animated = false;
  87163. _this.onApplyObservable.add(function (effect) {
  87164. effect.setFloat('intensity', _this.intensity);
  87165. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  87166. });
  87167. return _this;
  87168. }
  87169. return GrainPostProcess;
  87170. }(BABYLON.PostProcess));
  87171. BABYLON.GrainPostProcess = GrainPostProcess;
  87172. })(BABYLON || (BABYLON = {}));
  87173. //# sourceMappingURL=babylon.grainPostProcess.js.map
  87174. var BABYLON;
  87175. (function (BABYLON) {
  87176. /**
  87177. * The SharpenPostProcess applies a sharpen kernel to every pixel
  87178. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87179. */
  87180. var SharpenPostProcess = /** @class */ (function (_super) {
  87181. __extends(SharpenPostProcess, _super);
  87182. /**
  87183. * Creates a new instance ConvolutionPostProcess
  87184. * @param name The name of the effect.
  87185. * @param options The required width/height ratio to downsize to before computing the render pass.
  87186. * @param camera The camera to apply the render pass to.
  87187. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87188. * @param engine The engine which the post process will be applied. (default: current engine)
  87189. * @param reusable If the post process can be reused on the same frame. (default: false)
  87190. * @param textureType Type of textures used when performing the post process. (default: 0)
  87191. * @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)
  87192. */
  87193. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87194. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87195. if (blockCompilation === void 0) { blockCompilation = false; }
  87196. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87197. /**
  87198. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  87199. */
  87200. _this.colorAmount = 1.0;
  87201. /**
  87202. * How much sharpness should be applied (default: 0.3)
  87203. */
  87204. _this.edgeAmount = 0.3;
  87205. _this.onApply = function (effect) {
  87206. effect.setFloat2("screenSize", _this.width, _this.height);
  87207. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  87208. };
  87209. return _this;
  87210. }
  87211. return SharpenPostProcess;
  87212. }(BABYLON.PostProcess));
  87213. BABYLON.SharpenPostProcess = SharpenPostProcess;
  87214. })(BABYLON || (BABYLON = {}));
  87215. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  87216. var BABYLON;
  87217. (function (BABYLON) {
  87218. /**
  87219. * The Blur Post Process which blurs an image based on a kernel and direction.
  87220. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  87221. */
  87222. var BlurPostProcess = /** @class */ (function (_super) {
  87223. __extends(BlurPostProcess, _super);
  87224. /**
  87225. * Creates a new instance BlurPostProcess
  87226. * @param name The name of the effect.
  87227. * @param direction The direction in which to blur the image.
  87228. * @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.
  87229. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  87230. * @param camera The camera to apply the render pass to.
  87231. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87232. * @param engine The engine which the post process will be applied. (default: current engine)
  87233. * @param reusable If the post process can be reused on the same frame. (default: false)
  87234. * @param textureType Type of textures used when performing the post process. (default: 0)
  87235. * @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)
  87236. */
  87237. function BlurPostProcess(name,
  87238. /** The direction in which to blur the image. */
  87239. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  87240. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87241. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87242. if (defines === void 0) { defines = ""; }
  87243. if (blockCompilation === void 0) { blockCompilation = false; }
  87244. 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;
  87245. _this.direction = direction;
  87246. _this.blockCompilation = blockCompilation;
  87247. _this._packedFloat = false;
  87248. _this._staticDefines = "";
  87249. _this._staticDefines = defines;
  87250. _this.onApplyObservable.add(function (effect) {
  87251. if (_this._outputTexture) {
  87252. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  87253. }
  87254. else {
  87255. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  87256. }
  87257. });
  87258. _this.kernel = kernel;
  87259. return _this;
  87260. }
  87261. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  87262. /**
  87263. * Gets the length in pixels of the blur sample region
  87264. */
  87265. get: function () {
  87266. return this._idealKernel;
  87267. },
  87268. /**
  87269. * Sets the length in pixels of the blur sample region
  87270. */
  87271. set: function (v) {
  87272. if (this._idealKernel === v) {
  87273. return;
  87274. }
  87275. v = Math.max(v, 1);
  87276. this._idealKernel = v;
  87277. this._kernel = this._nearestBestKernel(v);
  87278. if (!this.blockCompilation) {
  87279. this._updateParameters();
  87280. }
  87281. },
  87282. enumerable: true,
  87283. configurable: true
  87284. });
  87285. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  87286. /**
  87287. * Gets wether or not the blur is unpacking/repacking floats
  87288. */
  87289. get: function () {
  87290. return this._packedFloat;
  87291. },
  87292. /**
  87293. * Sets wether or not the blur needs to unpack/repack floats
  87294. */
  87295. set: function (v) {
  87296. if (this._packedFloat === v) {
  87297. return;
  87298. }
  87299. this._packedFloat = v;
  87300. if (!this.blockCompilation) {
  87301. this._updateParameters();
  87302. }
  87303. },
  87304. enumerable: true,
  87305. configurable: true
  87306. });
  87307. /**
  87308. * Updates the effect with the current post process compile time values and recompiles the shader.
  87309. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87310. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87311. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87312. * @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
  87313. * @param onCompiled Called when the shader has been compiled.
  87314. * @param onError Called if there is an error when compiling a shader.
  87315. */
  87316. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87317. if (defines === void 0) { defines = null; }
  87318. if (uniforms === void 0) { uniforms = null; }
  87319. if (samplers === void 0) { samplers = null; }
  87320. this._updateParameters(onCompiled, onError);
  87321. };
  87322. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  87323. // Generate sampling offsets and weights
  87324. var N = this._kernel;
  87325. var centerIndex = (N - 1) / 2;
  87326. // Generate Gaussian sampling weights over kernel
  87327. var offsets = [];
  87328. var weights = [];
  87329. var totalWeight = 0;
  87330. for (var i = 0; i < N; i++) {
  87331. var u = i / (N - 1);
  87332. var w = this._gaussianWeight(u * 2.0 - 1);
  87333. offsets[i] = (i - centerIndex);
  87334. weights[i] = w;
  87335. totalWeight += w;
  87336. }
  87337. // Normalize weights
  87338. for (var i = 0; i < weights.length; i++) {
  87339. weights[i] /= totalWeight;
  87340. }
  87341. // Optimize: combine samples to take advantage of hardware linear sampling
  87342. // Walk from left to center, combining pairs (symmetrically)
  87343. var linearSamplingWeights = [];
  87344. var linearSamplingOffsets = [];
  87345. var linearSamplingMap = [];
  87346. for (var i = 0; i <= centerIndex; i += 2) {
  87347. var j = Math.min(i + 1, Math.floor(centerIndex));
  87348. var singleCenterSample = i === j;
  87349. if (singleCenterSample) {
  87350. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87351. }
  87352. else {
  87353. var sharedCell = j === centerIndex;
  87354. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  87355. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  87356. if (offsetLinear === 0) {
  87357. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87358. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  87359. }
  87360. else {
  87361. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  87362. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  87363. }
  87364. }
  87365. }
  87366. for (var i = 0; i < linearSamplingMap.length; i++) {
  87367. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  87368. linearSamplingWeights[i] = linearSamplingMap[i].w;
  87369. }
  87370. // Replace with optimized
  87371. offsets = linearSamplingOffsets;
  87372. weights = linearSamplingWeights;
  87373. // Generate shaders
  87374. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  87375. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  87376. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  87377. var defines = "";
  87378. defines += this._staticDefines;
  87379. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  87380. if (this._staticDefines.indexOf("DOF") != -1) {
  87381. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  87382. varyingCount--;
  87383. }
  87384. for (var i = 0; i < varyingCount; i++) {
  87385. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  87386. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  87387. }
  87388. var depCount = 0;
  87389. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  87390. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  87391. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  87392. depCount++;
  87393. }
  87394. if (this.packedFloat) {
  87395. defines += "#define PACKEDFLOAT 1";
  87396. }
  87397. this.blockCompilation = false;
  87398. _super.prototype.updateEffect.call(this, defines, null, null, {
  87399. varyingCount: varyingCount,
  87400. depCount: depCount
  87401. }, onCompiled, onError);
  87402. };
  87403. /**
  87404. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  87405. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  87406. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  87407. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  87408. * The gaps between physical kernels are compensated for in the weighting of the samples
  87409. * @param idealKernel Ideal blur kernel.
  87410. * @return Nearest best kernel.
  87411. */
  87412. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  87413. var v = Math.round(idealKernel);
  87414. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  87415. var k = _a[_i];
  87416. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  87417. return Math.max(k, 3);
  87418. }
  87419. }
  87420. return Math.max(v, 3);
  87421. };
  87422. /**
  87423. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  87424. * @param x The point on the Gaussian distribution to sample.
  87425. * @return the value of the Gaussian function at x.
  87426. */
  87427. BlurPostProcess.prototype._gaussianWeight = function (x) {
  87428. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  87429. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  87430. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  87431. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  87432. // truncated at around 1.3% of peak strength.
  87433. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  87434. var sigma = (1 / 3);
  87435. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  87436. var exponent = -((x * x) / (2.0 * sigma * sigma));
  87437. var weight = (1.0 / denominator) * Math.exp(exponent);
  87438. return weight;
  87439. };
  87440. /**
  87441. * Generates a string that can be used as a floating point number in GLSL.
  87442. * @param x Value to print.
  87443. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  87444. * @return GLSL float string.
  87445. */
  87446. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  87447. if (decimalFigures === void 0) { decimalFigures = 8; }
  87448. return x.toFixed(decimalFigures).replace(/0+$/, '');
  87449. };
  87450. return BlurPostProcess;
  87451. }(BABYLON.PostProcess));
  87452. BABYLON.BlurPostProcess = BlurPostProcess;
  87453. })(BABYLON || (BABYLON = {}));
  87454. //# sourceMappingURL=babylon.blurPostProcess.js.map
  87455. var BABYLON;
  87456. (function (BABYLON) {
  87457. /**
  87458. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  87459. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  87460. * based on samples that have a large difference in distance than the center pixel.
  87461. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87462. */
  87463. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  87464. __extends(DepthOfFieldBlurPostProcess, _super);
  87465. /**
  87466. * Creates a new instance CircleOfConfusionPostProcess
  87467. * @param name The name of the effect.
  87468. * @param scene The scene the effect belongs to.
  87469. * @param direction The direction the blur should be applied.
  87470. * @param kernel The size of the kernel used to blur.
  87471. * @param options The required width/height ratio to downsize to before computing the render pass.
  87472. * @param camera The camera to apply the render pass to.
  87473. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  87474. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  87475. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87476. * @param engine The engine which the post process will be applied. (default: current engine)
  87477. * @param reusable If the post process can be reused on the same frame. (default: false)
  87478. * @param textureType Type of textures used when performing the post process. (default: 0)
  87479. * @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)
  87480. */
  87481. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  87482. if (imageToBlur === void 0) { imageToBlur = null; }
  87483. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87484. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87485. if (blockCompilation === void 0) { blockCompilation = false; }
  87486. 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;
  87487. _this.direction = direction;
  87488. _this.onApplyObservable.add(function (effect) {
  87489. if (imageToBlur != null) {
  87490. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  87491. }
  87492. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87493. if (scene.activeCamera) {
  87494. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87495. }
  87496. });
  87497. return _this;
  87498. }
  87499. return DepthOfFieldBlurPostProcess;
  87500. }(BABYLON.BlurPostProcess));
  87501. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  87502. })(BABYLON || (BABYLON = {}));
  87503. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  87504. var BABYLON;
  87505. (function (BABYLON) {
  87506. /**
  87507. * Options to be set when merging outputs from the default pipeline.
  87508. */
  87509. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  87510. function DepthOfFieldMergePostProcessOptions() {
  87511. }
  87512. return DepthOfFieldMergePostProcessOptions;
  87513. }());
  87514. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  87515. /**
  87516. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87517. */
  87518. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  87519. __extends(DepthOfFieldMergePostProcess, _super);
  87520. /**
  87521. * Creates a new instance of DepthOfFieldMergePostProcess
  87522. * @param name The name of the effect.
  87523. * @param originalFromInput Post process which's input will be used for the merge.
  87524. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  87525. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  87526. * @param options The required width/height ratio to downsize to before computing the render pass.
  87527. * @param camera The camera to apply the render pass to.
  87528. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87529. * @param engine The engine which the post process will be applied. (default: current engine)
  87530. * @param reusable If the post process can be reused on the same frame. (default: false)
  87531. * @param textureType Type of textures used when performing the post process. (default: 0)
  87532. * @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)
  87533. */
  87534. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87535. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87536. if (blockCompilation === void 0) { blockCompilation = false; }
  87537. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87538. _this.blurSteps = blurSteps;
  87539. _this.onApplyObservable.add(function (effect) {
  87540. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87541. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87542. blurSteps.forEach(function (step, index) {
  87543. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  87544. });
  87545. });
  87546. if (!blockCompilation) {
  87547. _this.updateEffect();
  87548. }
  87549. return _this;
  87550. }
  87551. /**
  87552. * Updates the effect with the current post process compile time values and recompiles the shader.
  87553. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87554. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87555. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87556. * @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
  87557. * @param onCompiled Called when the shader has been compiled.
  87558. * @param onError Called if there is an error when compiling a shader.
  87559. */
  87560. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87561. if (defines === void 0) { defines = null; }
  87562. if (uniforms === void 0) { uniforms = null; }
  87563. if (samplers === void 0) { samplers = null; }
  87564. if (!defines) {
  87565. defines = "";
  87566. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  87567. }
  87568. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  87569. };
  87570. return DepthOfFieldMergePostProcess;
  87571. }(BABYLON.PostProcess));
  87572. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  87573. })(BABYLON || (BABYLON = {}));
  87574. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  87575. var BABYLON;
  87576. (function (BABYLON) {
  87577. /**
  87578. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  87579. */
  87580. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  87581. __extends(CircleOfConfusionPostProcess, _super);
  87582. /**
  87583. * Creates a new instance CircleOfConfusionPostProcess
  87584. * @param name The name of the effect.
  87585. * @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.
  87586. * @param options The required width/height ratio to downsize to before computing the render pass.
  87587. * @param camera The camera to apply the render pass to.
  87588. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87589. * @param engine The engine which the post process will be applied. (default: current engine)
  87590. * @param reusable If the post process can be reused on the same frame. (default: false)
  87591. * @param textureType Type of textures used when performing the post process. (default: 0)
  87592. * @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)
  87593. */
  87594. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87596. if (blockCompilation === void 0) { blockCompilation = false; }
  87597. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87598. /**
  87599. * 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.
  87600. */
  87601. _this.lensSize = 50;
  87602. /**
  87603. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87604. */
  87605. _this.fStop = 1.4;
  87606. /**
  87607. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87608. */
  87609. _this.focusDistance = 2000;
  87610. /**
  87611. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  87612. */
  87613. _this.focalLength = 50;
  87614. _this._depthTexture = null;
  87615. _this._depthTexture = depthTexture;
  87616. _this.onApplyObservable.add(function (effect) {
  87617. if (!_this._depthTexture) {
  87618. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  87619. return;
  87620. }
  87621. effect.setTexture("depthSampler", _this._depthTexture);
  87622. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  87623. var aperture = _this.lensSize / _this.fStop;
  87624. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  87625. effect.setFloat('focusDistance', _this.focusDistance);
  87626. effect.setFloat('cocPrecalculation', cocPrecalculation);
  87627. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  87628. });
  87629. return _this;
  87630. }
  87631. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  87632. /**
  87633. * 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.
  87634. */
  87635. set: function (value) {
  87636. this._depthTexture = value;
  87637. },
  87638. enumerable: true,
  87639. configurable: true
  87640. });
  87641. return CircleOfConfusionPostProcess;
  87642. }(BABYLON.PostProcess));
  87643. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  87644. })(BABYLON || (BABYLON = {}));
  87645. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  87646. var BABYLON;
  87647. (function (BABYLON) {
  87648. /**
  87649. * Specifies the level of max blur that should be applied when using the depth of field effect
  87650. */
  87651. var DepthOfFieldEffectBlurLevel;
  87652. (function (DepthOfFieldEffectBlurLevel) {
  87653. /**
  87654. * Subtle blur
  87655. */
  87656. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  87657. /**
  87658. * Medium blur
  87659. */
  87660. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  87661. /**
  87662. * Large blur
  87663. */
  87664. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  87665. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  87666. /**
  87667. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  87668. */
  87669. var DepthOfFieldEffect = /** @class */ (function (_super) {
  87670. __extends(DepthOfFieldEffect, _super);
  87671. /**
  87672. * Creates a new instance DepthOfFieldEffect
  87673. * @param scene The scene the effect belongs to.
  87674. * @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.
  87675. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87676. * @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)
  87677. */
  87678. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  87679. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  87680. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87681. if (blockCompilation === void 0) { blockCompilation = false; }
  87682. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  87683. return _this._effects;
  87684. }, true) || this;
  87685. /**
  87686. * @hidden Internal post processes in depth of field effect
  87687. */
  87688. _this._effects = [];
  87689. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  87690. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87691. // 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)
  87692. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  87693. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87694. _this._depthOfFieldBlurY = [];
  87695. _this._depthOfFieldBlurX = [];
  87696. var blurCount = 1;
  87697. var kernelSize = 15;
  87698. switch (blurLevel) {
  87699. case DepthOfFieldEffectBlurLevel.High: {
  87700. blurCount = 3;
  87701. kernelSize = 51;
  87702. break;
  87703. }
  87704. case DepthOfFieldEffectBlurLevel.Medium: {
  87705. blurCount = 2;
  87706. kernelSize = 31;
  87707. break;
  87708. }
  87709. default: {
  87710. kernelSize = 15;
  87711. blurCount = 1;
  87712. break;
  87713. }
  87714. }
  87715. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  87716. var ratio = 1.0;
  87717. for (var i = 0; i < blurCount; i++) {
  87718. 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);
  87719. blurY.autoClear = false;
  87720. ratio = 0.75 / Math.pow(2, i);
  87721. 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);
  87722. blurX.autoClear = false;
  87723. _this._depthOfFieldBlurY.push(blurY);
  87724. _this._depthOfFieldBlurX.push(blurX);
  87725. }
  87726. // Set all post processes on the effect.
  87727. _this._effects = [_this._circleOfConfusion];
  87728. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  87729. _this._effects.push(_this._depthOfFieldBlurY[i]);
  87730. _this._effects.push(_this._depthOfFieldBlurX[i]);
  87731. }
  87732. // Merge blurred images with original image based on circleOfConfusion
  87733. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87734. _this._dofMerge.autoClear = false;
  87735. _this._effects.push(_this._dofMerge);
  87736. return _this;
  87737. }
  87738. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  87739. get: function () {
  87740. return this._circleOfConfusion.focalLength;
  87741. },
  87742. /**
  87743. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  87744. */
  87745. set: function (value) {
  87746. this._circleOfConfusion.focalLength = value;
  87747. },
  87748. enumerable: true,
  87749. configurable: true
  87750. });
  87751. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  87752. get: function () {
  87753. return this._circleOfConfusion.fStop;
  87754. },
  87755. /**
  87756. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87757. */
  87758. set: function (value) {
  87759. this._circleOfConfusion.fStop = value;
  87760. },
  87761. enumerable: true,
  87762. configurable: true
  87763. });
  87764. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  87765. get: function () {
  87766. return this._circleOfConfusion.focusDistance;
  87767. },
  87768. /**
  87769. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87770. */
  87771. set: function (value) {
  87772. this._circleOfConfusion.focusDistance = value;
  87773. },
  87774. enumerable: true,
  87775. configurable: true
  87776. });
  87777. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  87778. get: function () {
  87779. return this._circleOfConfusion.lensSize;
  87780. },
  87781. /**
  87782. * 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.
  87783. */
  87784. set: function (value) {
  87785. this._circleOfConfusion.lensSize = value;
  87786. },
  87787. enumerable: true,
  87788. configurable: true
  87789. });
  87790. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  87791. /**
  87792. * 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.
  87793. */
  87794. set: function (value) {
  87795. this._circleOfConfusion.depthTexture = value;
  87796. },
  87797. enumerable: true,
  87798. configurable: true
  87799. });
  87800. /**
  87801. * Disposes each of the internal effects for a given camera.
  87802. * @param camera The camera to dispose the effect on.
  87803. */
  87804. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  87805. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87806. this._effects[effectIndex].dispose(camera);
  87807. }
  87808. };
  87809. /**
  87810. * @hidden Internal
  87811. */
  87812. DepthOfFieldEffect.prototype._updateEffects = function () {
  87813. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87814. this._effects[effectIndex].updateEffect();
  87815. }
  87816. };
  87817. /**
  87818. * Internal
  87819. * @returns if all the contained post processes are ready.
  87820. * @hidden
  87821. */
  87822. DepthOfFieldEffect.prototype._isReady = function () {
  87823. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87824. if (!this._effects[effectIndex].isReady()) {
  87825. return false;
  87826. }
  87827. }
  87828. return true;
  87829. };
  87830. return DepthOfFieldEffect;
  87831. }(BABYLON.PostProcessRenderEffect));
  87832. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  87833. })(BABYLON || (BABYLON = {}));
  87834. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  87835. var BABYLON;
  87836. (function (BABYLON) {
  87837. /**
  87838. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87839. */
  87840. var BloomMergePostProcess = /** @class */ (function (_super) {
  87841. __extends(BloomMergePostProcess, _super);
  87842. /**
  87843. * Creates a new instance of @see BloomMergePostProcess
  87844. * @param name The name of the effect.
  87845. * @param originalFromInput Post process which's input will be used for the merge.
  87846. * @param blurred Blurred highlights post process which's output will be used.
  87847. * @param weight Weight of the bloom to be added to the original input.
  87848. * @param options The required width/height ratio to downsize to before computing the render pass.
  87849. * @param camera The camera to apply the render pass to.
  87850. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87851. * @param engine The engine which the post process will be applied. (default: current engine)
  87852. * @param reusable If the post process can be reused on the same frame. (default: false)
  87853. * @param textureType Type of textures used when performing the post process. (default: 0)
  87854. * @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)
  87855. */
  87856. function BloomMergePostProcess(name, originalFromInput, blurred,
  87857. /** Weight of the bloom to be added to the original input. */
  87858. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87859. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87860. if (blockCompilation === void 0) { blockCompilation = false; }
  87861. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87862. _this.weight = weight;
  87863. _this.onApplyObservable.add(function (effect) {
  87864. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87865. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  87866. effect.setFloat("bloomWeight", _this.weight);
  87867. });
  87868. if (!blockCompilation) {
  87869. _this.updateEffect();
  87870. }
  87871. return _this;
  87872. }
  87873. return BloomMergePostProcess;
  87874. }(BABYLON.PostProcess));
  87875. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  87876. })(BABYLON || (BABYLON = {}));
  87877. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  87878. var BABYLON;
  87879. (function (BABYLON) {
  87880. /**
  87881. * 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.
  87882. */
  87883. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  87884. __extends(ExtractHighlightsPostProcess, _super);
  87885. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87886. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87887. if (blockCompilation === void 0) { blockCompilation = false; }
  87888. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87889. /**
  87890. * The luminance threshold, pixels below this value will be set to black.
  87891. */
  87892. _this.threshold = 0.9;
  87893. /** @hidden */
  87894. _this._exposure = 1;
  87895. /**
  87896. * Post process which has the input texture to be used when performing highlight extraction
  87897. * @hidden
  87898. */
  87899. _this._inputPostProcess = null;
  87900. _this.onApplyObservable.add(function (effect) {
  87901. if (_this._inputPostProcess) {
  87902. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  87903. }
  87904. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  87905. effect.setFloat('exposure', _this._exposure);
  87906. });
  87907. return _this;
  87908. }
  87909. return ExtractHighlightsPostProcess;
  87910. }(BABYLON.PostProcess));
  87911. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  87912. })(BABYLON || (BABYLON = {}));
  87913. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  87914. var BABYLON;
  87915. (function (BABYLON) {
  87916. /**
  87917. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  87918. */
  87919. var BloomEffect = /** @class */ (function (_super) {
  87920. __extends(BloomEffect, _super);
  87921. /**
  87922. * Creates a new instance of @see BloomEffect
  87923. * @param scene The scene the effect belongs to.
  87924. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  87925. * @param bloomKernel The size of the kernel to be used when applying the blur.
  87926. * @param bloomWeight The the strength of bloom.
  87927. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87928. * @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)
  87929. */
  87930. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  87931. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87932. if (blockCompilation === void 0) { blockCompilation = false; }
  87933. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  87934. return _this._effects;
  87935. }, true) || this;
  87936. _this.bloomScale = bloomScale;
  87937. /**
  87938. * @hidden Internal
  87939. */
  87940. _this._effects = [];
  87941. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87942. _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);
  87943. _this._blurX.alwaysForcePOT = true;
  87944. _this._blurX.autoClear = false;
  87945. _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);
  87946. _this._blurY.alwaysForcePOT = true;
  87947. _this._blurY.autoClear = false;
  87948. _this.kernel = bloomKernel;
  87949. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  87950. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87951. _this._merge.autoClear = false;
  87952. _this._effects.push(_this._merge);
  87953. return _this;
  87954. }
  87955. Object.defineProperty(BloomEffect.prototype, "threshold", {
  87956. /**
  87957. * The luminance threshold to find bright areas of the image to bloom.
  87958. */
  87959. get: function () {
  87960. return this._downscale.threshold;
  87961. },
  87962. set: function (value) {
  87963. this._downscale.threshold = value;
  87964. },
  87965. enumerable: true,
  87966. configurable: true
  87967. });
  87968. Object.defineProperty(BloomEffect.prototype, "weight", {
  87969. /**
  87970. * The strength of the bloom.
  87971. */
  87972. get: function () {
  87973. return this._merge.weight;
  87974. },
  87975. set: function (value) {
  87976. this._merge.weight = value;
  87977. },
  87978. enumerable: true,
  87979. configurable: true
  87980. });
  87981. Object.defineProperty(BloomEffect.prototype, "kernel", {
  87982. /**
  87983. * Specifies the size of the bloom blur kernel, relative to the final output size
  87984. */
  87985. get: function () {
  87986. return this._blurX.kernel / this.bloomScale;
  87987. },
  87988. set: function (value) {
  87989. this._blurX.kernel = value * this.bloomScale;
  87990. this._blurY.kernel = value * this.bloomScale;
  87991. },
  87992. enumerable: true,
  87993. configurable: true
  87994. });
  87995. /**
  87996. * Disposes each of the internal effects for a given camera.
  87997. * @param camera The camera to dispose the effect on.
  87998. */
  87999. BloomEffect.prototype.disposeEffects = function (camera) {
  88000. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88001. this._effects[effectIndex].dispose(camera);
  88002. }
  88003. };
  88004. /**
  88005. * @hidden Internal
  88006. */
  88007. BloomEffect.prototype._updateEffects = function () {
  88008. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88009. this._effects[effectIndex].updateEffect();
  88010. }
  88011. };
  88012. /**
  88013. * Internal
  88014. * @returns if all the contained post processes are ready.
  88015. * @hidden
  88016. */
  88017. BloomEffect.prototype._isReady = function () {
  88018. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88019. if (!this._effects[effectIndex].isReady()) {
  88020. return false;
  88021. }
  88022. }
  88023. return true;
  88024. };
  88025. return BloomEffect;
  88026. }(BABYLON.PostProcessRenderEffect));
  88027. BABYLON.BloomEffect = BloomEffect;
  88028. })(BABYLON || (BABYLON = {}));
  88029. //# sourceMappingURL=babylon.bloomEffect.js.map
  88030. var BABYLON;
  88031. (function (BABYLON) {
  88032. /**
  88033. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  88034. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  88035. */
  88036. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  88037. __extends(DefaultRenderingPipeline, _super);
  88038. /**
  88039. * @constructor
  88040. * @param name - The rendering pipeline name (default: "")
  88041. * @param hdr - If high dynamic range textures should be used (default: true)
  88042. * @param scene - The scene linked to this pipeline (default: the last created scene)
  88043. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  88044. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  88045. */
  88046. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  88047. if (name === void 0) { name = ""; }
  88048. if (hdr === void 0) { hdr = true; }
  88049. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  88050. if (automaticBuild === void 0) { automaticBuild = true; }
  88051. var _this = _super.call(this, scene.getEngine(), name) || this;
  88052. _this._camerasToBeAttached = [];
  88053. /**
  88054. * ID of the sharpen post process,
  88055. */
  88056. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  88057. /**
  88058. * @ignore
  88059. * ID of the image processing post process;
  88060. */
  88061. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  88062. /**
  88063. * @ignore
  88064. * ID of the Fast Approximate Anti-Aliasing post process;
  88065. */
  88066. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  88067. /**
  88068. * ID of the chromatic aberration post process,
  88069. */
  88070. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  88071. /**
  88072. * ID of the grain post process
  88073. */
  88074. _this.GrainPostProcessId = "GrainPostProcessEffect";
  88075. /**
  88076. * Glow post process which adds a glow to emmisive areas of the image
  88077. */
  88078. _this._glowLayer = null;
  88079. /**
  88080. * Animations which can be used to tweak settings over a period of time
  88081. */
  88082. _this.animations = [];
  88083. _this._imageProcessingConfigurationObserver = null;
  88084. // Values
  88085. _this._sharpenEnabled = false;
  88086. _this._bloomEnabled = false;
  88087. _this._depthOfFieldEnabled = false;
  88088. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  88089. _this._fxaaEnabled = false;
  88090. _this._imageProcessingEnabled = true;
  88091. _this._bloomScale = 0.5;
  88092. _this._chromaticAberrationEnabled = false;
  88093. _this._grainEnabled = false;
  88094. _this._buildAllowed = true;
  88095. _this._resizeObserver = null;
  88096. _this._hardwareScaleLevel = 1.0;
  88097. _this._bloomKernel = 64;
  88098. /**
  88099. * Specifies the weight of the bloom in the final rendering
  88100. */
  88101. _this._bloomWeight = 0.15;
  88102. /**
  88103. * Specifies the luma threshold for the area that will be blurred by the bloom
  88104. */
  88105. _this._bloomThreshold = 0.9;
  88106. _this._samples = 1;
  88107. _this._hasCleared = false;
  88108. _this._prevPostProcess = null;
  88109. _this._prevPrevPostProcess = null;
  88110. _this._depthOfFieldSceneObserver = null;
  88111. _this._cameras = cameras || scene.cameras;
  88112. _this._cameras = _this._cameras.slice();
  88113. _this._camerasToBeAttached = _this._cameras.slice();
  88114. _this._buildAllowed = automaticBuild;
  88115. // Initialize
  88116. _this._scene = scene;
  88117. var caps = _this._scene.getEngine().getCaps();
  88118. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  88119. // Misc
  88120. if (_this._hdr) {
  88121. if (caps.textureHalfFloatRender) {
  88122. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88123. }
  88124. else if (caps.textureFloatRender) {
  88125. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88126. }
  88127. }
  88128. else {
  88129. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88130. }
  88131. // Attach
  88132. scene.postProcessRenderPipelineManager.addPipeline(_this);
  88133. var engine = _this._scene.getEngine();
  88134. // Create post processes before hand so they can be modified before enabled.
  88135. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  88136. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88137. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  88138. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  88139. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  88140. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88141. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  88142. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88143. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  88144. _this._resizeObserver = engine.onResizeObservable.add(function () {
  88145. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  88146. _this.bloomKernel = _this.bloomKernel;
  88147. });
  88148. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  88149. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  88150. });
  88151. _this._buildPipeline();
  88152. return _this;
  88153. }
  88154. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  88155. get: function () {
  88156. return this._sharpenEnabled;
  88157. },
  88158. /**
  88159. * Enable or disable the sharpen process from the pipeline
  88160. */
  88161. set: function (enabled) {
  88162. if (this._sharpenEnabled === enabled) {
  88163. return;
  88164. }
  88165. this._sharpenEnabled = enabled;
  88166. this._buildPipeline();
  88167. },
  88168. enumerable: true,
  88169. configurable: true
  88170. });
  88171. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  88172. /**
  88173. * Specifies the size of the bloom blur kernel, relative to the final output size
  88174. */
  88175. get: function () {
  88176. return this._bloomKernel;
  88177. },
  88178. set: function (value) {
  88179. this._bloomKernel = value;
  88180. this.bloom.kernel = value / this._hardwareScaleLevel;
  88181. },
  88182. enumerable: true,
  88183. configurable: true
  88184. });
  88185. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  88186. get: function () {
  88187. return this._bloomWeight;
  88188. },
  88189. /**
  88190. * The strength of the bloom.
  88191. */
  88192. set: function (value) {
  88193. if (this._bloomWeight === value) {
  88194. return;
  88195. }
  88196. this.bloom.weight = value;
  88197. this._bloomWeight = value;
  88198. },
  88199. enumerable: true,
  88200. configurable: true
  88201. });
  88202. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  88203. get: function () {
  88204. return this._bloomThreshold;
  88205. },
  88206. /**
  88207. * The strength of the bloom.
  88208. */
  88209. set: function (value) {
  88210. if (this._bloomThreshold === value) {
  88211. return;
  88212. }
  88213. this.bloom.threshold = value;
  88214. this._bloomThreshold = value;
  88215. },
  88216. enumerable: true,
  88217. configurable: true
  88218. });
  88219. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  88220. get: function () {
  88221. return this._bloomScale;
  88222. },
  88223. /**
  88224. * The scale of the bloom, lower value will provide better performance.
  88225. */
  88226. set: function (value) {
  88227. if (this._bloomScale === value) {
  88228. return;
  88229. }
  88230. this._bloomScale = value;
  88231. // recreate bloom and dispose old as this setting is not dynamic
  88232. this._rebuildBloom();
  88233. this._buildPipeline();
  88234. },
  88235. enumerable: true,
  88236. configurable: true
  88237. });
  88238. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  88239. get: function () {
  88240. return this._bloomEnabled;
  88241. },
  88242. /**
  88243. * Enable or disable the bloom from the pipeline
  88244. */
  88245. set: function (enabled) {
  88246. if (this._bloomEnabled === enabled) {
  88247. return;
  88248. }
  88249. this._bloomEnabled = enabled;
  88250. this._buildPipeline();
  88251. },
  88252. enumerable: true,
  88253. configurable: true
  88254. });
  88255. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  88256. // recreate bloom and dispose old as this setting is not dynamic
  88257. var oldBloom = this.bloom;
  88258. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  88259. this.bloom.threshold = oldBloom.threshold;
  88260. for (var i = 0; i < this._cameras.length; i++) {
  88261. oldBloom.disposeEffects(this._cameras[i]);
  88262. }
  88263. };
  88264. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  88265. /**
  88266. * If the depth of field is enabled.
  88267. */
  88268. get: function () {
  88269. return this._depthOfFieldEnabled;
  88270. },
  88271. set: function (enabled) {
  88272. if (this._depthOfFieldEnabled === enabled) {
  88273. return;
  88274. }
  88275. this._depthOfFieldEnabled = enabled;
  88276. this._buildPipeline();
  88277. },
  88278. enumerable: true,
  88279. configurable: true
  88280. });
  88281. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  88282. /**
  88283. * Blur level of the depth of field effect. (Higher blur will effect performance)
  88284. */
  88285. get: function () {
  88286. return this._depthOfFieldBlurLevel;
  88287. },
  88288. set: function (value) {
  88289. if (this._depthOfFieldBlurLevel === value) {
  88290. return;
  88291. }
  88292. this._depthOfFieldBlurLevel = value;
  88293. // recreate dof and dispose old as this setting is not dynamic
  88294. var oldDof = this.depthOfField;
  88295. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  88296. this.depthOfField.focalLength = oldDof.focalLength;
  88297. this.depthOfField.focusDistance = oldDof.focusDistance;
  88298. this.depthOfField.fStop = oldDof.fStop;
  88299. this.depthOfField.lensSize = oldDof.lensSize;
  88300. for (var i = 0; i < this._cameras.length; i++) {
  88301. oldDof.disposeEffects(this._cameras[i]);
  88302. }
  88303. this._buildPipeline();
  88304. },
  88305. enumerable: true,
  88306. configurable: true
  88307. });
  88308. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  88309. get: function () {
  88310. return this._fxaaEnabled;
  88311. },
  88312. /**
  88313. * If the anti aliasing is enabled.
  88314. */
  88315. set: function (enabled) {
  88316. if (this._fxaaEnabled === enabled) {
  88317. return;
  88318. }
  88319. this._fxaaEnabled = enabled;
  88320. this._buildPipeline();
  88321. },
  88322. enumerable: true,
  88323. configurable: true
  88324. });
  88325. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  88326. get: function () {
  88327. return this._samples;
  88328. },
  88329. /**
  88330. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  88331. */
  88332. set: function (sampleCount) {
  88333. if (this._samples === sampleCount) {
  88334. return;
  88335. }
  88336. this._samples = sampleCount;
  88337. this._buildPipeline();
  88338. },
  88339. enumerable: true,
  88340. configurable: true
  88341. });
  88342. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  88343. get: function () {
  88344. return this._imageProcessingEnabled;
  88345. },
  88346. /**
  88347. * If image processing is enabled.
  88348. */
  88349. set: function (enabled) {
  88350. if (this._imageProcessingEnabled === enabled) {
  88351. return;
  88352. }
  88353. this._imageProcessingEnabled = enabled;
  88354. this._buildPipeline();
  88355. },
  88356. enumerable: true,
  88357. configurable: true
  88358. });
  88359. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  88360. get: function () {
  88361. return this._glowLayer == null;
  88362. },
  88363. /**
  88364. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  88365. */
  88366. set: function (enabled) {
  88367. if (enabled && !this._glowLayer) {
  88368. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  88369. }
  88370. else if (!enabled && this._glowLayer) {
  88371. this._glowLayer.dispose();
  88372. this._glowLayer = null;
  88373. }
  88374. },
  88375. enumerable: true,
  88376. configurable: true
  88377. });
  88378. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  88379. get: function () {
  88380. return this._chromaticAberrationEnabled;
  88381. },
  88382. /**
  88383. * Enable or disable the chromaticAberration process from the pipeline
  88384. */
  88385. set: function (enabled) {
  88386. if (this._chromaticAberrationEnabled === enabled) {
  88387. return;
  88388. }
  88389. this._chromaticAberrationEnabled = enabled;
  88390. this._buildPipeline();
  88391. },
  88392. enumerable: true,
  88393. configurable: true
  88394. });
  88395. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  88396. get: function () {
  88397. return this._grainEnabled;
  88398. },
  88399. /**
  88400. * Enable or disable the grain process from the pipeline
  88401. */
  88402. set: function (enabled) {
  88403. if (this._grainEnabled === enabled) {
  88404. return;
  88405. }
  88406. this._grainEnabled = enabled;
  88407. this._buildPipeline();
  88408. },
  88409. enumerable: true,
  88410. configurable: true
  88411. });
  88412. /**
  88413. * Force the compilation of the entire pipeline.
  88414. */
  88415. DefaultRenderingPipeline.prototype.prepare = function () {
  88416. var previousState = this._buildAllowed;
  88417. this._buildAllowed = true;
  88418. this._buildPipeline();
  88419. this._buildAllowed = previousState;
  88420. };
  88421. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  88422. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  88423. if (this._hasCleared) {
  88424. postProcess.autoClear = false;
  88425. }
  88426. else {
  88427. postProcess.autoClear = true;
  88428. this._scene.autoClear = false;
  88429. this._hasCleared = true;
  88430. }
  88431. if (!skipTextureSharing) {
  88432. if (this._prevPrevPostProcess) {
  88433. postProcess.shareOutputWith(this._prevPrevPostProcess);
  88434. }
  88435. else {
  88436. postProcess.useOwnOutput();
  88437. }
  88438. if (this._prevPostProcess) {
  88439. this._prevPrevPostProcess = this._prevPostProcess;
  88440. }
  88441. this._prevPostProcess = postProcess;
  88442. }
  88443. };
  88444. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  88445. var _this = this;
  88446. if (!this._buildAllowed) {
  88447. return;
  88448. }
  88449. this._scene.autoClear = true;
  88450. var engine = this._scene.getEngine();
  88451. this._disposePostProcesses();
  88452. if (this._cameras !== null) {
  88453. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88454. // get back cameras to be used to reattach pipeline
  88455. this._cameras = this._camerasToBeAttached.slice();
  88456. }
  88457. this._reset();
  88458. this._prevPostProcess = null;
  88459. this._prevPrevPostProcess = null;
  88460. this._hasCleared = false;
  88461. if (this.depthOfFieldEnabled) {
  88462. // Multi camera suport
  88463. if (this._cameras.length > 1) {
  88464. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  88465. var camera = _a[_i];
  88466. var depthRenderer = this._scene.enableDepthRenderer(camera);
  88467. depthRenderer.useOnlyInActiveCamera = true;
  88468. }
  88469. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  88470. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  88471. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  88472. }
  88473. });
  88474. }
  88475. else {
  88476. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88477. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  88478. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  88479. }
  88480. if (!this.depthOfField._isReady()) {
  88481. this.depthOfField._updateEffects();
  88482. }
  88483. this.addEffect(this.depthOfField);
  88484. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  88485. }
  88486. else {
  88487. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88488. }
  88489. if (this.bloomEnabled) {
  88490. if (!this.bloom._isReady()) {
  88491. this.bloom._updateEffects();
  88492. }
  88493. this.addEffect(this.bloom);
  88494. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  88495. }
  88496. if (this._imageProcessingEnabled) {
  88497. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88498. if (this._hdr) {
  88499. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  88500. this._setAutoClearAndTextureSharing(this.imageProcessing);
  88501. }
  88502. else {
  88503. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  88504. }
  88505. }
  88506. if (this.sharpenEnabled) {
  88507. if (!this.sharpen.isReady()) {
  88508. this.sharpen.updateEffect();
  88509. }
  88510. this.addEffect(this._sharpenEffect);
  88511. this._setAutoClearAndTextureSharing(this.sharpen);
  88512. }
  88513. if (this.grainEnabled) {
  88514. if (!this.grain.isReady()) {
  88515. this.grain.updateEffect();
  88516. }
  88517. this.addEffect(this._grainEffect);
  88518. this._setAutoClearAndTextureSharing(this.grain);
  88519. }
  88520. if (this.chromaticAberrationEnabled) {
  88521. if (!this.chromaticAberration.isReady()) {
  88522. this.chromaticAberration.updateEffect();
  88523. }
  88524. this.addEffect(this._chromaticAberrationEffect);
  88525. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  88526. }
  88527. if (this.fxaaEnabled) {
  88528. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88529. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  88530. this._setAutoClearAndTextureSharing(this.fxaa, true);
  88531. }
  88532. if (this._cameras !== null) {
  88533. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  88534. }
  88535. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  88536. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  88537. }
  88538. };
  88539. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  88540. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  88541. for (var i = 0; i < this._cameras.length; i++) {
  88542. var camera = this._cameras[i];
  88543. if (this.imageProcessing) {
  88544. this.imageProcessing.dispose(camera);
  88545. }
  88546. if (this.fxaa) {
  88547. this.fxaa.dispose(camera);
  88548. }
  88549. // These are created in the constructor and should not be disposed on every pipeline change
  88550. if (disposeNonRecreated) {
  88551. if (this.sharpen) {
  88552. this.sharpen.dispose(camera);
  88553. }
  88554. if (this.depthOfField) {
  88555. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88556. this.depthOfField.disposeEffects(camera);
  88557. }
  88558. if (this.bloom) {
  88559. this.bloom.disposeEffects(camera);
  88560. }
  88561. if (this.chromaticAberration) {
  88562. this.chromaticAberration.dispose(camera);
  88563. }
  88564. if (this.grain) {
  88565. this.grain.dispose(camera);
  88566. }
  88567. if (this._glowLayer) {
  88568. this._glowLayer.dispose();
  88569. }
  88570. }
  88571. }
  88572. this.imageProcessing = null;
  88573. this.fxaa = null;
  88574. if (disposeNonRecreated) {
  88575. this.sharpen = null;
  88576. this._sharpenEffect = null;
  88577. this.depthOfField = null;
  88578. this.bloom = null;
  88579. this.chromaticAberration = null;
  88580. this._chromaticAberrationEffect = null;
  88581. this.grain = null;
  88582. this._grainEffect = null;
  88583. this._glowLayer = null;
  88584. }
  88585. };
  88586. /**
  88587. * Adds a camera to the pipeline
  88588. * @param camera the camera to be added
  88589. */
  88590. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  88591. this._camerasToBeAttached.push(camera);
  88592. this._buildPipeline();
  88593. };
  88594. /**
  88595. * Removes a camera from the pipeline
  88596. * @param camera the camera to remove
  88597. */
  88598. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  88599. var index = this._camerasToBeAttached.indexOf(camera);
  88600. this._camerasToBeAttached.splice(index, 1);
  88601. this._buildPipeline();
  88602. };
  88603. /**
  88604. * Dispose of the pipeline and stop all post processes
  88605. */
  88606. DefaultRenderingPipeline.prototype.dispose = function () {
  88607. this._disposePostProcesses(true);
  88608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88609. this._scene.autoClear = true;
  88610. if (this._resizeObserver) {
  88611. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  88612. this._resizeObserver = null;
  88613. }
  88614. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  88615. _super.prototype.dispose.call(this);
  88616. };
  88617. /**
  88618. * Serialize the rendering pipeline (Used when exporting)
  88619. * @returns the serialized object
  88620. */
  88621. DefaultRenderingPipeline.prototype.serialize = function () {
  88622. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88623. serializationObject.customType = "DefaultRenderingPipeline";
  88624. return serializationObject;
  88625. };
  88626. /**
  88627. * Parse the serialized pipeline
  88628. * @param source Source pipeline.
  88629. * @param scene The scene to load the pipeline to.
  88630. * @param rootUrl The URL of the serialized pipeline.
  88631. * @returns An instantiated pipeline from the serialized object.
  88632. */
  88633. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  88634. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  88635. };
  88636. __decorate([
  88637. BABYLON.serialize()
  88638. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  88639. __decorate([
  88640. BABYLON.serialize()
  88641. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  88642. __decorate([
  88643. BABYLON.serialize()
  88644. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  88645. __decorate([
  88646. BABYLON.serialize()
  88647. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  88648. __decorate([
  88649. BABYLON.serialize()
  88650. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  88651. __decorate([
  88652. BABYLON.serialize()
  88653. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  88654. __decorate([
  88655. BABYLON.serialize()
  88656. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  88657. __decorate([
  88658. BABYLON.serialize()
  88659. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  88660. __decorate([
  88661. BABYLON.serialize()
  88662. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  88663. __decorate([
  88664. BABYLON.serialize()
  88665. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  88666. __decorate([
  88667. BABYLON.serialize()
  88668. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  88669. __decorate([
  88670. BABYLON.serialize()
  88671. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  88672. __decorate([
  88673. BABYLON.serialize()
  88674. ], DefaultRenderingPipeline.prototype, "samples", null);
  88675. __decorate([
  88676. BABYLON.serialize()
  88677. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  88678. __decorate([
  88679. BABYLON.serialize()
  88680. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  88681. __decorate([
  88682. BABYLON.serialize()
  88683. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  88684. __decorate([
  88685. BABYLON.serialize()
  88686. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  88687. return DefaultRenderingPipeline;
  88688. }(BABYLON.PostProcessRenderPipeline));
  88689. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  88690. })(BABYLON || (BABYLON = {}));
  88691. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  88692. var BABYLON;
  88693. (function (BABYLON) {
  88694. /**
  88695. * @hidden
  88696. */
  88697. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  88698. __extends(ImageProcessingConfigurationDefines, _super);
  88699. function ImageProcessingConfigurationDefines() {
  88700. var _this = _super.call(this) || this;
  88701. _this.IMAGEPROCESSING = false;
  88702. _this.VIGNETTE = false;
  88703. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88704. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88705. _this.TONEMAPPING = false;
  88706. _this.TONEMAPPING_ACES = false;
  88707. _this.CONTRAST = false;
  88708. _this.COLORCURVES = false;
  88709. _this.COLORGRADING = false;
  88710. _this.COLORGRADING3D = false;
  88711. _this.SAMPLER3DGREENDEPTH = false;
  88712. _this.SAMPLER3DBGRMAP = false;
  88713. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88714. _this.EXPOSURE = false;
  88715. _this.rebuild();
  88716. return _this;
  88717. }
  88718. return ImageProcessingConfigurationDefines;
  88719. }(BABYLON.MaterialDefines));
  88720. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  88721. /**
  88722. * This groups together the common properties used for image processing either in direct forward pass
  88723. * or through post processing effect depending on the use of the image processing pipeline in your scene
  88724. * or not.
  88725. */
  88726. var ImageProcessingConfiguration = /** @class */ (function () {
  88727. function ImageProcessingConfiguration() {
  88728. /**
  88729. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  88730. */
  88731. this.colorCurves = new BABYLON.ColorCurves();
  88732. this._colorCurvesEnabled = false;
  88733. this._colorGradingEnabled = false;
  88734. this._colorGradingWithGreenDepth = true;
  88735. this._colorGradingBGR = true;
  88736. /** @hidden */
  88737. this._exposure = 1.0;
  88738. this._toneMappingEnabled = false;
  88739. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  88740. this._contrast = 1.0;
  88741. /**
  88742. * Vignette stretch size.
  88743. */
  88744. this.vignetteStretch = 0;
  88745. /**
  88746. * Vignette centre X Offset.
  88747. */
  88748. this.vignetteCentreX = 0;
  88749. /**
  88750. * Vignette centre Y Offset.
  88751. */
  88752. this.vignetteCentreY = 0;
  88753. /**
  88754. * Vignette weight or intensity of the vignette effect.
  88755. */
  88756. this.vignetteWeight = 1.5;
  88757. /**
  88758. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88759. * if vignetteEnabled is set to true.
  88760. */
  88761. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88762. /**
  88763. * Camera field of view used by the Vignette effect.
  88764. */
  88765. this.vignetteCameraFov = 0.5;
  88766. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  88767. this._vignetteEnabled = false;
  88768. this._applyByPostProcess = false;
  88769. this._isEnabled = true;
  88770. /**
  88771. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  88772. */
  88773. this.onUpdateParameters = new BABYLON.Observable();
  88774. }
  88775. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  88776. /**
  88777. * Gets wether the color curves effect is enabled.
  88778. */
  88779. get: function () {
  88780. return this._colorCurvesEnabled;
  88781. },
  88782. /**
  88783. * Sets wether the color curves effect is enabled.
  88784. */
  88785. set: function (value) {
  88786. if (this._colorCurvesEnabled === value) {
  88787. return;
  88788. }
  88789. this._colorCurvesEnabled = value;
  88790. this._updateParameters();
  88791. },
  88792. enumerable: true,
  88793. configurable: true
  88794. });
  88795. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  88796. /**
  88797. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88798. */
  88799. get: function () {
  88800. return this._colorGradingTexture;
  88801. },
  88802. /**
  88803. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88804. */
  88805. set: function (value) {
  88806. if (this._colorGradingTexture === value) {
  88807. return;
  88808. }
  88809. this._colorGradingTexture = value;
  88810. this._updateParameters();
  88811. },
  88812. enumerable: true,
  88813. configurable: true
  88814. });
  88815. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  88816. /**
  88817. * Gets wether the color grading effect is enabled.
  88818. */
  88819. get: function () {
  88820. return this._colorGradingEnabled;
  88821. },
  88822. /**
  88823. * Sets wether the color grading effect is enabled.
  88824. */
  88825. set: function (value) {
  88826. if (this._colorGradingEnabled === value) {
  88827. return;
  88828. }
  88829. this._colorGradingEnabled = value;
  88830. this._updateParameters();
  88831. },
  88832. enumerable: true,
  88833. configurable: true
  88834. });
  88835. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  88836. /**
  88837. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  88838. */
  88839. get: function () {
  88840. return this._colorGradingWithGreenDepth;
  88841. },
  88842. /**
  88843. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  88844. */
  88845. set: function (value) {
  88846. if (this._colorGradingWithGreenDepth === value) {
  88847. return;
  88848. }
  88849. this._colorGradingWithGreenDepth = value;
  88850. this._updateParameters();
  88851. },
  88852. enumerable: true,
  88853. configurable: true
  88854. });
  88855. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  88856. /**
  88857. * Gets wether the color grading texture contains BGR values.
  88858. */
  88859. get: function () {
  88860. return this._colorGradingBGR;
  88861. },
  88862. /**
  88863. * Sets wether the color grading texture contains BGR values.
  88864. */
  88865. set: function (value) {
  88866. if (this._colorGradingBGR === value) {
  88867. return;
  88868. }
  88869. this._colorGradingBGR = value;
  88870. this._updateParameters();
  88871. },
  88872. enumerable: true,
  88873. configurable: true
  88874. });
  88875. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  88876. /**
  88877. * Gets the Exposure used in the effect.
  88878. */
  88879. get: function () {
  88880. return this._exposure;
  88881. },
  88882. /**
  88883. * Sets the Exposure used in the effect.
  88884. */
  88885. set: function (value) {
  88886. if (this._exposure === value) {
  88887. return;
  88888. }
  88889. this._exposure = value;
  88890. this._updateParameters();
  88891. },
  88892. enumerable: true,
  88893. configurable: true
  88894. });
  88895. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  88896. /**
  88897. * Gets wether the tone mapping effect is enabled.
  88898. */
  88899. get: function () {
  88900. return this._toneMappingEnabled;
  88901. },
  88902. /**
  88903. * Sets wether the tone mapping effect is enabled.
  88904. */
  88905. set: function (value) {
  88906. if (this._toneMappingEnabled === value) {
  88907. return;
  88908. }
  88909. this._toneMappingEnabled = value;
  88910. this._updateParameters();
  88911. },
  88912. enumerable: true,
  88913. configurable: true
  88914. });
  88915. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  88916. /**
  88917. * Gets the type of tone mapping effect.
  88918. */
  88919. get: function () {
  88920. return this._toneMappingType;
  88921. },
  88922. /**
  88923. * Sets the type of tone mapping effect used in BabylonJS.
  88924. */
  88925. set: function (value) {
  88926. if (this._toneMappingType === value) {
  88927. return;
  88928. }
  88929. this._toneMappingType = value;
  88930. this._updateParameters();
  88931. },
  88932. enumerable: true,
  88933. configurable: true
  88934. });
  88935. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  88936. /**
  88937. * Gets the contrast used in the effect.
  88938. */
  88939. get: function () {
  88940. return this._contrast;
  88941. },
  88942. /**
  88943. * Sets the contrast used in the effect.
  88944. */
  88945. set: function (value) {
  88946. if (this._contrast === value) {
  88947. return;
  88948. }
  88949. this._contrast = value;
  88950. this._updateParameters();
  88951. },
  88952. enumerable: true,
  88953. configurable: true
  88954. });
  88955. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  88956. /**
  88957. * Gets the vignette blend mode allowing different kind of effect.
  88958. */
  88959. get: function () {
  88960. return this._vignetteBlendMode;
  88961. },
  88962. /**
  88963. * Sets the vignette blend mode allowing different kind of effect.
  88964. */
  88965. set: function (value) {
  88966. if (this._vignetteBlendMode === value) {
  88967. return;
  88968. }
  88969. this._vignetteBlendMode = value;
  88970. this._updateParameters();
  88971. },
  88972. enumerable: true,
  88973. configurable: true
  88974. });
  88975. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  88976. /**
  88977. * Gets wether the vignette effect is enabled.
  88978. */
  88979. get: function () {
  88980. return this._vignetteEnabled;
  88981. },
  88982. /**
  88983. * Sets wether the vignette effect is enabled.
  88984. */
  88985. set: function (value) {
  88986. if (this._vignetteEnabled === value) {
  88987. return;
  88988. }
  88989. this._vignetteEnabled = value;
  88990. this._updateParameters();
  88991. },
  88992. enumerable: true,
  88993. configurable: true
  88994. });
  88995. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  88996. /**
  88997. * Gets wether the image processing is applied through a post process or not.
  88998. */
  88999. get: function () {
  89000. return this._applyByPostProcess;
  89001. },
  89002. /**
  89003. * Sets wether the image processing is applied through a post process or not.
  89004. */
  89005. set: function (value) {
  89006. if (this._applyByPostProcess === value) {
  89007. return;
  89008. }
  89009. this._applyByPostProcess = value;
  89010. this._updateParameters();
  89011. },
  89012. enumerable: true,
  89013. configurable: true
  89014. });
  89015. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  89016. /**
  89017. * Gets wether the image processing is enabled or not.
  89018. */
  89019. get: function () {
  89020. return this._isEnabled;
  89021. },
  89022. /**
  89023. * Sets wether the image processing is enabled or not.
  89024. */
  89025. set: function (value) {
  89026. if (this._isEnabled === value) {
  89027. return;
  89028. }
  89029. this._isEnabled = value;
  89030. this._updateParameters();
  89031. },
  89032. enumerable: true,
  89033. configurable: true
  89034. });
  89035. /**
  89036. * Method called each time the image processing information changes requires to recompile the effect.
  89037. */
  89038. ImageProcessingConfiguration.prototype._updateParameters = function () {
  89039. this.onUpdateParameters.notifyObservers(this);
  89040. };
  89041. /**
  89042. * Gets the current class name.
  89043. * @return "ImageProcessingConfiguration"
  89044. */
  89045. ImageProcessingConfiguration.prototype.getClassName = function () {
  89046. return "ImageProcessingConfiguration";
  89047. };
  89048. /**
  89049. * Prepare the list of uniforms associated with the Image Processing effects.
  89050. * @param uniforms The list of uniforms used in the effect
  89051. * @param defines the list of defines currently in use
  89052. */
  89053. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  89054. if (defines.EXPOSURE) {
  89055. uniforms.push("exposureLinear");
  89056. }
  89057. if (defines.CONTRAST) {
  89058. uniforms.push("contrast");
  89059. }
  89060. if (defines.COLORGRADING) {
  89061. uniforms.push("colorTransformSettings");
  89062. }
  89063. if (defines.VIGNETTE) {
  89064. uniforms.push("vInverseScreenSize");
  89065. uniforms.push("vignetteSettings1");
  89066. uniforms.push("vignetteSettings2");
  89067. }
  89068. if (defines.COLORCURVES) {
  89069. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  89070. }
  89071. };
  89072. /**
  89073. * Prepare the list of samplers associated with the Image Processing effects.
  89074. * @param samplersList The list of uniforms used in the effect
  89075. * @param defines the list of defines currently in use
  89076. */
  89077. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  89078. if (defines.COLORGRADING) {
  89079. samplersList.push("txColorTransform");
  89080. }
  89081. };
  89082. /**
  89083. * Prepare the list of defines associated to the shader.
  89084. * @param defines the list of defines to complete
  89085. * @param forPostProcess Define if we are currently in post process mode or not
  89086. */
  89087. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  89088. if (forPostProcess === void 0) { forPostProcess = false; }
  89089. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  89090. defines.VIGNETTE = false;
  89091. defines.TONEMAPPING = false;
  89092. defines.TONEMAPPING_ACES = false;
  89093. defines.CONTRAST = false;
  89094. defines.EXPOSURE = false;
  89095. defines.COLORCURVES = false;
  89096. defines.COLORGRADING = false;
  89097. defines.COLORGRADING3D = false;
  89098. defines.IMAGEPROCESSING = false;
  89099. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  89100. return;
  89101. }
  89102. defines.VIGNETTE = this.vignetteEnabled;
  89103. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  89104. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  89105. defines.TONEMAPPING = this.toneMappingEnabled;
  89106. switch (this._toneMappingType) {
  89107. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  89108. defines.TONEMAPPING_ACES = true;
  89109. break;
  89110. }
  89111. defines.CONTRAST = (this.contrast !== 1.0);
  89112. defines.EXPOSURE = (this.exposure !== 1.0);
  89113. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  89114. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  89115. if (defines.COLORGRADING) {
  89116. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  89117. }
  89118. else {
  89119. defines.COLORGRADING3D = false;
  89120. }
  89121. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  89122. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  89123. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  89124. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  89125. };
  89126. /**
  89127. * Returns true if all the image processing information are ready.
  89128. * @returns True if ready, otherwise, false
  89129. */
  89130. ImageProcessingConfiguration.prototype.isReady = function () {
  89131. // Color Grading texure can not be none blocking.
  89132. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  89133. };
  89134. /**
  89135. * Binds the image processing to the shader.
  89136. * @param effect The effect to bind to
  89137. * @param aspectRatio Define the current aspect ratio of the effect
  89138. */
  89139. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  89140. if (aspectRatio === void 0) { aspectRatio = 1; }
  89141. // Color Curves
  89142. if (this._colorCurvesEnabled && this.colorCurves) {
  89143. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  89144. }
  89145. // Vignette
  89146. if (this._vignetteEnabled) {
  89147. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  89148. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  89149. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  89150. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  89151. var vignetteScaleX = vignetteScaleY * aspectRatio;
  89152. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  89153. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  89154. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  89155. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  89156. var vignettePower = -2.0 * this.vignetteWeight;
  89157. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  89158. }
  89159. // Exposure
  89160. effect.setFloat("exposureLinear", this.exposure);
  89161. // Contrast
  89162. effect.setFloat("contrast", this.contrast);
  89163. // Color transform settings
  89164. if (this.colorGradingTexture) {
  89165. effect.setTexture("txColorTransform", this.colorGradingTexture);
  89166. var textureSize = this.colorGradingTexture.getSize().height;
  89167. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  89168. 0.5 / textureSize, // textureOffset
  89169. textureSize, // textureSize
  89170. this.colorGradingTexture.level // weight
  89171. );
  89172. }
  89173. };
  89174. /**
  89175. * Clones the current image processing instance.
  89176. * @return The cloned image processing
  89177. */
  89178. ImageProcessingConfiguration.prototype.clone = function () {
  89179. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  89180. };
  89181. /**
  89182. * Serializes the current image processing instance to a json representation.
  89183. * @return a JSON representation
  89184. */
  89185. ImageProcessingConfiguration.prototype.serialize = function () {
  89186. return BABYLON.SerializationHelper.Serialize(this);
  89187. };
  89188. /**
  89189. * Parses the image processing from a json representation.
  89190. * @param source the JSON source to parse
  89191. * @return The parsed image processing
  89192. */
  89193. ImageProcessingConfiguration.Parse = function (source) {
  89194. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  89195. };
  89196. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  89197. /**
  89198. * Used to apply the vignette as a mix with the pixel color.
  89199. */
  89200. get: function () {
  89201. return this._VIGNETTEMODE_MULTIPLY;
  89202. },
  89203. enumerable: true,
  89204. configurable: true
  89205. });
  89206. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  89207. /**
  89208. * Used to apply the vignette as a replacement of the pixel color.
  89209. */
  89210. get: function () {
  89211. return this._VIGNETTEMODE_OPAQUE;
  89212. },
  89213. enumerable: true,
  89214. configurable: true
  89215. });
  89216. /**
  89217. * Default tone mapping applied in BabylonJS.
  89218. */
  89219. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  89220. /**
  89221. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  89222. * to other engines rendering to increase portability.
  89223. */
  89224. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  89225. // Static constants associated to the image processing.
  89226. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  89227. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  89228. __decorate([
  89229. BABYLON.serializeAsColorCurves()
  89230. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  89231. __decorate([
  89232. BABYLON.serialize()
  89233. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  89234. __decorate([
  89235. BABYLON.serializeAsTexture("colorGradingTexture")
  89236. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  89237. __decorate([
  89238. BABYLON.serialize()
  89239. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  89240. __decorate([
  89241. BABYLON.serialize()
  89242. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  89243. __decorate([
  89244. BABYLON.serialize()
  89245. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  89246. __decorate([
  89247. BABYLON.serialize()
  89248. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  89249. __decorate([
  89250. BABYLON.serialize()
  89251. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  89252. __decorate([
  89253. BABYLON.serialize()
  89254. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  89255. __decorate([
  89256. BABYLON.serialize()
  89257. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  89258. __decorate([
  89259. BABYLON.serialize()
  89260. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  89261. __decorate([
  89262. BABYLON.serialize()
  89263. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  89264. __decorate([
  89265. BABYLON.serialize()
  89266. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  89267. __decorate([
  89268. BABYLON.serialize()
  89269. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  89270. __decorate([
  89271. BABYLON.serializeAsColor4()
  89272. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  89273. __decorate([
  89274. BABYLON.serialize()
  89275. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  89276. __decorate([
  89277. BABYLON.serialize()
  89278. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  89279. __decorate([
  89280. BABYLON.serialize()
  89281. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  89282. __decorate([
  89283. BABYLON.serialize()
  89284. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  89285. __decorate([
  89286. BABYLON.serialize()
  89287. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  89288. return ImageProcessingConfiguration;
  89289. }());
  89290. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  89291. })(BABYLON || (BABYLON = {}));
  89292. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  89293. var BABYLON;
  89294. (function (BABYLON) {
  89295. /**
  89296. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  89297. * It can help converting any input color in a desired output one. This can then be used to create effects
  89298. * from sepia, black and white to sixties or futuristic rendering...
  89299. *
  89300. * The only supported format is currently 3dl.
  89301. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  89302. */
  89303. var ColorGradingTexture = /** @class */ (function (_super) {
  89304. __extends(ColorGradingTexture, _super);
  89305. /**
  89306. * Instantiates a ColorGradingTexture from the following parameters.
  89307. *
  89308. * @param url The location of the color gradind data (currently only supporting 3dl)
  89309. * @param scene The scene the texture will be used in
  89310. */
  89311. function ColorGradingTexture(url, scene) {
  89312. var _this = _super.call(this, scene) || this;
  89313. if (!url) {
  89314. return _this;
  89315. }
  89316. _this._engine = scene.getEngine();
  89317. _this._textureMatrix = BABYLON.Matrix.Identity();
  89318. _this.name = url;
  89319. _this.url = url;
  89320. _this.hasAlpha = false;
  89321. _this.isCube = false;
  89322. _this.is3D = _this._engine.webGLVersion > 1;
  89323. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89324. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89325. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89326. _this.anisotropicFilteringLevel = 1;
  89327. _this._texture = _this._getFromCache(url, true);
  89328. if (!_this._texture) {
  89329. if (!scene.useDelayedTextureLoading) {
  89330. _this.loadTexture();
  89331. }
  89332. else {
  89333. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89334. }
  89335. }
  89336. return _this;
  89337. }
  89338. /**
  89339. * Returns the texture matrix used in most of the material.
  89340. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  89341. */
  89342. ColorGradingTexture.prototype.getTextureMatrix = function () {
  89343. return this._textureMatrix;
  89344. };
  89345. /**
  89346. * Occurs when the file being loaded is a .3dl LUT file.
  89347. */
  89348. ColorGradingTexture.prototype.load3dlTexture = function () {
  89349. var engine = this._engine;
  89350. var texture;
  89351. if (engine.webGLVersion === 1) {
  89352. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89353. }
  89354. else {
  89355. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89356. }
  89357. this._texture = texture;
  89358. var callback = function (text) {
  89359. if (typeof text !== "string") {
  89360. return;
  89361. }
  89362. var data = null;
  89363. var tempData = null;
  89364. var line;
  89365. var lines = text.split('\n');
  89366. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  89367. var maxColor = 0;
  89368. for (var i = 0; i < lines.length; i++) {
  89369. line = lines[i];
  89370. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  89371. continue;
  89372. }
  89373. if (line.indexOf('#') === 0) {
  89374. continue;
  89375. }
  89376. var words = line.split(" ");
  89377. if (size === 0) {
  89378. // Number of space + one
  89379. size = words.length;
  89380. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  89381. tempData = new Float32Array(size * size * size * 4);
  89382. continue;
  89383. }
  89384. if (size != 0) {
  89385. var r = Math.max(parseInt(words[0]), 0);
  89386. var g = Math.max(parseInt(words[1]), 0);
  89387. var b = Math.max(parseInt(words[2]), 0);
  89388. maxColor = Math.max(r, maxColor);
  89389. maxColor = Math.max(g, maxColor);
  89390. maxColor = Math.max(b, maxColor);
  89391. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  89392. if (tempData) {
  89393. tempData[pixelStorageIndex + 0] = r;
  89394. tempData[pixelStorageIndex + 1] = g;
  89395. tempData[pixelStorageIndex + 2] = b;
  89396. }
  89397. // Keep for reference in case of back compat problems.
  89398. // pixelIndexSlice++;
  89399. // if (pixelIndexSlice % size == 0) {
  89400. // pixelIndexH++;
  89401. // pixelIndexSlice = 0;
  89402. // if (pixelIndexH % size == 0) {
  89403. // pixelIndexW++;
  89404. // pixelIndexH = 0;
  89405. // }
  89406. // }
  89407. pixelIndexH++;
  89408. if (pixelIndexH % size == 0) {
  89409. pixelIndexSlice++;
  89410. pixelIndexH = 0;
  89411. if (pixelIndexSlice % size == 0) {
  89412. pixelIndexW++;
  89413. pixelIndexSlice = 0;
  89414. }
  89415. }
  89416. }
  89417. }
  89418. if (tempData && data) {
  89419. for (var i = 0; i < tempData.length; i++) {
  89420. if (i > 0 && (i + 1) % 4 === 0) {
  89421. data[i] = 255;
  89422. }
  89423. else {
  89424. var value = tempData[i];
  89425. data[i] = (value / maxColor * 255);
  89426. }
  89427. }
  89428. }
  89429. if (texture.is3D) {
  89430. texture.updateSize(size, size, size);
  89431. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89432. }
  89433. else {
  89434. texture.updateSize(size * size, size);
  89435. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89436. }
  89437. };
  89438. var scene = this.getScene();
  89439. if (scene) {
  89440. scene._loadFile(this.url, callback);
  89441. }
  89442. else {
  89443. this._engine._loadFile(this.url, callback);
  89444. }
  89445. return this._texture;
  89446. };
  89447. /**
  89448. * Starts the loading process of the texture.
  89449. */
  89450. ColorGradingTexture.prototype.loadTexture = function () {
  89451. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  89452. this.load3dlTexture();
  89453. }
  89454. };
  89455. /**
  89456. * Clones the color gradind texture.
  89457. */
  89458. ColorGradingTexture.prototype.clone = function () {
  89459. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  89460. // Base texture
  89461. newTexture.level = this.level;
  89462. return newTexture;
  89463. };
  89464. /**
  89465. * Called during delayed load for textures.
  89466. */
  89467. ColorGradingTexture.prototype.delayLoad = function () {
  89468. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89469. return;
  89470. }
  89471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89472. this._texture = this._getFromCache(this.url, true);
  89473. if (!this._texture) {
  89474. this.loadTexture();
  89475. }
  89476. };
  89477. /**
  89478. * Parses a color grading texture serialized by Babylon.
  89479. * @param parsedTexture The texture information being parsedTexture
  89480. * @param scene The scene to load the texture in
  89481. * @param rootUrl The root url of the data assets to load
  89482. * @return A color gradind texture
  89483. */
  89484. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89485. var texture = null;
  89486. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89487. texture = new ColorGradingTexture(parsedTexture.name, scene);
  89488. texture.name = parsedTexture.name;
  89489. texture.level = parsedTexture.level;
  89490. }
  89491. return texture;
  89492. };
  89493. /**
  89494. * Serializes the LUT texture to json format.
  89495. */
  89496. ColorGradingTexture.prototype.serialize = function () {
  89497. if (!this.name) {
  89498. return null;
  89499. }
  89500. var serializationObject = {};
  89501. serializationObject.name = this.name;
  89502. serializationObject.level = this.level;
  89503. serializationObject.customType = "BABYLON.ColorGradingTexture";
  89504. return serializationObject;
  89505. };
  89506. /**
  89507. * Empty line regex stored for GC.
  89508. */
  89509. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  89510. return ColorGradingTexture;
  89511. }(BABYLON.BaseTexture));
  89512. BABYLON.ColorGradingTexture = ColorGradingTexture;
  89513. })(BABYLON || (BABYLON = {}));
  89514. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  89515. var BABYLON;
  89516. (function (BABYLON) {
  89517. /**
  89518. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89519. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89520. * 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;
  89521. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89522. */
  89523. var ColorCurves = /** @class */ (function () {
  89524. function ColorCurves() {
  89525. this._dirty = true;
  89526. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  89527. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  89528. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89529. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  89530. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89531. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  89532. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  89533. this._globalHue = 30;
  89534. this._globalDensity = 0;
  89535. this._globalSaturation = 0;
  89536. this._globalExposure = 0;
  89537. this._highlightsHue = 30;
  89538. this._highlightsDensity = 0;
  89539. this._highlightsSaturation = 0;
  89540. this._highlightsExposure = 0;
  89541. this._midtonesHue = 30;
  89542. this._midtonesDensity = 0;
  89543. this._midtonesSaturation = 0;
  89544. this._midtonesExposure = 0;
  89545. this._shadowsHue = 30;
  89546. this._shadowsDensity = 0;
  89547. this._shadowsSaturation = 0;
  89548. this._shadowsExposure = 0;
  89549. }
  89550. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  89551. /**
  89552. * Gets the global Hue value.
  89553. * 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).
  89554. */
  89555. get: function () {
  89556. return this._globalHue;
  89557. },
  89558. /**
  89559. * Sets the global Hue value.
  89560. * 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).
  89561. */
  89562. set: function (value) {
  89563. this._globalHue = value;
  89564. this._dirty = true;
  89565. },
  89566. enumerable: true,
  89567. configurable: true
  89568. });
  89569. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  89570. /**
  89571. * Gets the global Density value.
  89572. * 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.
  89573. * Values less than zero provide a filter of opposite hue.
  89574. */
  89575. get: function () {
  89576. return this._globalDensity;
  89577. },
  89578. /**
  89579. * Sets the global Density value.
  89580. * 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.
  89581. * Values less than zero provide a filter of opposite hue.
  89582. */
  89583. set: function (value) {
  89584. this._globalDensity = value;
  89585. this._dirty = true;
  89586. },
  89587. enumerable: true,
  89588. configurable: true
  89589. });
  89590. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  89591. /**
  89592. * Gets the global Saturation value.
  89593. * 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.
  89594. */
  89595. get: function () {
  89596. return this._globalSaturation;
  89597. },
  89598. /**
  89599. * Sets the global Saturation value.
  89600. * 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.
  89601. */
  89602. set: function (value) {
  89603. this._globalSaturation = value;
  89604. this._dirty = true;
  89605. },
  89606. enumerable: true,
  89607. configurable: true
  89608. });
  89609. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  89610. /**
  89611. * Gets the global Exposure value.
  89612. * 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.
  89613. */
  89614. get: function () {
  89615. return this._globalExposure;
  89616. },
  89617. /**
  89618. * Sets the global Exposure value.
  89619. * 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.
  89620. */
  89621. set: function (value) {
  89622. this._globalExposure = value;
  89623. this._dirty = true;
  89624. },
  89625. enumerable: true,
  89626. configurable: true
  89627. });
  89628. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  89629. /**
  89630. * Gets the highlights Hue value.
  89631. * 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).
  89632. */
  89633. get: function () {
  89634. return this._highlightsHue;
  89635. },
  89636. /**
  89637. * Sets the highlights Hue value.
  89638. * 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).
  89639. */
  89640. set: function (value) {
  89641. this._highlightsHue = value;
  89642. this._dirty = true;
  89643. },
  89644. enumerable: true,
  89645. configurable: true
  89646. });
  89647. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  89648. /**
  89649. * Gets the highlights Density value.
  89650. * 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.
  89651. * Values less than zero provide a filter of opposite hue.
  89652. */
  89653. get: function () {
  89654. return this._highlightsDensity;
  89655. },
  89656. /**
  89657. * Sets the highlights Density value.
  89658. * 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.
  89659. * Values less than zero provide a filter of opposite hue.
  89660. */
  89661. set: function (value) {
  89662. this._highlightsDensity = value;
  89663. this._dirty = true;
  89664. },
  89665. enumerable: true,
  89666. configurable: true
  89667. });
  89668. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  89669. /**
  89670. * Gets the highlights Saturation value.
  89671. * 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.
  89672. */
  89673. get: function () {
  89674. return this._highlightsSaturation;
  89675. },
  89676. /**
  89677. * Sets the highlights Saturation value.
  89678. * 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.
  89679. */
  89680. set: function (value) {
  89681. this._highlightsSaturation = value;
  89682. this._dirty = true;
  89683. },
  89684. enumerable: true,
  89685. configurable: true
  89686. });
  89687. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  89688. /**
  89689. * Gets the highlights Exposure value.
  89690. * 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.
  89691. */
  89692. get: function () {
  89693. return this._highlightsExposure;
  89694. },
  89695. /**
  89696. * Sets the highlights Exposure value.
  89697. * 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.
  89698. */
  89699. set: function (value) {
  89700. this._highlightsExposure = value;
  89701. this._dirty = true;
  89702. },
  89703. enumerable: true,
  89704. configurable: true
  89705. });
  89706. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  89707. /**
  89708. * Gets the midtones Hue value.
  89709. * 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).
  89710. */
  89711. get: function () {
  89712. return this._midtonesHue;
  89713. },
  89714. /**
  89715. * Sets the midtones Hue value.
  89716. * 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).
  89717. */
  89718. set: function (value) {
  89719. this._midtonesHue = value;
  89720. this._dirty = true;
  89721. },
  89722. enumerable: true,
  89723. configurable: true
  89724. });
  89725. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  89726. /**
  89727. * Gets the midtones Density value.
  89728. * 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.
  89729. * Values less than zero provide a filter of opposite hue.
  89730. */
  89731. get: function () {
  89732. return this._midtonesDensity;
  89733. },
  89734. /**
  89735. * Sets the midtones Density value.
  89736. * 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.
  89737. * Values less than zero provide a filter of opposite hue.
  89738. */
  89739. set: function (value) {
  89740. this._midtonesDensity = value;
  89741. this._dirty = true;
  89742. },
  89743. enumerable: true,
  89744. configurable: true
  89745. });
  89746. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  89747. /**
  89748. * Gets the midtones Saturation value.
  89749. * 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.
  89750. */
  89751. get: function () {
  89752. return this._midtonesSaturation;
  89753. },
  89754. /**
  89755. * Sets the midtones Saturation value.
  89756. * 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.
  89757. */
  89758. set: function (value) {
  89759. this._midtonesSaturation = value;
  89760. this._dirty = true;
  89761. },
  89762. enumerable: true,
  89763. configurable: true
  89764. });
  89765. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  89766. /**
  89767. * Gets the midtones Exposure value.
  89768. * 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.
  89769. */
  89770. get: function () {
  89771. return this._midtonesExposure;
  89772. },
  89773. /**
  89774. * Sets the midtones Exposure value.
  89775. * 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.
  89776. */
  89777. set: function (value) {
  89778. this._midtonesExposure = value;
  89779. this._dirty = true;
  89780. },
  89781. enumerable: true,
  89782. configurable: true
  89783. });
  89784. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  89785. /**
  89786. * Gets the shadows Hue value.
  89787. * 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).
  89788. */
  89789. get: function () {
  89790. return this._shadowsHue;
  89791. },
  89792. /**
  89793. * Sets the shadows Hue value.
  89794. * 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).
  89795. */
  89796. set: function (value) {
  89797. this._shadowsHue = value;
  89798. this._dirty = true;
  89799. },
  89800. enumerable: true,
  89801. configurable: true
  89802. });
  89803. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  89804. /**
  89805. * Gets the shadows Density value.
  89806. * 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.
  89807. * Values less than zero provide a filter of opposite hue.
  89808. */
  89809. get: function () {
  89810. return this._shadowsDensity;
  89811. },
  89812. /**
  89813. * Sets the shadows Density value.
  89814. * 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.
  89815. * Values less than zero provide a filter of opposite hue.
  89816. */
  89817. set: function (value) {
  89818. this._shadowsDensity = value;
  89819. this._dirty = true;
  89820. },
  89821. enumerable: true,
  89822. configurable: true
  89823. });
  89824. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  89825. /**
  89826. * Gets the shadows Saturation value.
  89827. * 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.
  89828. */
  89829. get: function () {
  89830. return this._shadowsSaturation;
  89831. },
  89832. /**
  89833. * Sets the shadows Saturation value.
  89834. * 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.
  89835. */
  89836. set: function (value) {
  89837. this._shadowsSaturation = value;
  89838. this._dirty = true;
  89839. },
  89840. enumerable: true,
  89841. configurable: true
  89842. });
  89843. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  89844. /**
  89845. * Gets the shadows Exposure value.
  89846. * 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.
  89847. */
  89848. get: function () {
  89849. return this._shadowsExposure;
  89850. },
  89851. /**
  89852. * Sets the shadows Exposure value.
  89853. * 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.
  89854. */
  89855. set: function (value) {
  89856. this._shadowsExposure = value;
  89857. this._dirty = true;
  89858. },
  89859. enumerable: true,
  89860. configurable: true
  89861. });
  89862. /**
  89863. * Returns the class name
  89864. * @returns The class name
  89865. */
  89866. ColorCurves.prototype.getClassName = function () {
  89867. return "ColorCurves";
  89868. };
  89869. /**
  89870. * Binds the color curves to the shader.
  89871. * @param colorCurves The color curve to bind
  89872. * @param effect The effect to bind to
  89873. * @param positiveUniform The positive uniform shader parameter
  89874. * @param neutralUniform The neutral uniform shader parameter
  89875. * @param negativeUniform The negative uniform shader parameter
  89876. */
  89877. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  89878. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  89879. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  89880. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  89881. if (colorCurves._dirty) {
  89882. colorCurves._dirty = false;
  89883. // Fill in global info.
  89884. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  89885. // Compute highlights info.
  89886. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  89887. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  89888. // Compute midtones info.
  89889. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  89890. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  89891. // Compute shadows info.
  89892. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  89893. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  89894. // Compute deltas (neutral is midtones).
  89895. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  89896. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  89897. }
  89898. if (effect) {
  89899. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  89900. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  89901. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  89902. }
  89903. };
  89904. /**
  89905. * Prepare the list of uniforms associated with the ColorCurves effects.
  89906. * @param uniformsList The list of uniforms used in the effect
  89907. */
  89908. ColorCurves.PrepareUniforms = function (uniformsList) {
  89909. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  89910. };
  89911. /**
  89912. * Returns color grading data based on a hue, density, saturation and exposure value.
  89913. * @param filterHue The hue of the color filter.
  89914. * @param filterDensity The density of the color filter.
  89915. * @param saturation The saturation.
  89916. * @param exposure The exposure.
  89917. * @param result The result data container.
  89918. */
  89919. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  89920. if (hue == null) {
  89921. return;
  89922. }
  89923. hue = ColorCurves.clamp(hue, 0, 360);
  89924. density = ColorCurves.clamp(density, -100, 100);
  89925. saturation = ColorCurves.clamp(saturation, -100, 100);
  89926. exposure = ColorCurves.clamp(exposure, -100, 100);
  89927. // Remap the slider/config filter density with non-linear mapping and also scale by half
  89928. // so that the maximum filter density is only 50% control. This provides fine control
  89929. // for small values and reasonable range.
  89930. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  89931. density *= 0.5;
  89932. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  89933. if (density < 0) {
  89934. density *= -1;
  89935. hue = (hue + 180) % 360;
  89936. }
  89937. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  89938. result.scaleToRef(2, result);
  89939. result.a = 1 + 0.01 * saturation;
  89940. };
  89941. /**
  89942. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  89943. * @param value The input slider value in range [-100,100].
  89944. * @returns Adjusted value.
  89945. */
  89946. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  89947. value /= 100;
  89948. var x = Math.abs(value);
  89949. x = Math.pow(x, 2);
  89950. if (value < 0) {
  89951. x *= -1;
  89952. }
  89953. x *= 100;
  89954. return x;
  89955. };
  89956. /**
  89957. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  89958. * @param hue The hue (H) input.
  89959. * @param saturation The saturation (S) input.
  89960. * @param brightness The brightness (B) input.
  89961. * @result An RGBA color represented as Vector4.
  89962. */
  89963. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  89964. var h = ColorCurves.clamp(hue, 0, 360);
  89965. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  89966. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  89967. if (s === 0) {
  89968. result.r = v;
  89969. result.g = v;
  89970. result.b = v;
  89971. }
  89972. else {
  89973. // sector 0 to 5
  89974. h /= 60;
  89975. var i = Math.floor(h);
  89976. // fractional part of h
  89977. var f = h - i;
  89978. var p = v * (1 - s);
  89979. var q = v * (1 - s * f);
  89980. var t = v * (1 - s * (1 - f));
  89981. switch (i) {
  89982. case 0:
  89983. result.r = v;
  89984. result.g = t;
  89985. result.b = p;
  89986. break;
  89987. case 1:
  89988. result.r = q;
  89989. result.g = v;
  89990. result.b = p;
  89991. break;
  89992. case 2:
  89993. result.r = p;
  89994. result.g = v;
  89995. result.b = t;
  89996. break;
  89997. case 3:
  89998. result.r = p;
  89999. result.g = q;
  90000. result.b = v;
  90001. break;
  90002. case 4:
  90003. result.r = t;
  90004. result.g = p;
  90005. result.b = v;
  90006. break;
  90007. default: // case 5:
  90008. result.r = v;
  90009. result.g = p;
  90010. result.b = q;
  90011. break;
  90012. }
  90013. }
  90014. result.a = 1;
  90015. };
  90016. /**
  90017. * Returns a value clamped between min and max
  90018. * @param value The value to clamp
  90019. * @param min The minimum of value
  90020. * @param max The maximum of value
  90021. * @returns The clamped value.
  90022. */
  90023. ColorCurves.clamp = function (value, min, max) {
  90024. return Math.min(Math.max(value, min), max);
  90025. };
  90026. /**
  90027. * Clones the current color curve instance.
  90028. * @return The cloned curves
  90029. */
  90030. ColorCurves.prototype.clone = function () {
  90031. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  90032. };
  90033. /**
  90034. * Serializes the current color curve instance to a json representation.
  90035. * @return a JSON representation
  90036. */
  90037. ColorCurves.prototype.serialize = function () {
  90038. return BABYLON.SerializationHelper.Serialize(this);
  90039. };
  90040. /**
  90041. * Parses the color curve from a json representation.
  90042. * @param source the JSON source to parse
  90043. * @return The parsed curves
  90044. */
  90045. ColorCurves.Parse = function (source) {
  90046. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  90047. };
  90048. __decorate([
  90049. BABYLON.serialize()
  90050. ], ColorCurves.prototype, "_globalHue", void 0);
  90051. __decorate([
  90052. BABYLON.serialize()
  90053. ], ColorCurves.prototype, "_globalDensity", void 0);
  90054. __decorate([
  90055. BABYLON.serialize()
  90056. ], ColorCurves.prototype, "_globalSaturation", void 0);
  90057. __decorate([
  90058. BABYLON.serialize()
  90059. ], ColorCurves.prototype, "_globalExposure", void 0);
  90060. __decorate([
  90061. BABYLON.serialize()
  90062. ], ColorCurves.prototype, "_highlightsHue", void 0);
  90063. __decorate([
  90064. BABYLON.serialize()
  90065. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  90066. __decorate([
  90067. BABYLON.serialize()
  90068. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  90069. __decorate([
  90070. BABYLON.serialize()
  90071. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  90072. __decorate([
  90073. BABYLON.serialize()
  90074. ], ColorCurves.prototype, "_midtonesHue", void 0);
  90075. __decorate([
  90076. BABYLON.serialize()
  90077. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  90078. __decorate([
  90079. BABYLON.serialize()
  90080. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  90081. __decorate([
  90082. BABYLON.serialize()
  90083. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  90084. return ColorCurves;
  90085. }());
  90086. BABYLON.ColorCurves = ColorCurves;
  90087. })(BABYLON || (BABYLON = {}));
  90088. //# sourceMappingURL=babylon.colorCurves.js.map
  90089. var BABYLON;
  90090. (function (BABYLON) {
  90091. /**
  90092. * Post process which applies a refractin texture
  90093. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90094. */
  90095. var RefractionPostProcess = /** @class */ (function (_super) {
  90096. __extends(RefractionPostProcess, _super);
  90097. /**
  90098. * Initializes the RefractionPostProcess
  90099. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90100. * @param name The name of the effect.
  90101. * @param refractionTextureUrl Url of the refraction texture to use
  90102. * @param color the base color of the refraction (used to taint the rendering)
  90103. * @param depth simulated refraction depth
  90104. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  90105. * @param camera The camera to apply the render pass to.
  90106. * @param options The required width/height ratio to downsize to before computing the render pass.
  90107. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90108. * @param engine The engine which the post process will be applied. (default: current engine)
  90109. * @param reusable If the post process can be reused on the same frame. (default: false)
  90110. */
  90111. function RefractionPostProcess(name, refractionTextureUrl,
  90112. /** the base color of the refraction (used to taint the rendering) */
  90113. color,
  90114. /** simulated refraction depth */
  90115. depth,
  90116. /** the coefficient of the base color (0 to remove base color tainting) */
  90117. colorLevel, options, camera, samplingMode, engine, reusable) {
  90118. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  90119. _this.color = color;
  90120. _this.depth = depth;
  90121. _this.colorLevel = colorLevel;
  90122. _this._ownRefractionTexture = true;
  90123. _this.onActivateObservable.add(function (cam) {
  90124. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  90125. });
  90126. _this.onApplyObservable.add(function (effect) {
  90127. effect.setColor3("baseColor", _this.color);
  90128. effect.setFloat("depth", _this.depth);
  90129. effect.setFloat("colorLevel", _this.colorLevel);
  90130. effect.setTexture("refractionSampler", _this._refTexture);
  90131. });
  90132. return _this;
  90133. }
  90134. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  90135. /**
  90136. * Gets or sets the refraction texture
  90137. * Please note that you are responsible for disposing the texture if you set it manually
  90138. */
  90139. get: function () {
  90140. return this._refTexture;
  90141. },
  90142. set: function (value) {
  90143. if (this._refTexture && this._ownRefractionTexture) {
  90144. this._refTexture.dispose();
  90145. }
  90146. this._refTexture = value;
  90147. this._ownRefractionTexture = false;
  90148. },
  90149. enumerable: true,
  90150. configurable: true
  90151. });
  90152. // Methods
  90153. /**
  90154. * Disposes of the post process
  90155. * @param camera Camera to dispose post process on
  90156. */
  90157. RefractionPostProcess.prototype.dispose = function (camera) {
  90158. if (this._refTexture && this._ownRefractionTexture) {
  90159. this._refTexture.dispose();
  90160. this._refTexture = null;
  90161. }
  90162. _super.prototype.dispose.call(this, camera);
  90163. };
  90164. return RefractionPostProcess;
  90165. }(BABYLON.PostProcess));
  90166. BABYLON.RefractionPostProcess = RefractionPostProcess;
  90167. })(BABYLON || (BABYLON = {}));
  90168. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  90169. var BABYLON;
  90170. (function (BABYLON) {
  90171. /**
  90172. * Post process used to render in black and white
  90173. */
  90174. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  90175. __extends(BlackAndWhitePostProcess, _super);
  90176. /**
  90177. * Creates a black and white post process
  90178. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  90179. * @param name The name of the effect.
  90180. * @param options The required width/height ratio to downsize to before computing the render pass.
  90181. * @param camera The camera to apply the render pass to.
  90182. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90183. * @param engine The engine which the post process will be applied. (default: current engine)
  90184. * @param reusable If the post process can be reused on the same frame. (default: false)
  90185. */
  90186. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  90187. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  90188. /**
  90189. * Linear about to convert he result to black and white (default: 1)
  90190. */
  90191. _this.degree = 1;
  90192. _this.onApplyObservable.add(function (effect) {
  90193. effect.setFloat("degree", _this.degree);
  90194. });
  90195. return _this;
  90196. }
  90197. return BlackAndWhitePostProcess;
  90198. }(BABYLON.PostProcess));
  90199. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  90200. })(BABYLON || (BABYLON = {}));
  90201. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  90202. var BABYLON;
  90203. (function (BABYLON) {
  90204. /**
  90205. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  90206. * input texture to perform effects such as edge detection or sharpening
  90207. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  90208. */
  90209. var ConvolutionPostProcess = /** @class */ (function (_super) {
  90210. __extends(ConvolutionPostProcess, _super);
  90211. /**
  90212. * Creates a new instance ConvolutionPostProcess
  90213. * @param name The name of the effect.
  90214. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  90215. * @param options The required width/height ratio to downsize to before computing the render pass.
  90216. * @param camera The camera to apply the render pass to.
  90217. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90218. * @param engine The engine which the post process will be applied. (default: current engine)
  90219. * @param reusable If the post process can be reused on the same frame. (default: false)
  90220. * @param textureType Type of textures used when performing the post process. (default: 0)
  90221. */
  90222. function ConvolutionPostProcess(name,
  90223. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  90224. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  90225. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90226. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90227. _this.kernel = kernel;
  90228. _this.onApply = function (effect) {
  90229. effect.setFloat2("screenSize", _this.width, _this.height);
  90230. effect.setArray("kernel", _this.kernel);
  90231. };
  90232. return _this;
  90233. }
  90234. // Statics
  90235. /**
  90236. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90237. */
  90238. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  90239. /**
  90240. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90241. */
  90242. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  90243. /**
  90244. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90245. */
  90246. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  90247. /**
  90248. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90249. */
  90250. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  90251. /**
  90252. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90253. */
  90254. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  90255. /**
  90256. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90257. */
  90258. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  90259. return ConvolutionPostProcess;
  90260. }(BABYLON.PostProcess));
  90261. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  90262. })(BABYLON || (BABYLON = {}));
  90263. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  90264. var BABYLON;
  90265. (function (BABYLON) {
  90266. /**
  90267. * Applies a kernel filter to the image
  90268. */
  90269. var FilterPostProcess = /** @class */ (function (_super) {
  90270. __extends(FilterPostProcess, _super);
  90271. /**
  90272. *
  90273. * @param name The name of the effect.
  90274. * @param kernelMatrix The matrix to be applied to the image
  90275. * @param options The required width/height ratio to downsize to before computing the render pass.
  90276. * @param camera The camera to apply the render pass to.
  90277. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90278. * @param engine The engine which the post process will be applied. (default: current engine)
  90279. * @param reusable If the post process can be reused on the same frame. (default: false)
  90280. */
  90281. function FilterPostProcess(name,
  90282. /** The matrix to be applied to the image */
  90283. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  90284. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  90285. _this.kernelMatrix = kernelMatrix;
  90286. _this.onApply = function (effect) {
  90287. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  90288. };
  90289. return _this;
  90290. }
  90291. return FilterPostProcess;
  90292. }(BABYLON.PostProcess));
  90293. BABYLON.FilterPostProcess = FilterPostProcess;
  90294. })(BABYLON || (BABYLON = {}));
  90295. //# sourceMappingURL=babylon.filterPostProcess.js.map
  90296. var BABYLON;
  90297. (function (BABYLON) {
  90298. /**
  90299. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  90300. */
  90301. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  90302. __extends(VolumetricLightScatteringPostProcess, _super);
  90303. /**
  90304. * @constructor
  90305. * @param name The post-process name
  90306. * @param 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)
  90307. * @param camera The camera that the post-process will be attached to
  90308. * @param mesh The mesh used to create the light scattering
  90309. * @param samples The post-process quality, default 100
  90310. * @param samplingModeThe post-process filtering mode
  90311. * @param engine The babylon engine
  90312. * @param reusable If the post-process is reusable
  90313. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  90314. */
  90315. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  90316. if (samples === void 0) { samples = 100; }
  90317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90318. 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;
  90319. _this._screenCoordinates = BABYLON.Vector2.Zero();
  90320. /**
  90321. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  90322. */
  90323. _this.customMeshPosition = BABYLON.Vector3.Zero();
  90324. /**
  90325. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  90326. */
  90327. _this.useCustomMeshPosition = false;
  90328. /**
  90329. * If the post-process should inverse the light scattering direction
  90330. */
  90331. _this.invert = true;
  90332. /**
  90333. * Array containing the excluded meshes not rendered in the internal pass
  90334. */
  90335. _this.excludedMeshes = new Array();
  90336. /**
  90337. * Controls the overall intensity of the post-process
  90338. */
  90339. _this.exposure = 0.3;
  90340. /**
  90341. * Dissipates each sample's contribution in range [0, 1]
  90342. */
  90343. _this.decay = 0.96815;
  90344. /**
  90345. * Controls the overall intensity of each sample
  90346. */
  90347. _this.weight = 0.58767;
  90348. /**
  90349. * Controls the density of each sample
  90350. */
  90351. _this.density = 0.926;
  90352. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  90353. engine = scene.getEngine();
  90354. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  90355. // Configure mesh
  90356. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  90357. // Configure
  90358. _this._createPass(scene, ratio.passRatio || ratio);
  90359. _this.onActivate = function (camera) {
  90360. if (!_this.isSupported) {
  90361. _this.dispose(camera);
  90362. }
  90363. _this.onActivate = null;
  90364. };
  90365. _this.onApplyObservable.add(function (effect) {
  90366. _this._updateMeshScreenCoordinates(scene);
  90367. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  90368. effect.setFloat("exposure", _this.exposure);
  90369. effect.setFloat("decay", _this.decay);
  90370. effect.setFloat("weight", _this.weight);
  90371. effect.setFloat("density", _this.density);
  90372. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  90373. });
  90374. return _this;
  90375. }
  90376. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  90377. /**
  90378. * @hidden
  90379. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  90380. */
  90381. get: function () {
  90382. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90383. return false;
  90384. },
  90385. set: function (useDiffuseColor) {
  90386. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90387. },
  90388. enumerable: true,
  90389. configurable: true
  90390. });
  90391. /**
  90392. * Returns the string "VolumetricLightScatteringPostProcess"
  90393. * @returns "VolumetricLightScatteringPostProcess"
  90394. */
  90395. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  90396. return "VolumetricLightScatteringPostProcess";
  90397. };
  90398. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  90399. var mesh = subMesh.getMesh();
  90400. // Render this.mesh as default
  90401. if (mesh === this.mesh && mesh.material) {
  90402. return mesh.material.isReady(mesh);
  90403. }
  90404. var defines = [];
  90405. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90406. var material = subMesh.getMaterial();
  90407. // Alpha test
  90408. if (material) {
  90409. if (material.needAlphaTesting()) {
  90410. defines.push("#define ALPHATEST");
  90411. }
  90412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90413. attribs.push(BABYLON.VertexBuffer.UVKind);
  90414. defines.push("#define UV1");
  90415. }
  90416. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90417. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90418. defines.push("#define UV2");
  90419. }
  90420. }
  90421. // Bones
  90422. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90423. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90424. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90425. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90426. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90427. }
  90428. else {
  90429. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90430. }
  90431. // Instances
  90432. if (useInstances) {
  90433. defines.push("#define INSTANCES");
  90434. attribs.push("world0");
  90435. attribs.push("world1");
  90436. attribs.push("world2");
  90437. attribs.push("world3");
  90438. }
  90439. // Get correct effect
  90440. var join = defines.join("\n");
  90441. if (this._cachedDefines !== join) {
  90442. this._cachedDefines = join;
  90443. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  90444. }
  90445. return this._volumetricLightScatteringPass.isReady();
  90446. };
  90447. /**
  90448. * Sets the new light position for light scattering effect
  90449. * @param position The new custom light position
  90450. */
  90451. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  90452. this.customMeshPosition = position;
  90453. };
  90454. /**
  90455. * Returns the light position for light scattering effect
  90456. * @return Vector3 The custom light position
  90457. */
  90458. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  90459. return this.customMeshPosition;
  90460. };
  90461. /**
  90462. * Disposes the internal assets and detaches the post-process from the camera
  90463. */
  90464. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  90465. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  90466. if (rttIndex !== -1) {
  90467. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  90468. }
  90469. this._volumetricLightScatteringRTT.dispose();
  90470. _super.prototype.dispose.call(this, camera);
  90471. };
  90472. /**
  90473. * Returns the render target texture used by the post-process
  90474. * @return the render target texture used by the post-process
  90475. */
  90476. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  90477. return this._volumetricLightScatteringRTT;
  90478. };
  90479. // Private methods
  90480. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  90481. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  90482. return true;
  90483. }
  90484. return false;
  90485. };
  90486. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  90487. var _this = this;
  90488. var engine = scene.getEngine();
  90489. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90490. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90491. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90492. this._volumetricLightScatteringRTT.renderList = null;
  90493. this._volumetricLightScatteringRTT.renderParticles = false;
  90494. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  90495. var camera = this.getCamera();
  90496. if (camera) {
  90497. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90498. }
  90499. else {
  90500. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90501. }
  90502. // Custom render function for submeshes
  90503. var renderSubMesh = function (subMesh) {
  90504. var mesh = subMesh.getRenderingMesh();
  90505. if (_this._meshExcluded(mesh)) {
  90506. return;
  90507. }
  90508. var material = subMesh.getMaterial();
  90509. if (!material) {
  90510. return;
  90511. }
  90512. var scene = mesh.getScene();
  90513. var engine = scene.getEngine();
  90514. // Culling
  90515. engine.setState(material.backFaceCulling);
  90516. // Managing instances
  90517. var batch = mesh._getInstancesRenderList(subMesh._id);
  90518. if (batch.mustReturn) {
  90519. return;
  90520. }
  90521. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  90522. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  90523. var effect = _this._volumetricLightScatteringPass;
  90524. if (mesh === _this.mesh) {
  90525. if (subMesh.effect) {
  90526. effect = subMesh.effect;
  90527. }
  90528. else {
  90529. effect = material.getEffect();
  90530. }
  90531. }
  90532. engine.enableEffect(effect);
  90533. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  90534. if (mesh === _this.mesh) {
  90535. material.bind(mesh.getWorldMatrix(), mesh);
  90536. }
  90537. else {
  90538. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  90539. // Alpha test
  90540. if (material && material.needAlphaTesting()) {
  90541. var alphaTexture = material.getAlphaTestTexture();
  90542. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  90543. if (alphaTexture) {
  90544. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90545. }
  90546. }
  90547. // Bones
  90548. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90549. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90550. }
  90551. }
  90552. // Draw
  90553. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  90554. }
  90555. };
  90556. // Render target texture callbacks
  90557. var savedSceneClearColor;
  90558. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  90559. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  90560. savedSceneClearColor = scene.clearColor;
  90561. scene.clearColor = sceneClearColor;
  90562. });
  90563. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  90564. scene.clearColor = savedSceneClearColor;
  90565. });
  90566. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90567. var engine = scene.getEngine();
  90568. var index;
  90569. if (depthOnlySubMeshes.length) {
  90570. engine.setColorWrite(false);
  90571. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90572. renderSubMesh(depthOnlySubMeshes.data[index]);
  90573. }
  90574. engine.setColorWrite(true);
  90575. }
  90576. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90577. renderSubMesh(opaqueSubMeshes.data[index]);
  90578. }
  90579. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90580. renderSubMesh(alphaTestSubMeshes.data[index]);
  90581. }
  90582. if (transparentSubMeshes.length) {
  90583. // Sort sub meshes
  90584. for (index = 0; index < transparentSubMeshes.length; index++) {
  90585. var submesh = transparentSubMeshes.data[index];
  90586. var boundingInfo = submesh.getBoundingInfo();
  90587. if (boundingInfo && scene.activeCamera) {
  90588. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  90589. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  90590. }
  90591. }
  90592. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  90593. sortedArray.sort(function (a, b) {
  90594. // Alpha index first
  90595. if (a._alphaIndex > b._alphaIndex) {
  90596. return 1;
  90597. }
  90598. if (a._alphaIndex < b._alphaIndex) {
  90599. return -1;
  90600. }
  90601. // Then distance to camera
  90602. if (a._distanceToCamera < b._distanceToCamera) {
  90603. return 1;
  90604. }
  90605. if (a._distanceToCamera > b._distanceToCamera) {
  90606. return -1;
  90607. }
  90608. return 0;
  90609. });
  90610. // Render sub meshes
  90611. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  90612. for (index = 0; index < sortedArray.length; index++) {
  90613. renderSubMesh(sortedArray[index]);
  90614. }
  90615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90616. }
  90617. };
  90618. };
  90619. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  90620. var transform = scene.getTransformMatrix();
  90621. var meshPosition;
  90622. if (this.useCustomMeshPosition) {
  90623. meshPosition = this.customMeshPosition;
  90624. }
  90625. else if (this.attachedNode) {
  90626. meshPosition = this.attachedNode.position;
  90627. }
  90628. else {
  90629. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  90630. }
  90631. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  90632. this._screenCoordinates.x = pos.x / this._viewPort.width;
  90633. this._screenCoordinates.y = pos.y / this._viewPort.height;
  90634. if (this.invert) {
  90635. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  90636. }
  90637. };
  90638. // Static methods
  90639. /**
  90640. * Creates a default mesh for the Volumeric Light Scattering post-process
  90641. * @param name The mesh name
  90642. * @param scene The scene where to create the mesh
  90643. * @return the default mesh
  90644. */
  90645. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  90646. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  90647. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  90648. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  90649. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  90650. mesh.material = material;
  90651. return mesh;
  90652. };
  90653. __decorate([
  90654. BABYLON.serializeAsVector3()
  90655. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  90656. __decorate([
  90657. BABYLON.serialize()
  90658. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  90659. __decorate([
  90660. BABYLON.serialize()
  90661. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  90662. __decorate([
  90663. BABYLON.serializeAsMeshReference()
  90664. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  90665. __decorate([
  90666. BABYLON.serialize()
  90667. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  90668. __decorate([
  90669. BABYLON.serialize()
  90670. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  90671. __decorate([
  90672. BABYLON.serialize()
  90673. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  90674. __decorate([
  90675. BABYLON.serialize()
  90676. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  90677. __decorate([
  90678. BABYLON.serialize()
  90679. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  90680. return VolumetricLightScatteringPostProcess;
  90681. }(BABYLON.PostProcess));
  90682. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  90683. })(BABYLON || (BABYLON = {}));
  90684. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  90685. var BABYLON;
  90686. (function (BABYLON) {
  90687. /**
  90688. *
  90689. * This post-process allows the modification of rendered colors by using
  90690. * a 'look-up table' (LUT). This effect is also called Color Grading.
  90691. *
  90692. * The object needs to be provided an url to a texture containing the color
  90693. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  90694. * Use an image editing software to tweak the LUT to match your needs.
  90695. *
  90696. * For an example of a color LUT, see here:
  90697. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  90698. * For explanations on color grading, see here:
  90699. * @see http://udn.epicgames.com/Three/ColorGrading.html
  90700. *
  90701. */
  90702. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  90703. __extends(ColorCorrectionPostProcess, _super);
  90704. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  90705. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  90706. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90707. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  90708. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90709. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90710. _this.onApply = function (effect) {
  90711. effect.setTexture("colorTable", _this._colorTableTexture);
  90712. };
  90713. return _this;
  90714. }
  90715. return ColorCorrectionPostProcess;
  90716. }(BABYLON.PostProcess));
  90717. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  90718. })(BABYLON || (BABYLON = {}));
  90719. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  90720. var BABYLON;
  90721. (function (BABYLON) {
  90722. /** Defines operator used for tonemapping */
  90723. var TonemappingOperator;
  90724. (function (TonemappingOperator) {
  90725. /** Hable */
  90726. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  90727. /** Reinhard */
  90728. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  90729. /** HejiDawson */
  90730. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  90731. /** Photographic */
  90732. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  90733. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  90734. /**
  90735. * Defines a post process to apply tone mapping
  90736. */
  90737. var TonemapPostProcess = /** @class */ (function (_super) {
  90738. __extends(TonemapPostProcess, _super);
  90739. /**
  90740. * Creates a new TonemapPostProcess
  90741. * @param name defines the name of the postprocess
  90742. * @param _operator defines the operator to use
  90743. * @param exposureAdjustment defines the required exposure adjustement
  90744. * @param camera defines the camera to use (can be null)
  90745. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  90746. * @param engine defines the hosting engine (can be ignore if camera is set)
  90747. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  90748. */
  90749. function TonemapPostProcess(name, _operator,
  90750. /** Defines the required exposure adjustement */
  90751. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  90752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90753. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90754. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  90755. _this._operator = _operator;
  90756. _this.exposureAdjustment = exposureAdjustment;
  90757. var defines = "#define ";
  90758. if (_this._operator === TonemappingOperator.Hable) {
  90759. defines += "HABLE_TONEMAPPING";
  90760. }
  90761. else if (_this._operator === TonemappingOperator.Reinhard) {
  90762. defines += "REINHARD_TONEMAPPING";
  90763. }
  90764. else if (_this._operator === TonemappingOperator.HejiDawson) {
  90765. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  90766. }
  90767. else if (_this._operator === TonemappingOperator.Photographic) {
  90768. defines += "PHOTOGRAPHIC_TONEMAPPING";
  90769. }
  90770. //sadly a second call to create the effect.
  90771. _this.updateEffect(defines);
  90772. _this.onApply = function (effect) {
  90773. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  90774. };
  90775. return _this;
  90776. }
  90777. return TonemapPostProcess;
  90778. }(BABYLON.PostProcess));
  90779. BABYLON.TonemapPostProcess = TonemapPostProcess;
  90780. })(BABYLON || (BABYLON = {}));
  90781. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  90782. var BABYLON;
  90783. (function (BABYLON) {
  90784. /**
  90785. * DisplayPassPostProcess which produces an output the same as it's input
  90786. */
  90787. var DisplayPassPostProcess = /** @class */ (function (_super) {
  90788. __extends(DisplayPassPostProcess, _super);
  90789. /**
  90790. * Creates the DisplayPassPostProcess
  90791. * @param name The name of the effect.
  90792. * @param options The required width/height ratio to downsize to before computing the render pass.
  90793. * @param camera The camera to apply the render pass to.
  90794. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90795. * @param engine The engine which the post process will be applied. (default: current engine)
  90796. * @param reusable If the post process can be reused on the same frame. (default: false)
  90797. */
  90798. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  90799. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  90800. }
  90801. return DisplayPassPostProcess;
  90802. }(BABYLON.PostProcess));
  90803. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  90804. })(BABYLON || (BABYLON = {}));
  90805. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  90806. var BABYLON;
  90807. (function (BABYLON) {
  90808. /**
  90809. * Extracts highlights from the image
  90810. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90811. */
  90812. var HighlightsPostProcess = /** @class */ (function (_super) {
  90813. __extends(HighlightsPostProcess, _super);
  90814. /**
  90815. * Extracts highlights from the image
  90816. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90817. * @param name The name of the effect.
  90818. * @param options The required width/height ratio to downsize to before computing the render pass.
  90819. * @param camera The camera to apply the render pass to.
  90820. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90821. * @param engine The engine which the post process will be applied. (default: current engine)
  90822. * @param reusable If the post process can be reused on the same frame. (default: false)
  90823. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  90824. */
  90825. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  90826. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90827. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90828. }
  90829. return HighlightsPostProcess;
  90830. }(BABYLON.PostProcess));
  90831. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  90832. })(BABYLON || (BABYLON = {}));
  90833. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  90834. var BABYLON;
  90835. (function (BABYLON) {
  90836. /**
  90837. * ImageProcessingPostProcess
  90838. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  90839. */
  90840. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  90841. __extends(ImageProcessingPostProcess, _super);
  90842. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  90843. if (camera === void 0) { camera = null; }
  90844. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90845. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  90846. _this._fromLinearSpace = true;
  90847. /**
  90848. * Defines cache preventing GC.
  90849. */
  90850. _this._defines = {
  90851. IMAGEPROCESSING: false,
  90852. VIGNETTE: false,
  90853. VIGNETTEBLENDMODEMULTIPLY: false,
  90854. VIGNETTEBLENDMODEOPAQUE: false,
  90855. TONEMAPPING: false,
  90856. TONEMAPPING_ACES: false,
  90857. CONTRAST: false,
  90858. COLORCURVES: false,
  90859. COLORGRADING: false,
  90860. COLORGRADING3D: false,
  90861. FROMLINEARSPACE: false,
  90862. SAMPLER3DGREENDEPTH: false,
  90863. SAMPLER3DBGRMAP: false,
  90864. IMAGEPROCESSINGPOSTPROCESS: false,
  90865. EXPOSURE: false,
  90866. };
  90867. // Setup the configuration as forced by the constructor. This would then not force the
  90868. // scene materials output in linear space and let untouched the default forward pass.
  90869. if (imageProcessingConfiguration) {
  90870. imageProcessingConfiguration.applyByPostProcess = true;
  90871. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  90872. // This will cause the shader to be compiled
  90873. _this.fromLinearSpace = false;
  90874. }
  90875. // Setup the default processing configuration to the scene.
  90876. else {
  90877. _this._attachImageProcessingConfiguration(null, true);
  90878. _this.imageProcessingConfiguration.applyByPostProcess = true;
  90879. }
  90880. _this.onApply = function (effect) {
  90881. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  90882. };
  90883. return _this;
  90884. }
  90885. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  90886. /**
  90887. * Gets the image processing configuration used either in this material.
  90888. */
  90889. get: function () {
  90890. return this._imageProcessingConfiguration;
  90891. },
  90892. /**
  90893. * Sets the Default image processing configuration used either in the this material.
  90894. *
  90895. * If sets to null, the scene one is in use.
  90896. */
  90897. set: function (value) {
  90898. this._attachImageProcessingConfiguration(value);
  90899. },
  90900. enumerable: true,
  90901. configurable: true
  90902. });
  90903. /**
  90904. * Attaches a new image processing configuration to the PBR Material.
  90905. * @param configuration
  90906. */
  90907. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  90908. var _this = this;
  90909. if (doNotBuild === void 0) { doNotBuild = false; }
  90910. if (configuration === this._imageProcessingConfiguration) {
  90911. return;
  90912. }
  90913. // Detaches observer.
  90914. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90915. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90916. }
  90917. // Pick the scene configuration if needed.
  90918. if (!configuration) {
  90919. var scene = null;
  90920. var engine = this.getEngine();
  90921. var camera = this.getCamera();
  90922. if (camera) {
  90923. scene = camera.getScene();
  90924. }
  90925. else if (engine && engine.scenes) {
  90926. var scenes = engine.scenes;
  90927. scene = scenes[scenes.length - 1];
  90928. }
  90929. else {
  90930. scene = BABYLON.Engine.LastCreatedScene;
  90931. }
  90932. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  90933. }
  90934. else {
  90935. this._imageProcessingConfiguration = configuration;
  90936. }
  90937. // Attaches observer.
  90938. if (this._imageProcessingConfiguration) {
  90939. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90940. _this._updateParameters();
  90941. });
  90942. }
  90943. // Ensure the effect will be rebuilt.
  90944. if (!doNotBuild) {
  90945. this._updateParameters();
  90946. }
  90947. };
  90948. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  90949. /**
  90950. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90951. */
  90952. get: function () {
  90953. return this.imageProcessingConfiguration.colorCurves;
  90954. },
  90955. /**
  90956. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90957. */
  90958. set: function (value) {
  90959. this.imageProcessingConfiguration.colorCurves = value;
  90960. },
  90961. enumerable: true,
  90962. configurable: true
  90963. });
  90964. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  90965. /**
  90966. * Gets wether the color curves effect is enabled.
  90967. */
  90968. get: function () {
  90969. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90970. },
  90971. /**
  90972. * Sets wether the color curves effect is enabled.
  90973. */
  90974. set: function (value) {
  90975. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90976. },
  90977. enumerable: true,
  90978. configurable: true
  90979. });
  90980. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  90981. /**
  90982. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  90983. */
  90984. get: function () {
  90985. return this.imageProcessingConfiguration.colorGradingTexture;
  90986. },
  90987. /**
  90988. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  90989. */
  90990. set: function (value) {
  90991. this.imageProcessingConfiguration.colorGradingTexture = value;
  90992. },
  90993. enumerable: true,
  90994. configurable: true
  90995. });
  90996. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  90997. /**
  90998. * Gets wether the color grading effect is enabled.
  90999. */
  91000. get: function () {
  91001. return this.imageProcessingConfiguration.colorGradingEnabled;
  91002. },
  91003. /**
  91004. * Gets wether the color grading effect is enabled.
  91005. */
  91006. set: function (value) {
  91007. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91008. },
  91009. enumerable: true,
  91010. configurable: true
  91011. });
  91012. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  91013. /**
  91014. * Gets exposure used in the effect.
  91015. */
  91016. get: function () {
  91017. return this.imageProcessingConfiguration.exposure;
  91018. },
  91019. /**
  91020. * Sets exposure used in the effect.
  91021. */
  91022. set: function (value) {
  91023. this.imageProcessingConfiguration.exposure = value;
  91024. },
  91025. enumerable: true,
  91026. configurable: true
  91027. });
  91028. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  91029. /**
  91030. * Gets wether tonemapping is enabled or not.
  91031. */
  91032. get: function () {
  91033. return this._imageProcessingConfiguration.toneMappingEnabled;
  91034. },
  91035. /**
  91036. * Sets wether tonemapping is enabled or not
  91037. */
  91038. set: function (value) {
  91039. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91040. },
  91041. enumerable: true,
  91042. configurable: true
  91043. });
  91044. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  91045. /**
  91046. * Gets contrast used in the effect.
  91047. */
  91048. get: function () {
  91049. return this.imageProcessingConfiguration.contrast;
  91050. },
  91051. /**
  91052. * Sets contrast used in the effect.
  91053. */
  91054. set: function (value) {
  91055. this.imageProcessingConfiguration.contrast = value;
  91056. },
  91057. enumerable: true,
  91058. configurable: true
  91059. });
  91060. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  91061. /**
  91062. * Gets Vignette stretch size.
  91063. */
  91064. get: function () {
  91065. return this.imageProcessingConfiguration.vignetteStretch;
  91066. },
  91067. /**
  91068. * Sets Vignette stretch size.
  91069. */
  91070. set: function (value) {
  91071. this.imageProcessingConfiguration.vignetteStretch = value;
  91072. },
  91073. enumerable: true,
  91074. configurable: true
  91075. });
  91076. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  91077. /**
  91078. * Gets Vignette centre X Offset.
  91079. */
  91080. get: function () {
  91081. return this.imageProcessingConfiguration.vignetteCentreX;
  91082. },
  91083. /**
  91084. * Sets Vignette centre X Offset.
  91085. */
  91086. set: function (value) {
  91087. this.imageProcessingConfiguration.vignetteCentreX = value;
  91088. },
  91089. enumerable: true,
  91090. configurable: true
  91091. });
  91092. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  91093. /**
  91094. * Gets Vignette centre Y Offset.
  91095. */
  91096. get: function () {
  91097. return this.imageProcessingConfiguration.vignetteCentreY;
  91098. },
  91099. /**
  91100. * Sets Vignette centre Y Offset.
  91101. */
  91102. set: function (value) {
  91103. this.imageProcessingConfiguration.vignetteCentreY = value;
  91104. },
  91105. enumerable: true,
  91106. configurable: true
  91107. });
  91108. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  91109. /**
  91110. * Gets Vignette weight or intensity of the vignette effect.
  91111. */
  91112. get: function () {
  91113. return this.imageProcessingConfiguration.vignetteWeight;
  91114. },
  91115. /**
  91116. * Sets Vignette weight or intensity of the vignette effect.
  91117. */
  91118. set: function (value) {
  91119. this.imageProcessingConfiguration.vignetteWeight = value;
  91120. },
  91121. enumerable: true,
  91122. configurable: true
  91123. });
  91124. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  91125. /**
  91126. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91127. * if vignetteEnabled is set to true.
  91128. */
  91129. get: function () {
  91130. return this.imageProcessingConfiguration.vignetteColor;
  91131. },
  91132. /**
  91133. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91134. * if vignetteEnabled is set to true.
  91135. */
  91136. set: function (value) {
  91137. this.imageProcessingConfiguration.vignetteColor = value;
  91138. },
  91139. enumerable: true,
  91140. configurable: true
  91141. });
  91142. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  91143. /**
  91144. * Gets Camera field of view used by the Vignette effect.
  91145. */
  91146. get: function () {
  91147. return this.imageProcessingConfiguration.vignetteCameraFov;
  91148. },
  91149. /**
  91150. * Sets Camera field of view used by the Vignette effect.
  91151. */
  91152. set: function (value) {
  91153. this.imageProcessingConfiguration.vignetteCameraFov = value;
  91154. },
  91155. enumerable: true,
  91156. configurable: true
  91157. });
  91158. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  91159. /**
  91160. * Gets the vignette blend mode allowing different kind of effect.
  91161. */
  91162. get: function () {
  91163. return this.imageProcessingConfiguration.vignetteBlendMode;
  91164. },
  91165. /**
  91166. * Sets the vignette blend mode allowing different kind of effect.
  91167. */
  91168. set: function (value) {
  91169. this.imageProcessingConfiguration.vignetteBlendMode = value;
  91170. },
  91171. enumerable: true,
  91172. configurable: true
  91173. });
  91174. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  91175. /**
  91176. * Gets wether the vignette effect is enabled.
  91177. */
  91178. get: function () {
  91179. return this.imageProcessingConfiguration.vignetteEnabled;
  91180. },
  91181. /**
  91182. * Sets wether the vignette effect is enabled.
  91183. */
  91184. set: function (value) {
  91185. this.imageProcessingConfiguration.vignetteEnabled = value;
  91186. },
  91187. enumerable: true,
  91188. configurable: true
  91189. });
  91190. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  91191. /**
  91192. * Gets wether the input of the processing is in Gamma or Linear Space.
  91193. */
  91194. get: function () {
  91195. return this._fromLinearSpace;
  91196. },
  91197. /**
  91198. * Sets wether the input of the processing is in Gamma or Linear Space.
  91199. */
  91200. set: function (value) {
  91201. if (this._fromLinearSpace === value) {
  91202. return;
  91203. }
  91204. this._fromLinearSpace = value;
  91205. this._updateParameters();
  91206. },
  91207. enumerable: true,
  91208. configurable: true
  91209. });
  91210. /**
  91211. * "ImageProcessingPostProcess"
  91212. * @returns "ImageProcessingPostProcess"
  91213. */
  91214. ImageProcessingPostProcess.prototype.getClassName = function () {
  91215. return "ImageProcessingPostProcess";
  91216. };
  91217. ImageProcessingPostProcess.prototype._updateParameters = function () {
  91218. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  91219. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  91220. var defines = "";
  91221. for (var define in this._defines) {
  91222. if (this._defines[define]) {
  91223. defines += "#define " + define + ";\r\n";
  91224. }
  91225. }
  91226. var samplers = ["textureSampler"];
  91227. var uniforms = ["scale"];
  91228. if (BABYLON.ImageProcessingConfiguration) {
  91229. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  91230. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  91231. }
  91232. this.updateEffect(defines, uniforms, samplers);
  91233. };
  91234. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  91235. _super.prototype.dispose.call(this, camera);
  91236. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91237. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91238. }
  91239. if (this._imageProcessingConfiguration) {
  91240. this.imageProcessingConfiguration.applyByPostProcess = false;
  91241. }
  91242. };
  91243. __decorate([
  91244. BABYLON.serialize()
  91245. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  91246. return ImageProcessingPostProcess;
  91247. }(BABYLON.PostProcess));
  91248. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  91249. })(BABYLON || (BABYLON = {}));
  91250. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  91251. var BABYLON;
  91252. (function (BABYLON) {
  91253. /**
  91254. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  91255. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  91256. * As an example, all you have to do is to create the post-process:
  91257. * var mb = new BABYLON.MotionBlurPostProcess(
  91258. * 'mb', // The name of the effect.
  91259. * scene, // The scene containing the objects to blur according to their velocity.
  91260. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  91261. * camera // The camera to apply the render pass to.
  91262. * );
  91263. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  91264. */
  91265. var MotionBlurPostProcess = /** @class */ (function (_super) {
  91266. __extends(MotionBlurPostProcess, _super);
  91267. /**
  91268. * Creates a new instance MotionBlurPostProcess
  91269. * @param name The name of the effect.
  91270. * @param scene The scene containing the objects to blur according to their velocity.
  91271. * @param options The required width/height ratio to downsize to before computing the render pass.
  91272. * @param camera The camera to apply the render pass to.
  91273. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91274. * @param engine The engine which the post process will be applied. (default: current engine)
  91275. * @param reusable If the post process can be reused on the same frame. (default: false)
  91276. * @param textureType Type of textures used when performing the post process. (default: 0)
  91277. * @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)
  91278. */
  91279. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  91280. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91281. if (blockCompilation === void 0) { blockCompilation = false; }
  91282. var _this = _super.call(this, name, "motionBlur", ["motionStrength", "motionScale", "screenSize"], ["velocitySampler"], options, camera, samplingMode, engine, reusable, "#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0", textureType, undefined, null, blockCompilation) || this;
  91283. /**
  91284. * Defines how much the image is blurred by the movement. Default value is equal to 1
  91285. */
  91286. _this.motionStrength = 1;
  91287. _this._motionBlurSamples = 32;
  91288. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  91289. if (!_this._geometryBufferRenderer) {
  91290. // Geometry buffer renderer is not supported. So, work as a passthrough.
  91291. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  91292. _this.updateEffect();
  91293. }
  91294. else {
  91295. // Geometry buffer renderer is supported.
  91296. _this._geometryBufferRenderer.enableVelocity = true;
  91297. _this.onApply = function (effect) {
  91298. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  91299. effect.setFloat("motionScale", scene.getAnimationRatio());
  91300. effect.setFloat("motionStrength", _this.motionStrength);
  91301. if (_this._geometryBufferRenderer) {
  91302. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  91303. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  91304. }
  91305. };
  91306. }
  91307. return _this;
  91308. }
  91309. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  91310. /**
  91311. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  91312. */
  91313. get: function () {
  91314. return this._motionBlurSamples;
  91315. },
  91316. /**
  91317. * Sets the number of iterations to be used for motion blur quality
  91318. */
  91319. set: function (samples) {
  91320. this._motionBlurSamples = samples;
  91321. if (this._geometryBufferRenderer) {
  91322. this.updateEffect("#define GEOMETRY_SUPPORTED\n#define SAMPLES " + samples.toFixed(1));
  91323. }
  91324. },
  91325. enumerable: true,
  91326. configurable: true
  91327. });
  91328. /**
  91329. * Disposes the post process.
  91330. * @param camera The camera to dispose the post process on.
  91331. */
  91332. MotionBlurPostProcess.prototype.dispose = function (camera) {
  91333. if (this._geometryBufferRenderer) {
  91334. // Clear previous transformation matrices dictionary used to compute objects velocities
  91335. this._geometryBufferRenderer._previousTransformationMatrices = {};
  91336. }
  91337. _super.prototype.dispose.call(this, camera);
  91338. };
  91339. return MotionBlurPostProcess;
  91340. }(BABYLON.PostProcess));
  91341. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  91342. })(BABYLON || (BABYLON = {}));
  91343. //# sourceMappingURL=babylon.motionBlurPostProcess.js.map
  91344. var BABYLON;
  91345. (function (BABYLON) {
  91346. /**
  91347. * Class used to store bone information
  91348. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91349. */
  91350. var Bone = /** @class */ (function (_super) {
  91351. __extends(Bone, _super);
  91352. /**
  91353. * Create a new bone
  91354. * @param name defines the bone name
  91355. * @param skeleton defines the parent skeleton
  91356. * @param parentBone defines the parent (can be null if the bone is the root)
  91357. * @param localMatrix defines the local matrix
  91358. * @param restPose defines the rest pose matrix
  91359. * @param baseMatrix defines the base matrix
  91360. * @param index defines index of the bone in the hiearchy
  91361. */
  91362. function Bone(
  91363. /**
  91364. * defines the bone name
  91365. */
  91366. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  91367. if (parentBone === void 0) { parentBone = null; }
  91368. if (localMatrix === void 0) { localMatrix = null; }
  91369. if (restPose === void 0) { restPose = null; }
  91370. if (baseMatrix === void 0) { baseMatrix = null; }
  91371. if (index === void 0) { index = null; }
  91372. var _this = _super.call(this, name, skeleton.getScene()) || this;
  91373. _this.name = name;
  91374. /**
  91375. * Gets the list of child bones
  91376. */
  91377. _this.children = new Array();
  91378. /** Gets the animations associated with this bone */
  91379. _this.animations = new Array();
  91380. /**
  91381. * @hidden Internal only
  91382. * Set this value to map this bone to a different index in the transform matrices
  91383. * Set this value to -1 to exclude the bone from the transform matrices
  91384. */
  91385. _this._index = null;
  91386. _this._absoluteTransform = new BABYLON.Matrix();
  91387. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  91388. _this._scalingDeterminant = 1;
  91389. _this._worldTransform = new BABYLON.Matrix();
  91390. _this._needToDecompose = true;
  91391. _this._needToCompose = false;
  91392. _this._skeleton = skeleton;
  91393. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  91394. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  91395. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  91396. _this._index = index;
  91397. skeleton.bones.push(_this);
  91398. _this.setParent(parentBone, false);
  91399. if (baseMatrix || localMatrix) {
  91400. _this._updateDifferenceMatrix();
  91401. }
  91402. return _this;
  91403. }
  91404. Object.defineProperty(Bone.prototype, "_matrix", {
  91405. /** @hidden */
  91406. get: function () {
  91407. this._compose();
  91408. return this._localMatrix;
  91409. },
  91410. /** @hidden */
  91411. set: function (value) {
  91412. this._localMatrix.copyFrom(value);
  91413. this._needToDecompose = true;
  91414. },
  91415. enumerable: true,
  91416. configurable: true
  91417. });
  91418. // Members
  91419. /**
  91420. * Gets the parent skeleton
  91421. * @returns a skeleton
  91422. */
  91423. Bone.prototype.getSkeleton = function () {
  91424. return this._skeleton;
  91425. };
  91426. /**
  91427. * Gets parent bone
  91428. * @returns a bone or null if the bone is the root of the bone hierarchy
  91429. */
  91430. Bone.prototype.getParent = function () {
  91431. return this._parent;
  91432. };
  91433. /**
  91434. * Sets the parent bone
  91435. * @param parent defines the parent (can be null if the bone is the root)
  91436. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91437. */
  91438. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  91439. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91440. if (this._parent === parent) {
  91441. return;
  91442. }
  91443. if (this._parent) {
  91444. var index = this._parent.children.indexOf(this);
  91445. if (index !== -1) {
  91446. this._parent.children.splice(index, 1);
  91447. }
  91448. }
  91449. this._parent = parent;
  91450. if (this._parent) {
  91451. this._parent.children.push(this);
  91452. }
  91453. if (updateDifferenceMatrix) {
  91454. this._updateDifferenceMatrix();
  91455. }
  91456. this.markAsDirty();
  91457. };
  91458. /**
  91459. * Gets the local matrix
  91460. * @returns a matrix
  91461. */
  91462. Bone.prototype.getLocalMatrix = function () {
  91463. this._compose();
  91464. return this._localMatrix;
  91465. };
  91466. /**
  91467. * Gets the base matrix (initial matrix which remains unchanged)
  91468. * @returns a matrix
  91469. */
  91470. Bone.prototype.getBaseMatrix = function () {
  91471. return this._baseMatrix;
  91472. };
  91473. /**
  91474. * Gets the rest pose matrix
  91475. * @returns a matrix
  91476. */
  91477. Bone.prototype.getRestPose = function () {
  91478. return this._restPose;
  91479. };
  91480. /**
  91481. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  91482. */
  91483. Bone.prototype.getWorldMatrix = function () {
  91484. return this._worldTransform;
  91485. };
  91486. /**
  91487. * Sets the local matrix to rest pose matrix
  91488. */
  91489. Bone.prototype.returnToRest = function () {
  91490. this.updateMatrix(this._restPose.clone());
  91491. };
  91492. /**
  91493. * Gets the inverse of the absolute transform matrix.
  91494. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  91495. * @returns a matrix
  91496. */
  91497. Bone.prototype.getInvertedAbsoluteTransform = function () {
  91498. return this._invertedAbsoluteTransform;
  91499. };
  91500. /**
  91501. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  91502. * @returns a matrix
  91503. */
  91504. Bone.prototype.getAbsoluteTransform = function () {
  91505. return this._absoluteTransform;
  91506. };
  91507. Object.defineProperty(Bone.prototype, "position", {
  91508. // Properties (matches AbstractMesh properties)
  91509. /** Gets or sets current position (in local space) */
  91510. get: function () {
  91511. this._decompose();
  91512. return this._localPosition;
  91513. },
  91514. set: function (newPosition) {
  91515. this._decompose();
  91516. this._localPosition.copyFrom(newPosition);
  91517. this._markAsDirtyAndCompose();
  91518. },
  91519. enumerable: true,
  91520. configurable: true
  91521. });
  91522. Object.defineProperty(Bone.prototype, "rotation", {
  91523. /** Gets or sets current rotation (in local space) */
  91524. get: function () {
  91525. return this.getRotation();
  91526. },
  91527. set: function (newRotation) {
  91528. this.setRotation(newRotation);
  91529. },
  91530. enumerable: true,
  91531. configurable: true
  91532. });
  91533. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  91534. /** Gets or sets current rotation quaternion (in local space) */
  91535. get: function () {
  91536. this._decompose();
  91537. return this._localRotation;
  91538. },
  91539. set: function (newRotation) {
  91540. this.setRotationQuaternion(newRotation);
  91541. },
  91542. enumerable: true,
  91543. configurable: true
  91544. });
  91545. Object.defineProperty(Bone.prototype, "scaling", {
  91546. /** Gets or sets current scaling (in local space) */
  91547. get: function () {
  91548. return this.getScale();
  91549. },
  91550. set: function (newScaling) {
  91551. this.setScale(newScaling);
  91552. },
  91553. enumerable: true,
  91554. configurable: true
  91555. });
  91556. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  91557. /**
  91558. * Gets the animation properties override
  91559. */
  91560. get: function () {
  91561. return this._skeleton.animationPropertiesOverride;
  91562. },
  91563. enumerable: true,
  91564. configurable: true
  91565. });
  91566. // Methods
  91567. Bone.prototype._decompose = function () {
  91568. if (!this._needToDecompose) {
  91569. return;
  91570. }
  91571. this._needToDecompose = false;
  91572. if (!this._localScaling) {
  91573. this._localScaling = BABYLON.Vector3.Zero();
  91574. this._localRotation = BABYLON.Quaternion.Zero();
  91575. this._localPosition = BABYLON.Vector3.Zero();
  91576. }
  91577. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  91578. };
  91579. Bone.prototype._compose = function () {
  91580. if (!this._needToCompose) {
  91581. return;
  91582. }
  91583. this._needToCompose = false;
  91584. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  91585. };
  91586. /**
  91587. * Update the base and local matrices
  91588. * @param matrix defines the new base or local matrix
  91589. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91590. * @param updateLocalMatrix defines if the local matrix should be updated
  91591. */
  91592. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  91593. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91594. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  91595. this._baseMatrix.copyFrom(matrix);
  91596. if (updateDifferenceMatrix) {
  91597. this._updateDifferenceMatrix();
  91598. }
  91599. if (updateLocalMatrix) {
  91600. this._localMatrix.copyFrom(matrix);
  91601. this._markAsDirtyAndDecompose();
  91602. }
  91603. else {
  91604. this.markAsDirty();
  91605. }
  91606. };
  91607. /** @hidden */
  91608. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  91609. if (updateChildren === void 0) { updateChildren = true; }
  91610. if (!rootMatrix) {
  91611. rootMatrix = this._baseMatrix;
  91612. }
  91613. if (this._parent) {
  91614. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  91615. }
  91616. else {
  91617. this._absoluteTransform.copyFrom(rootMatrix);
  91618. }
  91619. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  91620. if (updateChildren) {
  91621. for (var index = 0; index < this.children.length; index++) {
  91622. this.children[index]._updateDifferenceMatrix();
  91623. }
  91624. }
  91625. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  91626. };
  91627. /**
  91628. * Flag the bone as dirty (Forcing it to update everything)
  91629. */
  91630. Bone.prototype.markAsDirty = function () {
  91631. this._currentRenderId++;
  91632. this._childRenderId++;
  91633. this._skeleton._markAsDirty();
  91634. };
  91635. Bone.prototype._markAsDirtyAndCompose = function () {
  91636. this.markAsDirty();
  91637. this._needToCompose = true;
  91638. };
  91639. Bone.prototype._markAsDirtyAndDecompose = function () {
  91640. this.markAsDirty();
  91641. this._needToDecompose = true;
  91642. };
  91643. /**
  91644. * Copy an animation range from another bone
  91645. * @param source defines the source bone
  91646. * @param rangeName defines the range name to copy
  91647. * @param frameOffset defines the frame offset
  91648. * @param rescaleAsRequired defines if rescaling must be applied if required
  91649. * @param skelDimensionsRatio defines the scaling ratio
  91650. * @returns true if operation was successful
  91651. */
  91652. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  91653. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91654. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  91655. // all animation may be coming from a library skeleton, so may need to create animation
  91656. if (this.animations.length === 0) {
  91657. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  91658. this.animations[0].setKeys([]);
  91659. }
  91660. // get animation info / verify there is such a range from the source bone
  91661. var sourceRange = source.animations[0].getRange(rangeName);
  91662. if (!sourceRange) {
  91663. return false;
  91664. }
  91665. var from = sourceRange.from;
  91666. var to = sourceRange.to;
  91667. var sourceKeys = source.animations[0].getKeys();
  91668. // rescaling prep
  91669. var sourceBoneLength = source.length;
  91670. var sourceParent = source.getParent();
  91671. var parent = this.getParent();
  91672. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  91673. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  91674. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  91675. var destKeys = this.animations[0].getKeys();
  91676. // loop vars declaration
  91677. var orig;
  91678. var origTranslation;
  91679. var mat;
  91680. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  91681. orig = sourceKeys[key];
  91682. if (orig.frame >= from && orig.frame <= to) {
  91683. if (rescaleAsRequired) {
  91684. mat = orig.value.clone();
  91685. // scale based on parent ratio, when bone has parent
  91686. if (parentScalingReqd) {
  91687. origTranslation = mat.getTranslation();
  91688. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  91689. // scale based on skeleton dimension ratio when root bone, and value is passed
  91690. }
  91691. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  91692. origTranslation = mat.getTranslation();
  91693. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  91694. // use original when root bone, and no data for skelDimensionsRatio
  91695. }
  91696. else {
  91697. mat = orig.value;
  91698. }
  91699. }
  91700. else {
  91701. mat = orig.value;
  91702. }
  91703. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  91704. }
  91705. }
  91706. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  91707. return true;
  91708. };
  91709. /**
  91710. * Translate the bone in local or world space
  91711. * @param vec The amount to translate the bone
  91712. * @param space The space that the translation is in
  91713. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91714. */
  91715. Bone.prototype.translate = function (vec, space, mesh) {
  91716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91717. var lm = this.getLocalMatrix();
  91718. if (space == BABYLON.Space.LOCAL) {
  91719. lm.addAtIndex(12, vec.x);
  91720. lm.addAtIndex(13, vec.y);
  91721. lm.addAtIndex(14, vec.z);
  91722. }
  91723. else {
  91724. var wm = null;
  91725. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91726. if (mesh) {
  91727. wm = mesh.getWorldMatrix();
  91728. }
  91729. this._skeleton.computeAbsoluteTransforms();
  91730. var tmat = Bone._tmpMats[0];
  91731. var tvec = Bone._tmpVecs[0];
  91732. if (this._parent) {
  91733. if (mesh && wm) {
  91734. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91735. tmat.multiplyToRef(wm, tmat);
  91736. }
  91737. else {
  91738. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91739. }
  91740. }
  91741. tmat.setTranslationFromFloats(0, 0, 0);
  91742. tmat.invert();
  91743. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  91744. lm.addAtIndex(12, tvec.x);
  91745. lm.addAtIndex(13, tvec.y);
  91746. lm.addAtIndex(14, tvec.z);
  91747. }
  91748. this._markAsDirtyAndDecompose();
  91749. };
  91750. /**
  91751. * Set the postion of the bone in local or world space
  91752. * @param position The position to set the bone
  91753. * @param space The space that the position is in
  91754. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91755. */
  91756. Bone.prototype.setPosition = function (position, space, mesh) {
  91757. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91758. var lm = this.getLocalMatrix();
  91759. if (space == BABYLON.Space.LOCAL) {
  91760. lm.setTranslationFromFloats(position.x, position.y, position.z);
  91761. }
  91762. else {
  91763. var wm = null;
  91764. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91765. if (mesh) {
  91766. wm = mesh.getWorldMatrix();
  91767. }
  91768. this._skeleton.computeAbsoluteTransforms();
  91769. var tmat = Bone._tmpMats[0];
  91770. var vec = Bone._tmpVecs[0];
  91771. if (this._parent) {
  91772. if (mesh && wm) {
  91773. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91774. tmat.multiplyToRef(wm, tmat);
  91775. }
  91776. else {
  91777. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91778. }
  91779. }
  91780. tmat.invert();
  91781. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  91782. lm.setTranslationFromFloats(vec.x, vec.y, vec.z);
  91783. }
  91784. this._markAsDirtyAndDecompose();
  91785. };
  91786. /**
  91787. * Set the absolute position of the bone (world space)
  91788. * @param position The position to set the bone
  91789. * @param mesh The mesh that this bone is attached to
  91790. */
  91791. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  91792. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  91793. };
  91794. /**
  91795. * Scale the bone on the x, y and z axes (in local space)
  91796. * @param x The amount to scale the bone on the x axis
  91797. * @param y The amount to scale the bone on the y axis
  91798. * @param z The amount to scale the bone on the z axis
  91799. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  91800. */
  91801. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  91802. if (scaleChildren === void 0) { scaleChildren = false; }
  91803. var locMat = this.getLocalMatrix();
  91804. // Apply new scaling on top of current local matrix
  91805. var scaleMat = Bone._tmpMats[0];
  91806. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  91807. scaleMat.multiplyToRef(locMat, locMat);
  91808. // Invert scaling matrix and apply the inverse to all children
  91809. scaleMat.invert();
  91810. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  91811. var child = _a[_i];
  91812. var cm = child.getLocalMatrix();
  91813. cm.multiplyToRef(scaleMat, cm);
  91814. cm.multiplyAtIndex(12, x);
  91815. cm.multiplyAtIndex(13, y);
  91816. cm.multiplyAtIndex(14, z);
  91817. child._markAsDirtyAndDecompose();
  91818. }
  91819. this._markAsDirtyAndDecompose();
  91820. if (scaleChildren) {
  91821. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  91822. var child = _c[_b];
  91823. child.scale(x, y, z, scaleChildren);
  91824. }
  91825. }
  91826. };
  91827. /**
  91828. * Set the bone scaling in local space
  91829. * @param scale defines the scaling vector
  91830. */
  91831. Bone.prototype.setScale = function (scale) {
  91832. this._decompose();
  91833. this._localScaling.copyFrom(scale);
  91834. this._markAsDirtyAndCompose();
  91835. };
  91836. /**
  91837. * Gets the current scaling in local space
  91838. * @returns the current scaling vector
  91839. */
  91840. Bone.prototype.getScale = function () {
  91841. this._decompose();
  91842. return this._localScaling;
  91843. };
  91844. /**
  91845. * Gets the current scaling in local space and stores it in a target vector
  91846. * @param result defines the target vector
  91847. */
  91848. Bone.prototype.getScaleToRef = function (result) {
  91849. this._decompose();
  91850. result.copyFrom(this._localScaling);
  91851. };
  91852. /**
  91853. * Set the yaw, pitch, and roll of the bone in local or world space
  91854. * @param yaw The rotation of the bone on the y axis
  91855. * @param pitch The rotation of the bone on the x axis
  91856. * @param roll The rotation of the bone on the z axis
  91857. * @param space The space that the axes of rotation are in
  91858. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91859. */
  91860. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  91861. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91862. if (space === BABYLON.Space.LOCAL) {
  91863. var quat = Bone._tmpQuat;
  91864. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  91865. this.setRotationQuaternion(quat, space, mesh);
  91866. return;
  91867. }
  91868. var rotMatInv = Bone._tmpMats[0];
  91869. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91870. return;
  91871. }
  91872. var rotMat = Bone._tmpMats[1];
  91873. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  91874. rotMatInv.multiplyToRef(rotMat, rotMat);
  91875. this._rotateWithMatrix(rotMat, space, mesh);
  91876. };
  91877. /**
  91878. * Add a rotation to the bone on an axis in local or world space
  91879. * @param axis The axis to rotate the bone on
  91880. * @param amount The amount to rotate the bone
  91881. * @param space The space that the axis is in
  91882. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91883. */
  91884. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  91885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91886. var rmat = Bone._tmpMats[0];
  91887. rmat.setTranslationFromFloats(0, 0, 0);
  91888. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  91889. this._rotateWithMatrix(rmat, space, mesh);
  91890. };
  91891. /**
  91892. * Set the rotation of the bone to a particular axis angle in local or world space
  91893. * @param axis The axis to rotate the bone on
  91894. * @param angle The angle that the bone should be rotated to
  91895. * @param space The space that the axis is in
  91896. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91897. */
  91898. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  91899. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91900. if (space === BABYLON.Space.LOCAL) {
  91901. var quat = Bone._tmpQuat;
  91902. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  91903. this.setRotationQuaternion(quat, space, mesh);
  91904. return;
  91905. }
  91906. var rotMatInv = Bone._tmpMats[0];
  91907. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91908. return;
  91909. }
  91910. var rotMat = Bone._tmpMats[1];
  91911. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  91912. rotMatInv.multiplyToRef(rotMat, rotMat);
  91913. this._rotateWithMatrix(rotMat, space, mesh);
  91914. };
  91915. /**
  91916. * Set the euler rotation of the bone in local of world space
  91917. * @param rotation The euler rotation that the bone should be set to
  91918. * @param space The space that the rotation is in
  91919. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91920. */
  91921. Bone.prototype.setRotation = function (rotation, space, mesh) {
  91922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91923. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  91924. };
  91925. /**
  91926. * Set the quaternion rotation of the bone in local of world space
  91927. * @param quat The quaternion rotation that the bone should be set to
  91928. * @param space The space that the rotation is in
  91929. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91930. */
  91931. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  91932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91933. if (space === BABYLON.Space.LOCAL) {
  91934. this._decompose();
  91935. this._localRotation.copyFrom(quat);
  91936. this._markAsDirtyAndCompose();
  91937. return;
  91938. }
  91939. var rotMatInv = Bone._tmpMats[0];
  91940. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91941. return;
  91942. }
  91943. var rotMat = Bone._tmpMats[1];
  91944. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  91945. rotMatInv.multiplyToRef(rotMat, rotMat);
  91946. this._rotateWithMatrix(rotMat, space, mesh);
  91947. };
  91948. /**
  91949. * Set the rotation matrix of the bone in local of world space
  91950. * @param rotMat The rotation matrix that the bone should be set to
  91951. * @param space The space that the rotation is in
  91952. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91953. */
  91954. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  91955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91956. if (space === BABYLON.Space.LOCAL) {
  91957. var quat = Bone._tmpQuat;
  91958. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  91959. this.setRotationQuaternion(quat, space, mesh);
  91960. return;
  91961. }
  91962. var rotMatInv = Bone._tmpMats[0];
  91963. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91964. return;
  91965. }
  91966. var rotMat2 = Bone._tmpMats[1];
  91967. rotMat2.copyFrom(rotMat);
  91968. rotMatInv.multiplyToRef(rotMat, rotMat2);
  91969. this._rotateWithMatrix(rotMat2, space, mesh);
  91970. };
  91971. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  91972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91973. var lmat = this.getLocalMatrix();
  91974. var lx = lmat.m[12];
  91975. var ly = lmat.m[13];
  91976. var lz = lmat.m[14];
  91977. var parent = this.getParent();
  91978. var parentScale = Bone._tmpMats[3];
  91979. var parentScaleInv = Bone._tmpMats[4];
  91980. if (parent && space == BABYLON.Space.WORLD) {
  91981. if (mesh) {
  91982. parentScale.copyFrom(mesh.getWorldMatrix());
  91983. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  91984. }
  91985. else {
  91986. parentScale.copyFrom(parent.getAbsoluteTransform());
  91987. }
  91988. parentScaleInv.copyFrom(parentScale);
  91989. parentScaleInv.invert();
  91990. lmat.multiplyToRef(parentScale, lmat);
  91991. lmat.multiplyToRef(rmat, lmat);
  91992. lmat.multiplyToRef(parentScaleInv, lmat);
  91993. }
  91994. else {
  91995. if (space == BABYLON.Space.WORLD && mesh) {
  91996. parentScale.copyFrom(mesh.getWorldMatrix());
  91997. parentScaleInv.copyFrom(parentScale);
  91998. parentScaleInv.invert();
  91999. lmat.multiplyToRef(parentScale, lmat);
  92000. lmat.multiplyToRef(rmat, lmat);
  92001. lmat.multiplyToRef(parentScaleInv, lmat);
  92002. }
  92003. else {
  92004. lmat.multiplyToRef(rmat, lmat);
  92005. }
  92006. }
  92007. lmat.setTranslationFromFloats(lx, ly, lz);
  92008. this.computeAbsoluteTransforms();
  92009. this._markAsDirtyAndDecompose();
  92010. };
  92011. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  92012. var scaleMatrix = Bone._tmpMats[2];
  92013. rotMatInv.copyFrom(this.getAbsoluteTransform());
  92014. if (mesh) {
  92015. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  92016. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  92017. }
  92018. rotMatInv.invert();
  92019. if (isNaN(rotMatInv.m[0])) {
  92020. // Matrix failed to invert.
  92021. // This can happen if scale is zero for example.
  92022. return false;
  92023. }
  92024. scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
  92025. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  92026. return true;
  92027. };
  92028. /**
  92029. * Get the position of the bone in local or world space
  92030. * @param space The space that the returned position is in
  92031. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92032. * @returns The position of the bone
  92033. */
  92034. Bone.prototype.getPosition = function (space, mesh) {
  92035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92036. if (mesh === void 0) { mesh = null; }
  92037. var pos = BABYLON.Vector3.Zero();
  92038. this.getPositionToRef(space, mesh, pos);
  92039. return pos;
  92040. };
  92041. /**
  92042. * Copy the position of the bone to a vector3 in local or world space
  92043. * @param space The space that the returned position is in
  92044. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92045. * @param result The vector3 to copy the position to
  92046. */
  92047. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  92048. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92049. if (space == BABYLON.Space.LOCAL) {
  92050. var lm = this.getLocalMatrix();
  92051. result.x = lm.m[12];
  92052. result.y = lm.m[13];
  92053. result.z = lm.m[14];
  92054. }
  92055. else {
  92056. var wm = null;
  92057. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92058. if (mesh) {
  92059. wm = mesh.getWorldMatrix();
  92060. }
  92061. this._skeleton.computeAbsoluteTransforms();
  92062. var tmat = Bone._tmpMats[0];
  92063. if (mesh && wm) {
  92064. tmat.copyFrom(this.getAbsoluteTransform());
  92065. tmat.multiplyToRef(wm, tmat);
  92066. }
  92067. else {
  92068. tmat = this.getAbsoluteTransform();
  92069. }
  92070. result.x = tmat.m[12];
  92071. result.y = tmat.m[13];
  92072. result.z = tmat.m[14];
  92073. }
  92074. };
  92075. /**
  92076. * Get the absolute position of the bone (world space)
  92077. * @param mesh The mesh that this bone is attached to
  92078. * @returns The absolute position of the bone
  92079. */
  92080. Bone.prototype.getAbsolutePosition = function (mesh) {
  92081. if (mesh === void 0) { mesh = null; }
  92082. var pos = BABYLON.Vector3.Zero();
  92083. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  92084. return pos;
  92085. };
  92086. /**
  92087. * Copy the absolute position of the bone (world space) to the result param
  92088. * @param mesh The mesh that this bone is attached to
  92089. * @param result The vector3 to copy the absolute position to
  92090. */
  92091. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  92092. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  92093. };
  92094. /**
  92095. * Compute the absolute transforms of this bone and its children
  92096. */
  92097. Bone.prototype.computeAbsoluteTransforms = function () {
  92098. this._compose();
  92099. if (this._parent) {
  92100. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92101. }
  92102. else {
  92103. this._absoluteTransform.copyFrom(this._localMatrix);
  92104. var poseMatrix = this._skeleton.getPoseMatrix();
  92105. if (poseMatrix) {
  92106. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  92107. }
  92108. }
  92109. var children = this.children;
  92110. var len = children.length;
  92111. for (var i = 0; i < len; i++) {
  92112. children[i].computeAbsoluteTransforms();
  92113. }
  92114. };
  92115. /**
  92116. * Get the world direction from an axis that is in the local space of the bone
  92117. * @param localAxis The local direction that is used to compute the world direction
  92118. * @param mesh The mesh that this bone is attached to
  92119. * @returns The world direction
  92120. */
  92121. Bone.prototype.getDirection = function (localAxis, mesh) {
  92122. if (mesh === void 0) { mesh = null; }
  92123. var result = BABYLON.Vector3.Zero();
  92124. this.getDirectionToRef(localAxis, mesh, result);
  92125. return result;
  92126. };
  92127. /**
  92128. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  92129. * @param localAxis The local direction that is used to compute the world direction
  92130. * @param mesh The mesh that this bone is attached to
  92131. * @param result The vector3 that the world direction will be copied to
  92132. */
  92133. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  92134. if (mesh === void 0) { mesh = null; }
  92135. var wm = null;
  92136. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92137. if (mesh) {
  92138. wm = mesh.getWorldMatrix();
  92139. }
  92140. this._skeleton.computeAbsoluteTransforms();
  92141. var mat = Bone._tmpMats[0];
  92142. mat.copyFrom(this.getAbsoluteTransform());
  92143. if (mesh && wm) {
  92144. mat.multiplyToRef(wm, mat);
  92145. }
  92146. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  92147. result.normalize();
  92148. };
  92149. /**
  92150. * Get the euler rotation of the bone in local or world space
  92151. * @param space The space that the rotation should be in
  92152. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92153. * @returns The euler rotation
  92154. */
  92155. Bone.prototype.getRotation = function (space, mesh) {
  92156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92157. if (mesh === void 0) { mesh = null; }
  92158. var result = BABYLON.Vector3.Zero();
  92159. this.getRotationToRef(space, mesh, result);
  92160. return result;
  92161. };
  92162. /**
  92163. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  92164. * @param space The space that the rotation should be in
  92165. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92166. * @param result The vector3 that the rotation should be copied to
  92167. */
  92168. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  92169. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92170. if (mesh === void 0) { mesh = null; }
  92171. var quat = Bone._tmpQuat;
  92172. this.getRotationQuaternionToRef(space, mesh, quat);
  92173. quat.toEulerAnglesToRef(result);
  92174. };
  92175. /**
  92176. * Get the quaternion rotation of the bone in either local or world space
  92177. * @param space The space that the rotation should be in
  92178. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92179. * @returns The quaternion rotation
  92180. */
  92181. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  92182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92183. if (mesh === void 0) { mesh = null; }
  92184. var result = BABYLON.Quaternion.Identity();
  92185. this.getRotationQuaternionToRef(space, mesh, result);
  92186. return result;
  92187. };
  92188. /**
  92189. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  92190. * @param space The space that the rotation should be in
  92191. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92192. * @param result The quaternion that the rotation should be copied to
  92193. */
  92194. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  92195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92196. if (mesh === void 0) { mesh = null; }
  92197. if (space == BABYLON.Space.LOCAL) {
  92198. this._decompose();
  92199. result.copyFrom(this._localRotation);
  92200. }
  92201. else {
  92202. var mat = Bone._tmpMats[0];
  92203. var amat = this.getAbsoluteTransform();
  92204. if (mesh) {
  92205. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92206. }
  92207. else {
  92208. mat.copyFrom(amat);
  92209. }
  92210. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92211. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92212. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92213. mat.decompose(undefined, result, undefined);
  92214. }
  92215. };
  92216. /**
  92217. * Get the rotation matrix of the bone in local or world space
  92218. * @param space The space that the rotation should be in
  92219. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92220. * @returns The rotation matrix
  92221. */
  92222. Bone.prototype.getRotationMatrix = function (space, mesh) {
  92223. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92224. var result = BABYLON.Matrix.Identity();
  92225. this.getRotationMatrixToRef(space, mesh, result);
  92226. return result;
  92227. };
  92228. /**
  92229. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  92230. * @param space The space that the rotation should be in
  92231. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92232. * @param result The quaternion that the rotation should be copied to
  92233. */
  92234. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  92235. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92236. if (space == BABYLON.Space.LOCAL) {
  92237. this.getLocalMatrix().getRotationMatrixToRef(result);
  92238. }
  92239. else {
  92240. var mat = Bone._tmpMats[0];
  92241. var amat = this.getAbsoluteTransform();
  92242. if (mesh) {
  92243. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92244. }
  92245. else {
  92246. mat.copyFrom(amat);
  92247. }
  92248. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92249. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92250. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92251. mat.getRotationMatrixToRef(result);
  92252. }
  92253. };
  92254. /**
  92255. * Get the world position of a point that is in the local space of the bone
  92256. * @param position The local position
  92257. * @param mesh The mesh that this bone is attached to
  92258. * @returns The world position
  92259. */
  92260. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  92261. if (mesh === void 0) { mesh = null; }
  92262. var result = BABYLON.Vector3.Zero();
  92263. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  92264. return result;
  92265. };
  92266. /**
  92267. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  92268. * @param position The local position
  92269. * @param mesh The mesh that this bone is attached to
  92270. * @param result The vector3 that the world position should be copied to
  92271. */
  92272. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  92273. if (mesh === void 0) { mesh = null; }
  92274. var wm = null;
  92275. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92276. if (mesh) {
  92277. wm = mesh.getWorldMatrix();
  92278. }
  92279. this._skeleton.computeAbsoluteTransforms();
  92280. var tmat = Bone._tmpMats[0];
  92281. if (mesh && wm) {
  92282. tmat.copyFrom(this.getAbsoluteTransform());
  92283. tmat.multiplyToRef(wm, tmat);
  92284. }
  92285. else {
  92286. tmat = this.getAbsoluteTransform();
  92287. }
  92288. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92289. };
  92290. /**
  92291. * Get the local position of a point that is in world space
  92292. * @param position The world position
  92293. * @param mesh The mesh that this bone is attached to
  92294. * @returns The local position
  92295. */
  92296. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  92297. if (mesh === void 0) { mesh = null; }
  92298. var result = BABYLON.Vector3.Zero();
  92299. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  92300. return result;
  92301. };
  92302. /**
  92303. * Get the local position of a point that is in world space and copy it to the result param
  92304. * @param position The world position
  92305. * @param mesh The mesh that this bone is attached to
  92306. * @param result The vector3 that the local position should be copied to
  92307. */
  92308. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  92309. if (mesh === void 0) { mesh = null; }
  92310. var wm = null;
  92311. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92312. if (mesh) {
  92313. wm = mesh.getWorldMatrix();
  92314. }
  92315. this._skeleton.computeAbsoluteTransforms();
  92316. var tmat = Bone._tmpMats[0];
  92317. tmat.copyFrom(this.getAbsoluteTransform());
  92318. if (mesh && wm) {
  92319. tmat.multiplyToRef(wm, tmat);
  92320. }
  92321. tmat.invert();
  92322. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92323. };
  92324. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  92325. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  92326. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92327. return Bone;
  92328. }(BABYLON.Node));
  92329. BABYLON.Bone = Bone;
  92330. })(BABYLON || (BABYLON = {}));
  92331. //# sourceMappingURL=babylon.bone.js.map
  92332. var BABYLON;
  92333. (function (BABYLON) {
  92334. /**
  92335. * Class used to apply inverse kinematics to bones
  92336. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  92337. */
  92338. var BoneIKController = /** @class */ (function () {
  92339. /**
  92340. * Creates a new BoneIKController
  92341. * @param mesh defines the mesh to control
  92342. * @param bone defines the bone to control
  92343. * @param options defines options to set up the controller
  92344. */
  92345. function BoneIKController(mesh, bone, options) {
  92346. /**
  92347. * Gets or sets the target position
  92348. */
  92349. this.targetPosition = BABYLON.Vector3.Zero();
  92350. /**
  92351. * Gets or sets the pole target position
  92352. */
  92353. this.poleTargetPosition = BABYLON.Vector3.Zero();
  92354. /**
  92355. * Gets or sets the pole target local offset
  92356. */
  92357. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  92358. /**
  92359. * Gets or sets the pole angle
  92360. */
  92361. this.poleAngle = 0;
  92362. /**
  92363. * 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)
  92364. */
  92365. this.slerpAmount = 1;
  92366. this._bone1Quat = BABYLON.Quaternion.Identity();
  92367. this._bone1Mat = BABYLON.Matrix.Identity();
  92368. this._bone2Ang = Math.PI;
  92369. this._maxAngle = Math.PI;
  92370. this._rightHandedSystem = false;
  92371. this._bendAxis = BABYLON.Vector3.Right();
  92372. this._slerping = false;
  92373. this._adjustRoll = 0;
  92374. this._bone2 = bone;
  92375. this._bone1 = bone.getParent();
  92376. if (!this._bone1) {
  92377. return;
  92378. }
  92379. this.mesh = mesh;
  92380. var bonePos = bone.getPosition();
  92381. if (bone.getAbsoluteTransform().determinant() > 0) {
  92382. this._rightHandedSystem = true;
  92383. this._bendAxis.x = 0;
  92384. this._bendAxis.y = 0;
  92385. this._bendAxis.z = -1;
  92386. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  92387. this._adjustRoll = Math.PI * .5;
  92388. this._bendAxis.z = 1;
  92389. }
  92390. }
  92391. if (this._bone1.length) {
  92392. var boneScale1 = this._bone1.getScale();
  92393. var boneScale2 = this._bone2.getScale();
  92394. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  92395. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  92396. }
  92397. else if (this._bone1.children[0]) {
  92398. mesh.computeWorldMatrix(true);
  92399. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  92400. var pos2 = this._bone2.getAbsolutePosition(mesh);
  92401. var pos3 = this._bone1.getAbsolutePosition(mesh);
  92402. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  92403. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  92404. }
  92405. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  92406. this.maxAngle = Math.PI;
  92407. if (options) {
  92408. if (options.targetMesh) {
  92409. this.targetMesh = options.targetMesh;
  92410. this.targetMesh.computeWorldMatrix(true);
  92411. }
  92412. if (options.poleTargetMesh) {
  92413. this.poleTargetMesh = options.poleTargetMesh;
  92414. this.poleTargetMesh.computeWorldMatrix(true);
  92415. }
  92416. else if (options.poleTargetBone) {
  92417. this.poleTargetBone = options.poleTargetBone;
  92418. }
  92419. else if (this._bone1.getParent()) {
  92420. this.poleTargetBone = this._bone1.getParent();
  92421. }
  92422. if (options.poleTargetLocalOffset) {
  92423. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  92424. }
  92425. if (options.poleAngle) {
  92426. this.poleAngle = options.poleAngle;
  92427. }
  92428. if (options.bendAxis) {
  92429. this._bendAxis.copyFrom(options.bendAxis);
  92430. }
  92431. if (options.maxAngle) {
  92432. this.maxAngle = options.maxAngle;
  92433. }
  92434. if (options.slerpAmount) {
  92435. this.slerpAmount = options.slerpAmount;
  92436. }
  92437. }
  92438. }
  92439. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  92440. /**
  92441. * Gets or sets maximum allowed angle
  92442. */
  92443. get: function () {
  92444. return this._maxAngle;
  92445. },
  92446. set: function (value) {
  92447. this._setMaxAngle(value);
  92448. },
  92449. enumerable: true,
  92450. configurable: true
  92451. });
  92452. BoneIKController.prototype._setMaxAngle = function (ang) {
  92453. if (ang < 0) {
  92454. ang = 0;
  92455. }
  92456. if (ang > Math.PI || ang == undefined) {
  92457. ang = Math.PI;
  92458. }
  92459. this._maxAngle = ang;
  92460. var a = this._bone1Length;
  92461. var b = this._bone2Length;
  92462. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  92463. };
  92464. /**
  92465. * Force the controller to update the bones
  92466. */
  92467. BoneIKController.prototype.update = function () {
  92468. var bone1 = this._bone1;
  92469. if (!bone1) {
  92470. return;
  92471. }
  92472. var target = this.targetPosition;
  92473. var poleTarget = this.poleTargetPosition;
  92474. var mat1 = BoneIKController._tmpMats[0];
  92475. var mat2 = BoneIKController._tmpMats[1];
  92476. if (this.targetMesh) {
  92477. target.copyFrom(this.targetMesh.getAbsolutePosition());
  92478. }
  92479. if (this.poleTargetBone) {
  92480. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  92481. }
  92482. else if (this.poleTargetMesh) {
  92483. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  92484. }
  92485. var bonePos = BoneIKController._tmpVecs[0];
  92486. var zaxis = BoneIKController._tmpVecs[1];
  92487. var xaxis = BoneIKController._tmpVecs[2];
  92488. var yaxis = BoneIKController._tmpVecs[3];
  92489. var upAxis = BoneIKController._tmpVecs[4];
  92490. var _tmpQuat = BoneIKController._tmpQuat;
  92491. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  92492. poleTarget.subtractToRef(bonePos, upAxis);
  92493. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  92494. upAxis.y = 1;
  92495. }
  92496. else {
  92497. upAxis.normalize();
  92498. }
  92499. target.subtractToRef(bonePos, yaxis);
  92500. yaxis.normalize();
  92501. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  92502. zaxis.normalize();
  92503. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  92504. xaxis.normalize();
  92505. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  92506. var a = this._bone1Length;
  92507. var b = this._bone2Length;
  92508. var c = BABYLON.Vector3.Distance(bonePos, target);
  92509. if (this._maxReach > 0) {
  92510. c = Math.min(this._maxReach, c);
  92511. }
  92512. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  92513. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  92514. if (acosa > 1) {
  92515. acosa = 1;
  92516. }
  92517. if (acosb > 1) {
  92518. acosb = 1;
  92519. }
  92520. if (acosa < -1) {
  92521. acosa = -1;
  92522. }
  92523. if (acosb < -1) {
  92524. acosb = -1;
  92525. }
  92526. var angA = Math.acos(acosa);
  92527. var angB = Math.acos(acosb);
  92528. var angC = -angA - angB;
  92529. if (this._rightHandedSystem) {
  92530. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  92531. mat2.multiplyToRef(mat1, mat1);
  92532. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  92533. mat2.multiplyToRef(mat1, mat1);
  92534. }
  92535. else {
  92536. var _tmpVec = BoneIKController._tmpVecs[5];
  92537. _tmpVec.copyFrom(this._bendAxis);
  92538. _tmpVec.x *= -1;
  92539. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  92540. mat2.multiplyToRef(mat1, mat1);
  92541. }
  92542. if (this.poleAngle) {
  92543. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  92544. mat1.multiplyToRef(mat2, mat1);
  92545. }
  92546. if (this._bone1) {
  92547. if (this.slerpAmount < 1) {
  92548. if (!this._slerping) {
  92549. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  92550. }
  92551. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  92552. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  92553. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  92554. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  92555. this._slerping = true;
  92556. }
  92557. else {
  92558. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  92559. this._bone1Mat.copyFrom(mat1);
  92560. this._slerping = false;
  92561. }
  92562. }
  92563. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  92564. this._bone2Ang = angC;
  92565. };
  92566. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92567. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  92568. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  92569. return BoneIKController;
  92570. }());
  92571. BABYLON.BoneIKController = BoneIKController;
  92572. })(BABYLON || (BABYLON = {}));
  92573. //# sourceMappingURL=babylon.boneIKController.js.map
  92574. var BABYLON;
  92575. (function (BABYLON) {
  92576. /**
  92577. * Class used to make a bone look toward a point in space
  92578. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  92579. */
  92580. var BoneLookController = /** @class */ (function () {
  92581. /**
  92582. * Create a BoneLookController
  92583. * @param mesh the mesh that the bone belongs to
  92584. * @param bone the bone that will be looking to the target
  92585. * @param target the target Vector3 to look at
  92586. * @param settings optional settings:
  92587. * * maxYaw: the maximum angle the bone will yaw to
  92588. * * minYaw: the minimum angle the bone will yaw to
  92589. * * maxPitch: the maximum angle the bone will pitch to
  92590. * * minPitch: the minimum angle the bone will yaw to
  92591. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  92592. * * upAxis: the up axis of the coordinate system
  92593. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  92594. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  92595. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  92596. * * adjustYaw: used to make an adjustment to the yaw of the bone
  92597. * * adjustPitch: used to make an adjustment to the pitch of the bone
  92598. * * adjustRoll: used to make an adjustment to the roll of the bone
  92599. **/
  92600. function BoneLookController(mesh, bone, target, options) {
  92601. /**
  92602. * The up axis of the coordinate system that is used when the bone is rotated
  92603. */
  92604. this.upAxis = BABYLON.Vector3.Up();
  92605. /**
  92606. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  92607. */
  92608. this.upAxisSpace = BABYLON.Space.LOCAL;
  92609. /**
  92610. * Used to make an adjustment to the yaw of the bone
  92611. */
  92612. this.adjustYaw = 0;
  92613. /**
  92614. * Used to make an adjustment to the pitch of the bone
  92615. */
  92616. this.adjustPitch = 0;
  92617. /**
  92618. * Used to make an adjustment to the roll of the bone
  92619. */
  92620. this.adjustRoll = 0;
  92621. /**
  92622. * 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)
  92623. */
  92624. this.slerpAmount = 1;
  92625. this._boneQuat = BABYLON.Quaternion.Identity();
  92626. this._slerping = false;
  92627. this._firstFrameSkipped = false;
  92628. this._fowardAxis = BABYLON.Vector3.Forward();
  92629. this.mesh = mesh;
  92630. this.bone = bone;
  92631. this.target = target;
  92632. if (options) {
  92633. if (options.adjustYaw) {
  92634. this.adjustYaw = options.adjustYaw;
  92635. }
  92636. if (options.adjustPitch) {
  92637. this.adjustPitch = options.adjustPitch;
  92638. }
  92639. if (options.adjustRoll) {
  92640. this.adjustRoll = options.adjustRoll;
  92641. }
  92642. if (options.maxYaw != null) {
  92643. this.maxYaw = options.maxYaw;
  92644. }
  92645. else {
  92646. this.maxYaw = Math.PI;
  92647. }
  92648. if (options.minYaw != null) {
  92649. this.minYaw = options.minYaw;
  92650. }
  92651. else {
  92652. this.minYaw = -Math.PI;
  92653. }
  92654. if (options.maxPitch != null) {
  92655. this.maxPitch = options.maxPitch;
  92656. }
  92657. else {
  92658. this.maxPitch = Math.PI;
  92659. }
  92660. if (options.minPitch != null) {
  92661. this.minPitch = options.minPitch;
  92662. }
  92663. else {
  92664. this.minPitch = -Math.PI;
  92665. }
  92666. if (options.slerpAmount != null) {
  92667. this.slerpAmount = options.slerpAmount;
  92668. }
  92669. if (options.upAxis != null) {
  92670. this.upAxis = options.upAxis;
  92671. }
  92672. if (options.upAxisSpace != null) {
  92673. this.upAxisSpace = options.upAxisSpace;
  92674. }
  92675. if (options.yawAxis != null || options.pitchAxis != null) {
  92676. var newYawAxis = BABYLON.Axis.Y;
  92677. var newPitchAxis = BABYLON.Axis.X;
  92678. if (options.yawAxis != null) {
  92679. newYawAxis = options.yawAxis.clone();
  92680. newYawAxis.normalize();
  92681. }
  92682. if (options.pitchAxis != null) {
  92683. newPitchAxis = options.pitchAxis.clone();
  92684. newPitchAxis.normalize();
  92685. }
  92686. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  92687. this._transformYawPitch = BABYLON.Matrix.Identity();
  92688. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  92689. this._transformYawPitchInv = this._transformYawPitch.clone();
  92690. this._transformYawPitch.invert();
  92691. }
  92692. }
  92693. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  92694. this.upAxisSpace = BABYLON.Space.LOCAL;
  92695. }
  92696. }
  92697. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  92698. /**
  92699. * Gets or sets the minimum yaw angle that the bone can look to
  92700. */
  92701. get: function () {
  92702. return this._minYaw;
  92703. },
  92704. set: function (value) {
  92705. this._minYaw = value;
  92706. this._minYawSin = Math.sin(value);
  92707. this._minYawCos = Math.cos(value);
  92708. if (this._maxYaw != null) {
  92709. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92710. this._yawRange = this._maxYaw - this._minYaw;
  92711. }
  92712. },
  92713. enumerable: true,
  92714. configurable: true
  92715. });
  92716. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  92717. /**
  92718. * Gets or sets the maximum yaw angle that the bone can look to
  92719. */
  92720. get: function () {
  92721. return this._maxYaw;
  92722. },
  92723. set: function (value) {
  92724. this._maxYaw = value;
  92725. this._maxYawSin = Math.sin(value);
  92726. this._maxYawCos = Math.cos(value);
  92727. if (this._minYaw != null) {
  92728. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92729. this._yawRange = this._maxYaw - this._minYaw;
  92730. }
  92731. },
  92732. enumerable: true,
  92733. configurable: true
  92734. });
  92735. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  92736. /**
  92737. * Gets or sets the minimum pitch angle that the bone can look to
  92738. */
  92739. get: function () {
  92740. return this._minPitch;
  92741. },
  92742. set: function (value) {
  92743. this._minPitch = value;
  92744. this._minPitchTan = Math.tan(value);
  92745. },
  92746. enumerable: true,
  92747. configurable: true
  92748. });
  92749. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  92750. /**
  92751. * Gets or sets the maximum pitch angle that the bone can look to
  92752. */
  92753. get: function () {
  92754. return this._maxPitch;
  92755. },
  92756. set: function (value) {
  92757. this._maxPitch = value;
  92758. this._maxPitchTan = Math.tan(value);
  92759. },
  92760. enumerable: true,
  92761. configurable: true
  92762. });
  92763. /**
  92764. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  92765. */
  92766. BoneLookController.prototype.update = function () {
  92767. //skip the first frame when slerping so that the mesh rotation is correct
  92768. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  92769. this._firstFrameSkipped = true;
  92770. return;
  92771. }
  92772. var bone = this.bone;
  92773. var bonePos = BoneLookController._tmpVecs[0];
  92774. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  92775. var target = this.target;
  92776. var _tmpMat1 = BoneLookController._tmpMats[0];
  92777. var _tmpMat2 = BoneLookController._tmpMats[1];
  92778. var mesh = this.mesh;
  92779. var parentBone = bone.getParent();
  92780. var upAxis = BoneLookController._tmpVecs[1];
  92781. upAxis.copyFrom(this.upAxis);
  92782. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  92783. if (this._transformYawPitch) {
  92784. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  92785. }
  92786. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  92787. }
  92788. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  92789. mesh.getDirectionToRef(upAxis, upAxis);
  92790. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  92791. upAxis.normalize();
  92792. }
  92793. }
  92794. var checkYaw = false;
  92795. var checkPitch = false;
  92796. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  92797. checkYaw = true;
  92798. }
  92799. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  92800. checkPitch = true;
  92801. }
  92802. if (checkYaw || checkPitch) {
  92803. var spaceMat = BoneLookController._tmpMats[2];
  92804. var spaceMatInv = BoneLookController._tmpMats[3];
  92805. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  92806. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  92807. }
  92808. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  92809. spaceMat.copyFrom(mesh.getWorldMatrix());
  92810. }
  92811. else {
  92812. var forwardAxis = BoneLookController._tmpVecs[2];
  92813. forwardAxis.copyFrom(this._fowardAxis);
  92814. if (this._transformYawPitch) {
  92815. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  92816. }
  92817. if (parentBone) {
  92818. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  92819. }
  92820. else {
  92821. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  92822. }
  92823. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  92824. rightAxis.normalize();
  92825. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  92826. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  92827. }
  92828. spaceMat.invertToRef(spaceMatInv);
  92829. var xzlen = null;
  92830. if (checkPitch) {
  92831. var localTarget = BoneLookController._tmpVecs[3];
  92832. target.subtractToRef(bonePos, localTarget);
  92833. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92834. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92835. var pitch = Math.atan2(localTarget.y, xzlen);
  92836. var newPitch = pitch;
  92837. if (pitch > this._maxPitch) {
  92838. localTarget.y = this._maxPitchTan * xzlen;
  92839. newPitch = this._maxPitch;
  92840. }
  92841. else if (pitch < this._minPitch) {
  92842. localTarget.y = this._minPitchTan * xzlen;
  92843. newPitch = this._minPitch;
  92844. }
  92845. if (pitch != newPitch) {
  92846. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92847. localTarget.addInPlace(bonePos);
  92848. target = localTarget;
  92849. }
  92850. }
  92851. if (checkYaw) {
  92852. var localTarget = BoneLookController._tmpVecs[4];
  92853. target.subtractToRef(bonePos, localTarget);
  92854. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92855. var yaw = Math.atan2(localTarget.x, localTarget.z);
  92856. var newYaw = yaw;
  92857. if (yaw > this._maxYaw || yaw < this._minYaw) {
  92858. if (xzlen == null) {
  92859. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92860. }
  92861. if (this._yawRange > Math.PI) {
  92862. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  92863. localTarget.z = this._maxYawCos * xzlen;
  92864. localTarget.x = this._maxYawSin * xzlen;
  92865. newYaw = this._maxYaw;
  92866. }
  92867. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  92868. localTarget.z = this._minYawCos * xzlen;
  92869. localTarget.x = this._minYawSin * xzlen;
  92870. newYaw = this._minYaw;
  92871. }
  92872. }
  92873. else {
  92874. if (yaw > this._maxYaw) {
  92875. localTarget.z = this._maxYawCos * xzlen;
  92876. localTarget.x = this._maxYawSin * xzlen;
  92877. newYaw = this._maxYaw;
  92878. }
  92879. else if (yaw < this._minYaw) {
  92880. localTarget.z = this._minYawCos * xzlen;
  92881. localTarget.x = this._minYawSin * xzlen;
  92882. newYaw = this._minYaw;
  92883. }
  92884. }
  92885. }
  92886. if (this._slerping && this._yawRange > Math.PI) {
  92887. //are we going to be crossing into the min/max region?
  92888. var boneFwd = BoneLookController._tmpVecs[8];
  92889. boneFwd.copyFrom(BABYLON.Axis.Z);
  92890. if (this._transformYawPitch) {
  92891. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  92892. }
  92893. var boneRotMat = BoneLookController._tmpMats[4];
  92894. this._boneQuat.toRotationMatrix(boneRotMat);
  92895. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  92896. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  92897. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  92898. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  92899. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  92900. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  92901. if (angBtwTar > angBtwMidYaw) {
  92902. if (xzlen == null) {
  92903. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92904. }
  92905. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  92906. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  92907. if (angBtwMin < angBtwMax) {
  92908. newYaw = boneYaw + Math.PI * .75;
  92909. localTarget.z = Math.cos(newYaw) * xzlen;
  92910. localTarget.x = Math.sin(newYaw) * xzlen;
  92911. }
  92912. else {
  92913. newYaw = boneYaw - Math.PI * .75;
  92914. localTarget.z = Math.cos(newYaw) * xzlen;
  92915. localTarget.x = Math.sin(newYaw) * xzlen;
  92916. }
  92917. }
  92918. }
  92919. if (yaw != newYaw) {
  92920. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92921. localTarget.addInPlace(bonePos);
  92922. target = localTarget;
  92923. }
  92924. }
  92925. }
  92926. var zaxis = BoneLookController._tmpVecs[5];
  92927. var xaxis = BoneLookController._tmpVecs[6];
  92928. var yaxis = BoneLookController._tmpVecs[7];
  92929. var _tmpQuat = BoneLookController._tmpQuat;
  92930. target.subtractToRef(bonePos, zaxis);
  92931. zaxis.normalize();
  92932. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  92933. xaxis.normalize();
  92934. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  92935. yaxis.normalize();
  92936. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  92937. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  92938. return;
  92939. }
  92940. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  92941. return;
  92942. }
  92943. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  92944. return;
  92945. }
  92946. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  92947. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  92948. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  92949. }
  92950. if (this.slerpAmount < 1) {
  92951. if (!this._slerping) {
  92952. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  92953. }
  92954. if (this._transformYawPitch) {
  92955. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  92956. }
  92957. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  92958. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  92959. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  92960. this._slerping = true;
  92961. }
  92962. else {
  92963. if (this._transformYawPitch) {
  92964. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  92965. }
  92966. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  92967. this._slerping = false;
  92968. }
  92969. };
  92970. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  92971. var angDiff = ang2 - ang1;
  92972. angDiff %= Math.PI * 2;
  92973. if (angDiff > Math.PI) {
  92974. angDiff -= Math.PI * 2;
  92975. }
  92976. else if (angDiff < -Math.PI) {
  92977. angDiff += Math.PI * 2;
  92978. }
  92979. return angDiff;
  92980. };
  92981. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  92982. ang1 %= (2 * Math.PI);
  92983. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  92984. ang2 %= (2 * Math.PI);
  92985. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  92986. var ab = 0;
  92987. if (ang1 < ang2) {
  92988. ab = ang2 - ang1;
  92989. }
  92990. else {
  92991. ab = ang1 - ang2;
  92992. }
  92993. if (ab > Math.PI) {
  92994. ab = Math.PI * 2 - ab;
  92995. }
  92996. return ab;
  92997. };
  92998. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  92999. ang %= (2 * Math.PI);
  93000. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  93001. ang1 %= (2 * Math.PI);
  93002. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93003. ang2 %= (2 * Math.PI);
  93004. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93005. if (ang1 < ang2) {
  93006. if (ang > ang1 && ang < ang2) {
  93007. return true;
  93008. }
  93009. }
  93010. else {
  93011. if (ang > ang2 && ang < ang1) {
  93012. return true;
  93013. }
  93014. }
  93015. return false;
  93016. };
  93017. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  93018. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  93019. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  93020. return BoneLookController;
  93021. }());
  93022. BABYLON.BoneLookController = BoneLookController;
  93023. })(BABYLON || (BABYLON = {}));
  93024. //# sourceMappingURL=babylon.boneLookController.js.map
  93025. var BABYLON;
  93026. (function (BABYLON) {
  93027. /**
  93028. * Class used to handle skinning animations
  93029. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  93030. */
  93031. var Skeleton = /** @class */ (function () {
  93032. /**
  93033. * Creates a new skeleton
  93034. * @param name defines the skeleton name
  93035. * @param id defines the skeleton Id
  93036. * @param scene defines the hosting scene
  93037. */
  93038. function Skeleton(
  93039. /** defines the skeleton name */
  93040. name,
  93041. /** defines the skeleton Id */
  93042. id, scene) {
  93043. this.name = name;
  93044. this.id = id;
  93045. /**
  93046. * Gets the list of child bones
  93047. */
  93048. this.bones = new Array();
  93049. /**
  93050. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  93051. */
  93052. this.needInitialSkinMatrix = false;
  93053. this._isDirty = true;
  93054. this._meshesWithPoseMatrix = new Array();
  93055. this._identity = BABYLON.Matrix.Identity();
  93056. this._ranges = {};
  93057. this._lastAbsoluteTransformsUpdateId = -1;
  93058. this._canUseTextureForBones = false;
  93059. /**
  93060. * Specifies if the skeleton should be serialized
  93061. */
  93062. this.doNotSerialize = false;
  93063. /**
  93064. * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).
  93065. * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it
  93066. */
  93067. this.useTextureToStoreBoneMatrices = true;
  93068. this._animationPropertiesOverride = null;
  93069. // Events
  93070. /**
  93071. * An observable triggered before computing the skeleton's matrices
  93072. */
  93073. this.onBeforeComputeObservable = new BABYLON.Observable();
  93074. this.bones = [];
  93075. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93076. this._scene.skeletons.push(this);
  93077. //make sure it will recalculate the matrix next time prepare is called.
  93078. this._isDirty = true;
  93079. var engineCaps = this._scene.getEngine().getCaps();
  93080. this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
  93081. }
  93082. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  93083. /**
  93084. * Gets or sets the animation properties override
  93085. */
  93086. get: function () {
  93087. if (!this._animationPropertiesOverride) {
  93088. return this._scene.animationPropertiesOverride;
  93089. }
  93090. return this._animationPropertiesOverride;
  93091. },
  93092. set: function (value) {
  93093. this._animationPropertiesOverride = value;
  93094. },
  93095. enumerable: true,
  93096. configurable: true
  93097. });
  93098. Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", {
  93099. /**
  93100. * Gets a boolean indicating that the skeleton effectively stores matrices into a texture
  93101. */
  93102. get: function () {
  93103. return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix;
  93104. },
  93105. enumerable: true,
  93106. configurable: true
  93107. });
  93108. // Members
  93109. /**
  93110. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  93111. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  93112. * @returns a Float32Array containing matrices data
  93113. */
  93114. Skeleton.prototype.getTransformMatrices = function (mesh) {
  93115. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  93116. return mesh._bonesTransformMatrices;
  93117. }
  93118. if (!this._transformMatrices) {
  93119. this.prepare();
  93120. }
  93121. return this._transformMatrices;
  93122. };
  93123. /**
  93124. * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)
  93125. * @returns a raw texture containing the data
  93126. */
  93127. Skeleton.prototype.getTransformMatrixTexture = function () {
  93128. return this._transformMatrixTexture;
  93129. };
  93130. /**
  93131. * Gets the current hosting scene
  93132. * @returns a scene object
  93133. */
  93134. Skeleton.prototype.getScene = function () {
  93135. return this._scene;
  93136. };
  93137. // Methods
  93138. /**
  93139. * Gets a string representing the current skeleton data
  93140. * @param fullDetails defines a boolean indicating if we want a verbose version
  93141. * @returns a string representing the current skeleton data
  93142. */
  93143. Skeleton.prototype.toString = function (fullDetails) {
  93144. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  93145. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  93146. if (fullDetails) {
  93147. ret += ", Ranges: {";
  93148. var first = true;
  93149. for (var name_1 in this._ranges) {
  93150. if (first) {
  93151. ret += ", ";
  93152. first = false;
  93153. }
  93154. ret += name_1;
  93155. }
  93156. ret += "}";
  93157. }
  93158. return ret;
  93159. };
  93160. /**
  93161. * Get bone's index searching by name
  93162. * @param name defines bone's name to search for
  93163. * @return the indice of the bone. Returns -1 if not found
  93164. */
  93165. Skeleton.prototype.getBoneIndexByName = function (name) {
  93166. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  93167. if (this.bones[boneIndex].name === name) {
  93168. return boneIndex;
  93169. }
  93170. }
  93171. return -1;
  93172. };
  93173. /**
  93174. * Creater a new animation range
  93175. * @param name defines the name of the range
  93176. * @param from defines the start key
  93177. * @param to defines the end key
  93178. */
  93179. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  93180. // check name not already in use
  93181. if (!this._ranges[name]) {
  93182. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  93183. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93184. if (this.bones[i].animations[0]) {
  93185. this.bones[i].animations[0].createRange(name, from, to);
  93186. }
  93187. }
  93188. }
  93189. };
  93190. /**
  93191. * Delete a specific animation range
  93192. * @param name defines the name of the range
  93193. * @param deleteFrames defines if frames must be removed as well
  93194. */
  93195. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  93196. if (deleteFrames === void 0) { deleteFrames = true; }
  93197. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93198. if (this.bones[i].animations[0]) {
  93199. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  93200. }
  93201. }
  93202. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  93203. };
  93204. /**
  93205. * Gets a specific animation range
  93206. * @param name defines the name of the range to look for
  93207. * @returns the requested animation range or null if not found
  93208. */
  93209. Skeleton.prototype.getAnimationRange = function (name) {
  93210. return this._ranges[name];
  93211. };
  93212. /**
  93213. * Gets the list of all animation ranges defined on this skeleton
  93214. * @returns an array
  93215. */
  93216. Skeleton.prototype.getAnimationRanges = function () {
  93217. var animationRanges = [];
  93218. var name;
  93219. var i = 0;
  93220. for (name in this._ranges) {
  93221. animationRanges[i] = this._ranges[name];
  93222. i++;
  93223. }
  93224. return animationRanges;
  93225. };
  93226. /**
  93227. * Copy animation range from a source skeleton.
  93228. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  93229. * @param source defines the source skeleton
  93230. * @param name defines the name of the range to copy
  93231. * @param rescaleAsRequired defines if rescaling must be applied if required
  93232. * @returns true if operation was successful
  93233. */
  93234. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  93235. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  93236. if (this._ranges[name] || !source.getAnimationRange(name)) {
  93237. return false;
  93238. }
  93239. var ret = true;
  93240. var frameOffset = this._getHighestAnimationFrame() + 1;
  93241. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  93242. var boneDict = {};
  93243. var sourceBones = source.bones;
  93244. var nBones;
  93245. var i;
  93246. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  93247. boneDict[sourceBones[i].name] = sourceBones[i];
  93248. }
  93249. if (this.bones.length !== sourceBones.length) {
  93250. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  93251. ret = false;
  93252. }
  93253. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  93254. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  93255. var boneName = this.bones[i].name;
  93256. var sourceBone = boneDict[boneName];
  93257. if (sourceBone) {
  93258. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  93259. }
  93260. else {
  93261. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  93262. ret = false;
  93263. }
  93264. }
  93265. // do not call createAnimationRange(), since it also is done to bones, which was already done
  93266. var range = source.getAnimationRange(name);
  93267. if (range) {
  93268. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  93269. }
  93270. return ret;
  93271. };
  93272. /**
  93273. * Forces the skeleton to go to rest pose
  93274. */
  93275. Skeleton.prototype.returnToRest = function () {
  93276. for (var index = 0; index < this.bones.length; index++) {
  93277. this.bones[index].returnToRest();
  93278. }
  93279. };
  93280. Skeleton.prototype._getHighestAnimationFrame = function () {
  93281. var ret = 0;
  93282. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93283. if (this.bones[i].animations[0]) {
  93284. var highest = this.bones[i].animations[0].getHighestFrame();
  93285. if (ret < highest) {
  93286. ret = highest;
  93287. }
  93288. }
  93289. }
  93290. return ret;
  93291. };
  93292. /**
  93293. * Begin a specific animation range
  93294. * @param name defines the name of the range to start
  93295. * @param loop defines if looping must be turned on (false by default)
  93296. * @param speedRatio defines the speed ratio to apply (1 by default)
  93297. * @param onAnimationEnd defines a callback which will be called when animation will end
  93298. * @returns a new animatable
  93299. */
  93300. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  93301. var range = this.getAnimationRange(name);
  93302. if (!range) {
  93303. return null;
  93304. }
  93305. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  93306. };
  93307. /** @hidden */
  93308. Skeleton.prototype._markAsDirty = function () {
  93309. this._isDirty = true;
  93310. };
  93311. /** @hidden */
  93312. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  93313. this._meshesWithPoseMatrix.push(mesh);
  93314. };
  93315. /** @hidden */
  93316. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  93317. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  93318. if (index > -1) {
  93319. this._meshesWithPoseMatrix.splice(index, 1);
  93320. }
  93321. };
  93322. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  93323. this.onBeforeComputeObservable.notifyObservers(this);
  93324. for (var index = 0; index < this.bones.length; index++) {
  93325. var bone = this.bones[index];
  93326. var parentBone = bone.getParent();
  93327. if (parentBone) {
  93328. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  93329. }
  93330. else {
  93331. if (initialSkinMatrix) {
  93332. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  93333. }
  93334. else {
  93335. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  93336. }
  93337. }
  93338. if (bone._index !== -1) {
  93339. var mappedIndex = bone._index === null ? index : bone._index;
  93340. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  93341. }
  93342. }
  93343. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  93344. };
  93345. /**
  93346. * Build all resources required to render a skeleton
  93347. */
  93348. Skeleton.prototype.prepare = function () {
  93349. if (!this._isDirty) {
  93350. return;
  93351. }
  93352. if (this.needInitialSkinMatrix) {
  93353. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  93354. var mesh = this._meshesWithPoseMatrix[index];
  93355. var poseMatrix = mesh.getPoseMatrix();
  93356. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  93357. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93358. }
  93359. if (this._synchronizedWithMesh !== mesh) {
  93360. this._synchronizedWithMesh = mesh;
  93361. // Prepare bones
  93362. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  93363. var bone = this.bones[boneIndex];
  93364. if (!bone.getParent()) {
  93365. var matrix = bone.getBaseMatrix();
  93366. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  93367. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  93368. }
  93369. }
  93370. }
  93371. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  93372. }
  93373. }
  93374. else {
  93375. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  93376. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93377. if (this.isUsingTextureForMatrices) {
  93378. if (this._transformMatrixTexture) {
  93379. this._transformMatrixTexture.dispose();
  93380. }
  93381. this._transformMatrixTexture = BABYLON.RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  93382. }
  93383. }
  93384. this._computeTransformMatrices(this._transformMatrices, null);
  93385. if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
  93386. this._transformMatrixTexture.update(this._transformMatrices);
  93387. }
  93388. }
  93389. this._isDirty = false;
  93390. this._scene._activeBones.addCount(this.bones.length, false);
  93391. };
  93392. /**
  93393. * Gets the list of animatables currently running for this skeleton
  93394. * @returns an array of animatables
  93395. */
  93396. Skeleton.prototype.getAnimatables = function () {
  93397. if (!this._animatables || this._animatables.length !== this.bones.length) {
  93398. this._animatables = [];
  93399. for (var index = 0; index < this.bones.length; index++) {
  93400. this._animatables.push(this.bones[index]);
  93401. }
  93402. }
  93403. return this._animatables;
  93404. };
  93405. /**
  93406. * Clone the current skeleton
  93407. * @param name defines the name of the new skeleton
  93408. * @param id defines the id of the enw skeleton
  93409. * @returns the new skeleton
  93410. */
  93411. Skeleton.prototype.clone = function (name, id) {
  93412. var result = new Skeleton(name, id || name, this._scene);
  93413. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93414. for (var index = 0; index < this.bones.length; index++) {
  93415. var source = this.bones[index];
  93416. var parentBone = null;
  93417. var parent_1 = source.getParent();
  93418. if (parent_1) {
  93419. var parentIndex = this.bones.indexOf(parent_1);
  93420. parentBone = result.bones[parentIndex];
  93421. }
  93422. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  93423. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  93424. }
  93425. if (this._ranges) {
  93426. result._ranges = {};
  93427. for (var rangeName in this._ranges) {
  93428. var range = this._ranges[rangeName];
  93429. if (range) {
  93430. result._ranges[rangeName] = range.clone();
  93431. }
  93432. }
  93433. }
  93434. this._isDirty = true;
  93435. return result;
  93436. };
  93437. /**
  93438. * Enable animation blending for this skeleton
  93439. * @param blendingSpeed defines the blending speed to apply
  93440. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  93441. */
  93442. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  93443. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  93444. this.bones.forEach(function (bone) {
  93445. bone.animations.forEach(function (animation) {
  93446. animation.enableBlending = true;
  93447. animation.blendingSpeed = blendingSpeed;
  93448. });
  93449. });
  93450. };
  93451. /**
  93452. * Releases all resources associated with the current skeleton
  93453. */
  93454. Skeleton.prototype.dispose = function () {
  93455. this._meshesWithPoseMatrix = [];
  93456. // Animations
  93457. this.getScene().stopAnimation(this);
  93458. // Remove from scene
  93459. this.getScene().removeSkeleton(this);
  93460. if (this._transformMatrixTexture) {
  93461. this._transformMatrixTexture.dispose();
  93462. this._transformMatrixTexture = null;
  93463. }
  93464. };
  93465. /**
  93466. * Serialize the skeleton in a JSON object
  93467. * @returns a JSON object
  93468. */
  93469. Skeleton.prototype.serialize = function () {
  93470. var serializationObject = {};
  93471. serializationObject.name = this.name;
  93472. serializationObject.id = this.id;
  93473. if (this.dimensionsAtRest) {
  93474. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  93475. }
  93476. serializationObject.bones = [];
  93477. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93478. for (var index = 0; index < this.bones.length; index++) {
  93479. var bone = this.bones[index];
  93480. var parent_2 = bone.getParent();
  93481. var serializedBone = {
  93482. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  93483. name: bone.name,
  93484. matrix: bone.getBaseMatrix().toArray(),
  93485. rest: bone.getRestPose().toArray()
  93486. };
  93487. serializationObject.bones.push(serializedBone);
  93488. if (bone.length) {
  93489. serializedBone.length = bone.length;
  93490. }
  93491. if (bone.metadata) {
  93492. serializedBone.metadata = bone.metadata;
  93493. }
  93494. if (bone.animations && bone.animations.length > 0) {
  93495. serializedBone.animation = bone.animations[0].serialize();
  93496. }
  93497. serializationObject.ranges = [];
  93498. for (var name in this._ranges) {
  93499. var source = this._ranges[name];
  93500. if (!source) {
  93501. continue;
  93502. }
  93503. var range = {};
  93504. range.name = name;
  93505. range.from = source.from;
  93506. range.to = source.to;
  93507. serializationObject.ranges.push(range);
  93508. }
  93509. }
  93510. return serializationObject;
  93511. };
  93512. /**
  93513. * Creates a new skeleton from serialized data
  93514. * @param parsedSkeleton defines the serialized data
  93515. * @param scene defines the hosting scene
  93516. * @returns a new skeleton
  93517. */
  93518. Skeleton.Parse = function (parsedSkeleton, scene) {
  93519. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  93520. if (parsedSkeleton.dimensionsAtRest) {
  93521. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  93522. }
  93523. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  93524. var index;
  93525. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  93526. var parsedBone = parsedSkeleton.bones[index];
  93527. var parentBone = null;
  93528. if (parsedBone.parentBoneIndex > -1) {
  93529. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  93530. }
  93531. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  93532. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  93533. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  93534. bone.id = parsedBone.id;
  93535. }
  93536. if (parsedBone.length) {
  93537. bone.length = parsedBone.length;
  93538. }
  93539. if (parsedBone.metadata) {
  93540. bone.metadata = parsedBone.metadata;
  93541. }
  93542. if (parsedBone.animation) {
  93543. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  93544. }
  93545. }
  93546. // placed after bones, so createAnimationRange can cascade down
  93547. if (parsedSkeleton.ranges) {
  93548. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  93549. var data = parsedSkeleton.ranges[index];
  93550. skeleton.createAnimationRange(data.name, data.from, data.to);
  93551. }
  93552. }
  93553. return skeleton;
  93554. };
  93555. /**
  93556. * Compute all node absolute transforms
  93557. * @param forceUpdate defines if computation must be done even if cache is up to date
  93558. */
  93559. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  93560. if (forceUpdate === void 0) { forceUpdate = false; }
  93561. var renderId = this._scene.getRenderId();
  93562. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  93563. this.bones[0].computeAbsoluteTransforms();
  93564. this._lastAbsoluteTransformsUpdateId = renderId;
  93565. }
  93566. };
  93567. /**
  93568. * Gets the root pose matrix
  93569. * @returns a matrix
  93570. */
  93571. Skeleton.prototype.getPoseMatrix = function () {
  93572. var poseMatrix = null;
  93573. if (this._meshesWithPoseMatrix.length > 0) {
  93574. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  93575. }
  93576. return poseMatrix;
  93577. };
  93578. /**
  93579. * Sorts bones per internal index
  93580. */
  93581. Skeleton.prototype.sortBones = function () {
  93582. var bones = new Array();
  93583. var visited = new Array(this.bones.length);
  93584. for (var index = 0; index < this.bones.length; index++) {
  93585. this._sortBones(index, bones, visited);
  93586. }
  93587. this.bones = bones;
  93588. };
  93589. Skeleton.prototype._sortBones = function (index, bones, visited) {
  93590. if (visited[index]) {
  93591. return;
  93592. }
  93593. visited[index] = true;
  93594. var bone = this.bones[index];
  93595. if (bone._index === undefined) {
  93596. bone._index = index;
  93597. }
  93598. var parentBone = bone.getParent();
  93599. if (parentBone) {
  93600. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  93601. }
  93602. bones.push(bone);
  93603. };
  93604. return Skeleton;
  93605. }());
  93606. BABYLON.Skeleton = Skeleton;
  93607. })(BABYLON || (BABYLON = {}));
  93608. //# sourceMappingURL=babylon.skeleton.js.map
  93609. var BABYLON;
  93610. (function (BABYLON) {
  93611. /**
  93612. * This groups tools to convert HDR texture to native colors array.
  93613. */
  93614. var HDRTools = /** @class */ (function () {
  93615. function HDRTools() {
  93616. }
  93617. HDRTools.Ldexp = function (mantissa, exponent) {
  93618. if (exponent > 1023) {
  93619. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  93620. }
  93621. if (exponent < -1074) {
  93622. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  93623. }
  93624. return mantissa * Math.pow(2, exponent);
  93625. };
  93626. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  93627. if (exponent > 0) { /*nonzero pixel*/
  93628. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  93629. float32array[index + 0] = red * exponent;
  93630. float32array[index + 1] = green * exponent;
  93631. float32array[index + 2] = blue * exponent;
  93632. }
  93633. else {
  93634. float32array[index + 0] = 0;
  93635. float32array[index + 1] = 0;
  93636. float32array[index + 2] = 0;
  93637. }
  93638. };
  93639. HDRTools.readStringLine = function (uint8array, startIndex) {
  93640. var line = "";
  93641. var character = "";
  93642. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  93643. character = String.fromCharCode(uint8array[i]);
  93644. if (character == "\n") {
  93645. break;
  93646. }
  93647. line += character;
  93648. }
  93649. return line;
  93650. };
  93651. /**
  93652. * Reads header information from an RGBE texture stored in a native array.
  93653. * More information on this format are available here:
  93654. * https://en.wikipedia.org/wiki/RGBE_image_format
  93655. *
  93656. * @param uint8array The binary file stored in native array.
  93657. * @return The header information.
  93658. */
  93659. HDRTools.RGBE_ReadHeader = function (uint8array) {
  93660. var height = 0;
  93661. var width = 0;
  93662. var line = this.readStringLine(uint8array, 0);
  93663. if (line[0] != '#' || line[1] != '?') {
  93664. throw "Bad HDR Format.";
  93665. }
  93666. var endOfHeader = false;
  93667. var findFormat = false;
  93668. var lineIndex = 0;
  93669. do {
  93670. lineIndex += (line.length + 1);
  93671. line = this.readStringLine(uint8array, lineIndex);
  93672. if (line == "FORMAT=32-bit_rle_rgbe") {
  93673. findFormat = true;
  93674. }
  93675. else if (line.length == 0) {
  93676. endOfHeader = true;
  93677. }
  93678. } while (!endOfHeader);
  93679. if (!findFormat) {
  93680. throw "HDR Bad header format, unsupported FORMAT";
  93681. }
  93682. lineIndex += (line.length + 1);
  93683. line = this.readStringLine(uint8array, lineIndex);
  93684. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  93685. var match = sizeRegexp.exec(line);
  93686. // TODO. Support +Y and -X if needed.
  93687. if (!match || match.length < 3) {
  93688. throw "HDR Bad header format, no size";
  93689. }
  93690. width = parseInt(match[2]);
  93691. height = parseInt(match[1]);
  93692. if (width < 8 || width > 0x7fff) {
  93693. throw "HDR Bad header format, unsupported size";
  93694. }
  93695. lineIndex += (line.length + 1);
  93696. return {
  93697. height: height,
  93698. width: width,
  93699. dataPosition: lineIndex
  93700. };
  93701. };
  93702. /**
  93703. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  93704. * This RGBE texture needs to store the information as a panorama.
  93705. *
  93706. * More information on this format are available here:
  93707. * https://en.wikipedia.org/wiki/RGBE_image_format
  93708. *
  93709. * @param buffer The binary file stored in an array buffer.
  93710. * @param size The expected size of the extracted cubemap.
  93711. * @return The Cube Map information.
  93712. */
  93713. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  93714. var uint8array = new Uint8Array(buffer);
  93715. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  93716. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93717. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  93718. return cubeMapData;
  93719. };
  93720. /**
  93721. * Returns the pixels data extracted from an RGBE texture.
  93722. * This pixels will be stored left to right up to down in the R G B order in one array.
  93723. *
  93724. * More information on this format are available here:
  93725. * https://en.wikipedia.org/wiki/RGBE_image_format
  93726. *
  93727. * @param uint8array The binary file stored in an array buffer.
  93728. * @param hdrInfo The header information of the file.
  93729. * @return The pixels data in RGB right to left up to down order.
  93730. */
  93731. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  93732. // Keep for multi format supports.
  93733. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93734. };
  93735. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  93736. var num_scanlines = hdrInfo.height;
  93737. var scanline_width = hdrInfo.width;
  93738. var a, b, c, d, count;
  93739. var dataIndex = hdrInfo.dataPosition;
  93740. var index = 0, endIndex = 0, i = 0;
  93741. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  93742. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  93743. // 3 channels of 4 bytes per pixel in float.
  93744. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  93745. var resultArray = new Float32Array(resultBuffer);
  93746. // read in each successive scanline
  93747. while (num_scanlines > 0) {
  93748. a = uint8array[dataIndex++];
  93749. b = uint8array[dataIndex++];
  93750. c = uint8array[dataIndex++];
  93751. d = uint8array[dataIndex++];
  93752. if (a != 2 || b != 2 || (c & 0x80)) {
  93753. // this file is not run length encoded
  93754. throw "HDR Bad header format, not RLE";
  93755. }
  93756. if (((c << 8) | d) != scanline_width) {
  93757. throw "HDR Bad header format, wrong scan line width";
  93758. }
  93759. index = 0;
  93760. // read each of the four channels for the scanline into the buffer
  93761. for (i = 0; i < 4; i++) {
  93762. endIndex = (i + 1) * scanline_width;
  93763. while (index < endIndex) {
  93764. a = uint8array[dataIndex++];
  93765. b = uint8array[dataIndex++];
  93766. if (a > 128) {
  93767. // a run of the same value
  93768. count = a - 128;
  93769. if ((count == 0) || (count > endIndex - index)) {
  93770. throw "HDR Bad Format, bad scanline data (run)";
  93771. }
  93772. while (count-- > 0) {
  93773. scanLineArray[index++] = b;
  93774. }
  93775. }
  93776. else {
  93777. // a non-run
  93778. count = a;
  93779. if ((count == 0) || (count > endIndex - index)) {
  93780. throw "HDR Bad Format, bad scanline data (non-run)";
  93781. }
  93782. scanLineArray[index++] = b;
  93783. if (--count > 0) {
  93784. for (var j = 0; j < count; j++) {
  93785. scanLineArray[index++] = uint8array[dataIndex++];
  93786. }
  93787. }
  93788. }
  93789. }
  93790. }
  93791. // now convert data from buffer into floats
  93792. for (i = 0; i < scanline_width; i++) {
  93793. a = scanLineArray[i];
  93794. b = scanLineArray[i + scanline_width];
  93795. c = scanLineArray[i + 2 * scanline_width];
  93796. d = scanLineArray[i + 3 * scanline_width];
  93797. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  93798. }
  93799. num_scanlines--;
  93800. }
  93801. return resultArray;
  93802. };
  93803. return HDRTools;
  93804. }());
  93805. BABYLON.HDRTools = HDRTools;
  93806. })(BABYLON || (BABYLON = {}));
  93807. //# sourceMappingURL=babylon.hdr.js.map
  93808. var BABYLON;
  93809. (function (BABYLON) {
  93810. /**
  93811. * This represents a texture coming from an HDR input.
  93812. *
  93813. * The only supported format is currently panorama picture stored in RGBE format.
  93814. * Example of such files can be found on HDRLib: http://hdrlib.com/
  93815. */
  93816. var HDRCubeTexture = /** @class */ (function (_super) {
  93817. __extends(HDRCubeTexture, _super);
  93818. /**
  93819. * Instantiates an HDRTexture from the following parameters.
  93820. *
  93821. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  93822. * @param scene The scene the texture will be used in
  93823. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  93824. * @param noMipmap Forces to not generate the mipmap if true
  93825. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  93826. * @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)
  93827. * @param reserved Reserved flag for internal use.
  93828. */
  93829. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  93830. if (noMipmap === void 0) { noMipmap = false; }
  93831. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93832. if (gammaSpace === void 0) { gammaSpace = false; }
  93833. if (reserved === void 0) { reserved = false; }
  93834. if (onLoad === void 0) { onLoad = null; }
  93835. if (onError === void 0) { onError = null; }
  93836. var _this = _super.call(this, scene) || this;
  93837. _this._generateHarmonics = true;
  93838. _this._onLoad = null;
  93839. _this._onError = null;
  93840. /**
  93841. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  93842. */
  93843. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  93844. _this._isBlocking = true;
  93845. _this._rotationY = 0;
  93846. /**
  93847. * Gets or sets the center of the bounding box associated with the cube texture
  93848. * It must define where the camera used to render the texture was set
  93849. */
  93850. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  93851. if (!url) {
  93852. return _this;
  93853. }
  93854. _this.name = url;
  93855. _this.url = url;
  93856. _this.hasAlpha = false;
  93857. _this.isCube = true;
  93858. _this._textureMatrix = BABYLON.Matrix.Identity();
  93859. _this._onLoad = onLoad;
  93860. _this._onError = onError;
  93861. _this.gammaSpace = gammaSpace;
  93862. _this._noMipmap = noMipmap;
  93863. _this._size = size;
  93864. _this._texture = _this._getFromCache(url, _this._noMipmap);
  93865. if (!_this._texture) {
  93866. if (!scene.useDelayedTextureLoading) {
  93867. _this.loadTexture();
  93868. }
  93869. else {
  93870. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  93871. }
  93872. }
  93873. return _this;
  93874. }
  93875. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  93876. /**
  93877. * Gets wether or not the texture is blocking during loading.
  93878. */
  93879. get: function () {
  93880. return this._isBlocking;
  93881. },
  93882. /**
  93883. * Sets wether or not the texture is blocking during loading.
  93884. */
  93885. set: function (value) {
  93886. this._isBlocking = value;
  93887. },
  93888. enumerable: true,
  93889. configurable: true
  93890. });
  93891. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  93892. /**
  93893. * Gets texture matrix rotation angle around Y axis radians.
  93894. */
  93895. get: function () {
  93896. return this._rotationY;
  93897. },
  93898. /**
  93899. * Sets texture matrix rotation angle around Y axis in radians.
  93900. */
  93901. set: function (value) {
  93902. this._rotationY = value;
  93903. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  93904. },
  93905. enumerable: true,
  93906. configurable: true
  93907. });
  93908. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  93909. get: function () {
  93910. return this._boundingBoxSize;
  93911. },
  93912. /**
  93913. * Gets or sets the size of the bounding box associated with the cube texture
  93914. * When defined, the cubemap will switch to local mode
  93915. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  93916. * @example https://www.babylonjs-playground.com/#RNASML
  93917. */
  93918. set: function (value) {
  93919. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  93920. return;
  93921. }
  93922. this._boundingBoxSize = value;
  93923. var scene = this.getScene();
  93924. if (scene) {
  93925. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  93926. }
  93927. },
  93928. enumerable: true,
  93929. configurable: true
  93930. });
  93931. /**
  93932. * Occurs when the file is raw .hdr file.
  93933. */
  93934. HDRCubeTexture.prototype.loadTexture = function () {
  93935. var _this = this;
  93936. var callback = function (buffer) {
  93937. _this.lodGenerationOffset = 0.0;
  93938. _this.lodGenerationScale = 0.8;
  93939. var scene = _this.getScene();
  93940. if (!scene) {
  93941. return null;
  93942. }
  93943. // Extract the raw linear data.
  93944. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  93945. // Generate harmonics if needed.
  93946. if (_this._generateHarmonics) {
  93947. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  93948. _this.sphericalPolynomial = sphericalPolynomial;
  93949. }
  93950. var results = [];
  93951. var byteArray = null;
  93952. // Push each faces.
  93953. for (var j = 0; j < 6; j++) {
  93954. // Create uintarray fallback.
  93955. if (!scene.getEngine().getCaps().textureFloat) {
  93956. // 3 channels of 1 bytes per pixel in bytes.
  93957. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  93958. byteArray = new Uint8Array(byteBuffer);
  93959. }
  93960. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  93961. // If special cases.
  93962. if (_this.gammaSpace || byteArray) {
  93963. for (var i = 0; i < _this._size * _this._size; i++) {
  93964. // Put in gamma space if requested.
  93965. if (_this.gammaSpace) {
  93966. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  93967. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  93968. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  93969. }
  93970. // Convert to int texture for fallback.
  93971. if (byteArray) {
  93972. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  93973. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  93974. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  93975. // May use luminance instead if the result is not accurate.
  93976. var max = Math.max(Math.max(r, g), b);
  93977. if (max > 255) {
  93978. var scale = 255 / max;
  93979. r *= scale;
  93980. g *= scale;
  93981. b *= scale;
  93982. }
  93983. byteArray[(i * 3) + 0] = r;
  93984. byteArray[(i * 3) + 1] = g;
  93985. byteArray[(i * 3) + 2] = b;
  93986. }
  93987. }
  93988. }
  93989. if (byteArray) {
  93990. results.push(byteArray);
  93991. }
  93992. else {
  93993. results.push(dataFace);
  93994. }
  93995. }
  93996. return results;
  93997. };
  93998. var scene = this.getScene();
  93999. if (scene) {
  94000. 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);
  94001. }
  94002. };
  94003. HDRCubeTexture.prototype.clone = function () {
  94004. var scene = this.getScene();
  94005. if (!scene) {
  94006. return this;
  94007. }
  94008. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  94009. // Base texture
  94010. newTexture.level = this.level;
  94011. newTexture.wrapU = this.wrapU;
  94012. newTexture.wrapV = this.wrapV;
  94013. newTexture.coordinatesIndex = this.coordinatesIndex;
  94014. newTexture.coordinatesMode = this.coordinatesMode;
  94015. return newTexture;
  94016. };
  94017. // Methods
  94018. HDRCubeTexture.prototype.delayLoad = function () {
  94019. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  94020. return;
  94021. }
  94022. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  94023. this._texture = this._getFromCache(this.url, this._noMipmap);
  94024. if (!this._texture) {
  94025. this.loadTexture();
  94026. }
  94027. };
  94028. /**
  94029. * Get the texture reflection matrix used to rotate/transform the reflection.
  94030. * @returns the reflection matrix
  94031. */
  94032. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  94033. return this._textureMatrix;
  94034. };
  94035. /**
  94036. * Set the texture reflection matrix used to rotate/transform the reflection.
  94037. * @param value Define the reflection matrix to set
  94038. */
  94039. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  94040. this._textureMatrix = value;
  94041. };
  94042. /**
  94043. * Parses a JSON representation of an HDR Texture in order to create the texture
  94044. * @param parsedTexture Define the JSON representation
  94045. * @param scene Define the scene the texture should be created in
  94046. * @param rootUrl Define the root url in case we need to load relative dependencies
  94047. * @returns the newly created texture after parsing
  94048. */
  94049. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  94050. var texture = null;
  94051. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  94052. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  94053. texture.name = parsedTexture.name;
  94054. texture.hasAlpha = parsedTexture.hasAlpha;
  94055. texture.level = parsedTexture.level;
  94056. texture.coordinatesMode = parsedTexture.coordinatesMode;
  94057. texture.isBlocking = parsedTexture.isBlocking;
  94058. }
  94059. if (texture) {
  94060. if (parsedTexture.boundingBoxPosition) {
  94061. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  94062. }
  94063. if (parsedTexture.boundingBoxSize) {
  94064. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  94065. }
  94066. if (parsedTexture.rotationY) {
  94067. texture.rotationY = parsedTexture.rotationY;
  94068. }
  94069. }
  94070. return texture;
  94071. };
  94072. HDRCubeTexture.prototype.serialize = function () {
  94073. if (!this.name) {
  94074. return null;
  94075. }
  94076. var serializationObject = {};
  94077. serializationObject.name = this.name;
  94078. serializationObject.hasAlpha = this.hasAlpha;
  94079. serializationObject.isCube = true;
  94080. serializationObject.level = this.level;
  94081. serializationObject.size = this._size;
  94082. serializationObject.coordinatesMode = this.coordinatesMode;
  94083. serializationObject.useInGammaSpace = this.gammaSpace;
  94084. serializationObject.generateHarmonics = this._generateHarmonics;
  94085. serializationObject.customType = "BABYLON.HDRCubeTexture";
  94086. serializationObject.noMipmap = this._noMipmap;
  94087. serializationObject.isBlocking = this._isBlocking;
  94088. serializationObject.rotationY = this._rotationY;
  94089. return serializationObject;
  94090. };
  94091. HDRCubeTexture._facesMapping = [
  94092. "right",
  94093. "left",
  94094. "up",
  94095. "down",
  94096. "front",
  94097. "back"
  94098. ];
  94099. return HDRCubeTexture;
  94100. }(BABYLON.BaseTexture));
  94101. BABYLON.HDRCubeTexture = HDRCubeTexture;
  94102. })(BABYLON || (BABYLON = {}));
  94103. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  94104. var BABYLON;
  94105. (function (BABYLON) {
  94106. /**
  94107. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  94108. */
  94109. var PanoramaToCubeMapTools = /** @class */ (function () {
  94110. function PanoramaToCubeMapTools() {
  94111. }
  94112. /**
  94113. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  94114. *
  94115. * @param float32Array The source data.
  94116. * @param inputWidth The width of the input panorama.
  94117. * @param inputHeight The height of the input panorama.
  94118. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  94119. * @return The cubemap data
  94120. */
  94121. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  94122. if (!float32Array) {
  94123. throw "ConvertPanoramaToCubemap: input cannot be null";
  94124. }
  94125. if (float32Array.length != inputWidth * inputHeight * 3) {
  94126. throw "ConvertPanoramaToCubemap: input size is wrong";
  94127. }
  94128. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  94129. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  94130. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  94131. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  94132. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  94133. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  94134. return {
  94135. front: textureFront,
  94136. back: textureBack,
  94137. left: textureLeft,
  94138. right: textureRight,
  94139. up: textureUp,
  94140. down: textureDown,
  94141. size: size,
  94142. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94143. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  94144. gammaSpace: false,
  94145. };
  94146. };
  94147. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  94148. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  94149. var textureArray = new Float32Array(buffer);
  94150. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  94151. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  94152. var dy = 1 / texSize;
  94153. var fy = 0;
  94154. for (var y = 0; y < texSize; y++) {
  94155. var xv1 = faceData[0];
  94156. var xv2 = faceData[2];
  94157. for (var x = 0; x < texSize; x++) {
  94158. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  94159. v.normalize();
  94160. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  94161. // 3 channels per pixels
  94162. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  94163. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  94164. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  94165. xv1 = xv1.add(rotDX1);
  94166. xv2 = xv2.add(rotDX2);
  94167. }
  94168. fy += dy;
  94169. }
  94170. return textureArray;
  94171. };
  94172. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  94173. var theta = Math.atan2(vDir.z, vDir.x);
  94174. var phi = Math.acos(vDir.y);
  94175. while (theta < -Math.PI) {
  94176. theta += 2 * Math.PI;
  94177. }
  94178. while (theta > Math.PI) {
  94179. theta -= 2 * Math.PI;
  94180. }
  94181. var dx = theta / Math.PI;
  94182. var dy = phi / Math.PI;
  94183. // recenter.
  94184. dx = dx * 0.5 + 0.5;
  94185. var px = Math.round(dx * inputWidth);
  94186. if (px < 0) {
  94187. px = 0;
  94188. }
  94189. else if (px >= inputWidth) {
  94190. px = inputWidth - 1;
  94191. }
  94192. var py = Math.round(dy * inputHeight);
  94193. if (py < 0) {
  94194. py = 0;
  94195. }
  94196. else if (py >= inputHeight) {
  94197. py = inputHeight - 1;
  94198. }
  94199. var inputY = (inputHeight - py - 1);
  94200. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  94201. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  94202. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  94203. return {
  94204. r: r,
  94205. g: g,
  94206. b: b
  94207. };
  94208. };
  94209. PanoramaToCubeMapTools.FACE_FRONT = [
  94210. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94211. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94212. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94213. new BABYLON.Vector3(1.0, 1.0, -1.0)
  94214. ];
  94215. PanoramaToCubeMapTools.FACE_BACK = [
  94216. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94217. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94218. new BABYLON.Vector3(1.0, 1.0, 1.0),
  94219. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  94220. ];
  94221. PanoramaToCubeMapTools.FACE_RIGHT = [
  94222. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94223. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94224. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94225. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94226. ];
  94227. PanoramaToCubeMapTools.FACE_LEFT = [
  94228. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94229. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94230. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94231. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  94232. ];
  94233. PanoramaToCubeMapTools.FACE_DOWN = [
  94234. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94235. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94236. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94237. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94238. ];
  94239. PanoramaToCubeMapTools.FACE_UP = [
  94240. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94241. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94242. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94243. new BABYLON.Vector3(1.0, -1.0, -1.0)
  94244. ];
  94245. return PanoramaToCubeMapTools;
  94246. }());
  94247. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  94248. })(BABYLON || (BABYLON = {}));
  94249. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  94250. var BABYLON;
  94251. (function (BABYLON) {
  94252. /**
  94253. * Vector2 wth index property
  94254. */
  94255. var IndexedVector2 = /** @class */ (function (_super) {
  94256. __extends(IndexedVector2, _super);
  94257. function IndexedVector2(original,
  94258. /** Index of the vector2 */
  94259. index) {
  94260. var _this = _super.call(this, original.x, original.y) || this;
  94261. _this.index = index;
  94262. return _this;
  94263. }
  94264. return IndexedVector2;
  94265. }(BABYLON.Vector2));
  94266. /**
  94267. * Defines points to create a polygon
  94268. */
  94269. var PolygonPoints = /** @class */ (function () {
  94270. function PolygonPoints() {
  94271. this.elements = new Array();
  94272. }
  94273. PolygonPoints.prototype.add = function (originalPoints) {
  94274. var _this = this;
  94275. var result = new Array();
  94276. originalPoints.forEach(function (point) {
  94277. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  94278. var newPoint = new IndexedVector2(point, _this.elements.length);
  94279. result.push(newPoint);
  94280. _this.elements.push(newPoint);
  94281. }
  94282. });
  94283. return result;
  94284. };
  94285. PolygonPoints.prototype.computeBounds = function () {
  94286. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94287. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94288. this.elements.forEach(function (point) {
  94289. // x
  94290. if (point.x < lmin.x) {
  94291. lmin.x = point.x;
  94292. }
  94293. else if (point.x > lmax.x) {
  94294. lmax.x = point.x;
  94295. }
  94296. // y
  94297. if (point.y < lmin.y) {
  94298. lmin.y = point.y;
  94299. }
  94300. else if (point.y > lmax.y) {
  94301. lmax.y = point.y;
  94302. }
  94303. });
  94304. return {
  94305. min: lmin,
  94306. max: lmax,
  94307. width: lmax.x - lmin.x,
  94308. height: lmax.y - lmin.y
  94309. };
  94310. };
  94311. return PolygonPoints;
  94312. }());
  94313. /**
  94314. * Polygon
  94315. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  94316. */
  94317. var Polygon = /** @class */ (function () {
  94318. function Polygon() {
  94319. }
  94320. /**
  94321. * Creates a rectangle
  94322. * @param xmin bottom X coord
  94323. * @param ymin bottom Y coord
  94324. * @param xmax top X coord
  94325. * @param ymax top Y coord
  94326. * @returns points that make the resulting rectation
  94327. */
  94328. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  94329. return [
  94330. new BABYLON.Vector2(xmin, ymin),
  94331. new BABYLON.Vector2(xmax, ymin),
  94332. new BABYLON.Vector2(xmax, ymax),
  94333. new BABYLON.Vector2(xmin, ymax)
  94334. ];
  94335. };
  94336. /**
  94337. * Creates a circle
  94338. * @param radius radius of circle
  94339. * @param cx scale in x
  94340. * @param cy scale in y
  94341. * @param numberOfSides number of sides that make up the circle
  94342. * @returns points that make the resulting circle
  94343. */
  94344. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  94345. if (cx === void 0) { cx = 0; }
  94346. if (cy === void 0) { cy = 0; }
  94347. if (numberOfSides === void 0) { numberOfSides = 32; }
  94348. var result = new Array();
  94349. var angle = 0;
  94350. var increment = (Math.PI * 2) / numberOfSides;
  94351. for (var i = 0; i < numberOfSides; i++) {
  94352. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  94353. angle -= increment;
  94354. }
  94355. return result;
  94356. };
  94357. /**
  94358. * Creates a polygon from input string
  94359. * @param input Input polygon data
  94360. * @returns the parsed points
  94361. */
  94362. Polygon.Parse = function (input) {
  94363. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  94364. var i, result = [];
  94365. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  94366. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  94367. }
  94368. return result;
  94369. };
  94370. /**
  94371. * Starts building a polygon from x and y coordinates
  94372. * @param x x coordinate
  94373. * @param y y coordinate
  94374. * @returns the started path2
  94375. */
  94376. Polygon.StartingAt = function (x, y) {
  94377. return BABYLON.Path2.StartingAt(x, y);
  94378. };
  94379. return Polygon;
  94380. }());
  94381. BABYLON.Polygon = Polygon;
  94382. /**
  94383. * Builds a polygon
  94384. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  94385. */
  94386. var PolygonMeshBuilder = /** @class */ (function () {
  94387. /**
  94388. * Creates a PolygonMeshBuilder
  94389. * @param name name of the builder
  94390. * @param contours Path of the polygon
  94391. * @param scene scene to add to
  94392. */
  94393. function PolygonMeshBuilder(name, contours, scene) {
  94394. this._points = new PolygonPoints();
  94395. this._outlinepoints = new PolygonPoints();
  94396. this._holes = new Array();
  94397. this._epoints = new Array();
  94398. this._eholes = new Array();
  94399. this._name = name;
  94400. this._scene = scene;
  94401. var points;
  94402. if (contours instanceof BABYLON.Path2) {
  94403. points = contours.getPoints();
  94404. }
  94405. else {
  94406. points = contours;
  94407. }
  94408. this._addToepoint(points);
  94409. this._points.add(points);
  94410. this._outlinepoints.add(points);
  94411. if (typeof earcut === 'undefined') {
  94412. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  94413. }
  94414. }
  94415. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  94416. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  94417. var p = points_1[_i];
  94418. this._epoints.push(p.x, p.y);
  94419. }
  94420. };
  94421. /**
  94422. * Adds a whole within the polygon
  94423. * @param hole Array of points defining the hole
  94424. * @returns this
  94425. */
  94426. PolygonMeshBuilder.prototype.addHole = function (hole) {
  94427. this._points.add(hole);
  94428. var holepoints = new PolygonPoints();
  94429. holepoints.add(hole);
  94430. this._holes.push(holepoints);
  94431. this._eholes.push(this._epoints.length / 2);
  94432. this._addToepoint(hole);
  94433. return this;
  94434. };
  94435. /**
  94436. * Creates the polygon
  94437. * @param updatable If the mesh should be updatable
  94438. * @param depth The depth of the mesh created
  94439. * @returns the created mesh
  94440. */
  94441. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  94442. var _this = this;
  94443. if (updatable === void 0) { updatable = false; }
  94444. if (depth === void 0) { depth = 0; }
  94445. var result = new BABYLON.Mesh(this._name, this._scene);
  94446. var normals = new Array();
  94447. var positions = new Array();
  94448. var uvs = new Array();
  94449. var bounds = this._points.computeBounds();
  94450. this._points.elements.forEach(function (p) {
  94451. normals.push(0, 1.0, 0);
  94452. positions.push(p.x, 0, p.y);
  94453. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  94454. });
  94455. var indices = new Array();
  94456. var res = earcut(this._epoints, this._eholes, 2);
  94457. for (var i = 0; i < res.length; i++) {
  94458. indices.push(res[i]);
  94459. }
  94460. if (depth > 0) {
  94461. var positionscount = (positions.length / 3); //get the current pointcount
  94462. this._points.elements.forEach(function (p) {
  94463. normals.push(0, -1.0, 0);
  94464. positions.push(p.x, -depth, p.y);
  94465. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  94466. });
  94467. var totalCount = indices.length;
  94468. for (var i = 0; i < totalCount; i += 3) {
  94469. var i0 = indices[i + 0];
  94470. var i1 = indices[i + 1];
  94471. var i2 = indices[i + 2];
  94472. indices.push(i2 + positionscount);
  94473. indices.push(i1 + positionscount);
  94474. indices.push(i0 + positionscount);
  94475. }
  94476. //Add the sides
  94477. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  94478. this._holes.forEach(function (hole) {
  94479. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  94480. });
  94481. }
  94482. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  94483. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  94484. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  94485. result.setIndices(indices);
  94486. return result;
  94487. };
  94488. /**
  94489. * Adds a side to the polygon
  94490. * @param positions points that make the polygon
  94491. * @param normals normals of the polygon
  94492. * @param uvs uvs of the polygon
  94493. * @param indices indices of the polygon
  94494. * @param bounds bounds of the polygon
  94495. * @param points points of the polygon
  94496. * @param depth depth of the polygon
  94497. * @param flip flip of the polygon
  94498. */
  94499. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  94500. var StartIndex = positions.length / 3;
  94501. var ulength = 0;
  94502. for (var i = 0; i < points.elements.length; i++) {
  94503. var p = points.elements[i];
  94504. var p1;
  94505. if ((i + 1) > points.elements.length - 1) {
  94506. p1 = points.elements[0];
  94507. }
  94508. else {
  94509. p1 = points.elements[i + 1];
  94510. }
  94511. positions.push(p.x, 0, p.y);
  94512. positions.push(p.x, -depth, p.y);
  94513. positions.push(p1.x, 0, p1.y);
  94514. positions.push(p1.x, -depth, p1.y);
  94515. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  94516. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  94517. var v3 = v2.subtract(v1);
  94518. var v4 = new BABYLON.Vector3(0, 1, 0);
  94519. var vn = BABYLON.Vector3.Cross(v3, v4);
  94520. vn = vn.normalize();
  94521. uvs.push(ulength / bounds.width, 0);
  94522. uvs.push(ulength / bounds.width, 1);
  94523. ulength += v3.length();
  94524. uvs.push((ulength / bounds.width), 0);
  94525. uvs.push((ulength / bounds.width), 1);
  94526. if (!flip) {
  94527. normals.push(-vn.x, -vn.y, -vn.z);
  94528. normals.push(-vn.x, -vn.y, -vn.z);
  94529. normals.push(-vn.x, -vn.y, -vn.z);
  94530. normals.push(-vn.x, -vn.y, -vn.z);
  94531. indices.push(StartIndex);
  94532. indices.push(StartIndex + 1);
  94533. indices.push(StartIndex + 2);
  94534. indices.push(StartIndex + 1);
  94535. indices.push(StartIndex + 3);
  94536. indices.push(StartIndex + 2);
  94537. }
  94538. else {
  94539. normals.push(vn.x, vn.y, vn.z);
  94540. normals.push(vn.x, vn.y, vn.z);
  94541. normals.push(vn.x, vn.y, vn.z);
  94542. normals.push(vn.x, vn.y, vn.z);
  94543. indices.push(StartIndex);
  94544. indices.push(StartIndex + 2);
  94545. indices.push(StartIndex + 1);
  94546. indices.push(StartIndex + 1);
  94547. indices.push(StartIndex + 2);
  94548. indices.push(StartIndex + 3);
  94549. }
  94550. StartIndex += 4;
  94551. }
  94552. };
  94553. return PolygonMeshBuilder;
  94554. }());
  94555. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  94556. })(BABYLON || (BABYLON = {}));
  94557. //# sourceMappingURL=babylon.polygonMesh.js.map
  94558. var BABYLON;
  94559. (function (BABYLON) {
  94560. /**
  94561. * Unique ID when we import meshes from Babylon to CSG
  94562. */
  94563. var currentCSGMeshId = 0;
  94564. /**
  94565. * Represents a vertex of a polygon. Use your own vertex class instead of this
  94566. * one to provide additional features like texture coordinates and vertex
  94567. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  94568. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  94569. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  94570. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  94571. * is not used anywhere else.
  94572. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  94573. */
  94574. var Vertex = /** @class */ (function () {
  94575. /**
  94576. * Initializes the vertex
  94577. * @param pos The position of the vertex
  94578. * @param normal The normal of the vertex
  94579. * @param uv The texture coordinate of the vertex
  94580. */
  94581. function Vertex(
  94582. /**
  94583. * The position of the vertex
  94584. */
  94585. pos,
  94586. /**
  94587. * The normal of the vertex
  94588. */
  94589. normal,
  94590. /**
  94591. * The texture coordinate of the vertex
  94592. */
  94593. uv) {
  94594. this.pos = pos;
  94595. this.normal = normal;
  94596. this.uv = uv;
  94597. }
  94598. /**
  94599. * Make a clone, or deep copy, of the vertex
  94600. * @returns A new Vertex
  94601. */
  94602. Vertex.prototype.clone = function () {
  94603. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  94604. };
  94605. /**
  94606. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  94607. * orientation of a polygon is flipped.
  94608. */
  94609. Vertex.prototype.flip = function () {
  94610. this.normal = this.normal.scale(-1);
  94611. };
  94612. /**
  94613. * Create a new vertex between this vertex and `other` by linearly
  94614. * interpolating all properties using a parameter of `t`. Subclasses should
  94615. * override this to interpolate additional properties.
  94616. * @param other the vertex to interpolate against
  94617. * @param t The factor used to linearly interpolate between the vertices
  94618. */
  94619. Vertex.prototype.interpolate = function (other, t) {
  94620. 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));
  94621. };
  94622. return Vertex;
  94623. }());
  94624. /**
  94625. * Represents a plane in 3D space.
  94626. */
  94627. var Plane = /** @class */ (function () {
  94628. /**
  94629. * Initializes the plane
  94630. * @param normal The normal for the plane
  94631. * @param w
  94632. */
  94633. function Plane(normal, w) {
  94634. this.normal = normal;
  94635. this.w = w;
  94636. }
  94637. /**
  94638. * Construct a plane from three points
  94639. * @param a Point a
  94640. * @param b Point b
  94641. * @param c Point c
  94642. */
  94643. Plane.FromPoints = function (a, b, c) {
  94644. var v0 = c.subtract(a);
  94645. var v1 = b.subtract(a);
  94646. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  94647. return null;
  94648. }
  94649. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  94650. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  94651. };
  94652. /**
  94653. * Clone, or make a deep copy of the plane
  94654. * @returns a new Plane
  94655. */
  94656. Plane.prototype.clone = function () {
  94657. return new Plane(this.normal.clone(), this.w);
  94658. };
  94659. /**
  94660. * Flip the face of the plane
  94661. */
  94662. Plane.prototype.flip = function () {
  94663. this.normal.scaleInPlace(-1);
  94664. this.w = -this.w;
  94665. };
  94666. /**
  94667. * Split `polygon` by this plane if needed, then put the polygon or polygon
  94668. * fragments in the appropriate lists. Coplanar polygons go into either
  94669. `* coplanarFront` or `coplanarBack` depending on their orientation with
  94670. * respect to this plane. Polygons in front or in back of this plane go into
  94671. * either `front` or `back`
  94672. * @param polygon The polygon to be split
  94673. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  94674. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  94675. * @param front Will contain the polygons in front of the plane
  94676. * @param back Will contain the polygons begind the plane
  94677. */
  94678. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  94679. var COPLANAR = 0;
  94680. var FRONT = 1;
  94681. var BACK = 2;
  94682. var SPANNING = 3;
  94683. // Classify each point as well as the entire polygon into one of the above
  94684. // four classes.
  94685. var polygonType = 0;
  94686. var types = [];
  94687. var i;
  94688. var t;
  94689. for (i = 0; i < polygon.vertices.length; i++) {
  94690. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  94691. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  94692. polygonType |= type;
  94693. types.push(type);
  94694. }
  94695. // Put the polygon in the correct list, splitting it when necessary
  94696. switch (polygonType) {
  94697. case COPLANAR:
  94698. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  94699. break;
  94700. case FRONT:
  94701. front.push(polygon);
  94702. break;
  94703. case BACK:
  94704. back.push(polygon);
  94705. break;
  94706. case SPANNING:
  94707. var f = [], b = [];
  94708. for (i = 0; i < polygon.vertices.length; i++) {
  94709. var j = (i + 1) % polygon.vertices.length;
  94710. var ti = types[i], tj = types[j];
  94711. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  94712. if (ti !== BACK) {
  94713. f.push(vi);
  94714. }
  94715. if (ti !== FRONT) {
  94716. b.push(ti !== BACK ? vi.clone() : vi);
  94717. }
  94718. if ((ti | tj) === SPANNING) {
  94719. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  94720. var v = vi.interpolate(vj, t);
  94721. f.push(v);
  94722. b.push(v.clone());
  94723. }
  94724. }
  94725. var poly;
  94726. if (f.length >= 3) {
  94727. poly = new Polygon(f, polygon.shared);
  94728. if (poly.plane) {
  94729. front.push(poly);
  94730. }
  94731. }
  94732. if (b.length >= 3) {
  94733. poly = new Polygon(b, polygon.shared);
  94734. if (poly.plane) {
  94735. back.push(poly);
  94736. }
  94737. }
  94738. break;
  94739. }
  94740. };
  94741. /**
  94742. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  94743. * point is on the plane
  94744. */
  94745. Plane.EPSILON = 1e-5;
  94746. return Plane;
  94747. }());
  94748. /**
  94749. * Represents a convex polygon. The vertices used to initialize a polygon must
  94750. * be coplanar and form a convex loop.
  94751. *
  94752. * Each convex polygon has a `shared` property, which is shared between all
  94753. * polygons that are clones of each other or were split from the same polygon.
  94754. * This can be used to define per-polygon properties (such as surface color)
  94755. */
  94756. var Polygon = /** @class */ (function () {
  94757. /**
  94758. * Initializes the polygon
  94759. * @param vertices The vertices of the polygon
  94760. * @param shared The properties shared across all polygons
  94761. */
  94762. function Polygon(vertices, shared) {
  94763. this.vertices = vertices;
  94764. this.shared = shared;
  94765. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  94766. }
  94767. /**
  94768. * Clones, or makes a deep copy, or the polygon
  94769. */
  94770. Polygon.prototype.clone = function () {
  94771. var vertices = this.vertices.map(function (v) { return v.clone(); });
  94772. return new Polygon(vertices, this.shared);
  94773. };
  94774. /**
  94775. * Flips the faces of the polygon
  94776. */
  94777. Polygon.prototype.flip = function () {
  94778. this.vertices.reverse().map(function (v) { v.flip(); });
  94779. this.plane.flip();
  94780. };
  94781. return Polygon;
  94782. }());
  94783. /**
  94784. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  94785. * by picking a polygon to split along. That polygon (and all other coplanar
  94786. * polygons) are added directly to that node and the other polygons are added to
  94787. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  94788. * no distinction between internal and leaf nodes
  94789. */
  94790. var Node = /** @class */ (function () {
  94791. /**
  94792. * Initializes the node
  94793. * @param polygons A collection of polygons held in the node
  94794. */
  94795. function Node(polygons) {
  94796. this.plane = null;
  94797. this.front = null;
  94798. this.back = null;
  94799. this.polygons = new Array();
  94800. if (polygons) {
  94801. this.build(polygons);
  94802. }
  94803. }
  94804. /**
  94805. * Clones, or makes a deep copy, of the node
  94806. * @returns The cloned node
  94807. */
  94808. Node.prototype.clone = function () {
  94809. var node = new Node();
  94810. node.plane = this.plane && this.plane.clone();
  94811. node.front = this.front && this.front.clone();
  94812. node.back = this.back && this.back.clone();
  94813. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  94814. return node;
  94815. };
  94816. /**
  94817. * Convert solid space to empty space and empty space to solid space
  94818. */
  94819. Node.prototype.invert = function () {
  94820. for (var i = 0; i < this.polygons.length; i++) {
  94821. this.polygons[i].flip();
  94822. }
  94823. if (this.plane) {
  94824. this.plane.flip();
  94825. }
  94826. if (this.front) {
  94827. this.front.invert();
  94828. }
  94829. if (this.back) {
  94830. this.back.invert();
  94831. }
  94832. var temp = this.front;
  94833. this.front = this.back;
  94834. this.back = temp;
  94835. };
  94836. /**
  94837. * Recursively remove all polygons in `polygons` that are inside this BSP
  94838. * tree.
  94839. * @param polygons Polygons to remove from the BSP
  94840. * @returns Polygons clipped from the BSP
  94841. */
  94842. Node.prototype.clipPolygons = function (polygons) {
  94843. if (!this.plane) {
  94844. return polygons.slice();
  94845. }
  94846. var front = new Array(), back = new Array();
  94847. for (var i = 0; i < polygons.length; i++) {
  94848. this.plane.splitPolygon(polygons[i], front, back, front, back);
  94849. }
  94850. if (this.front) {
  94851. front = this.front.clipPolygons(front);
  94852. }
  94853. if (this.back) {
  94854. back = this.back.clipPolygons(back);
  94855. }
  94856. else {
  94857. back = [];
  94858. }
  94859. return front.concat(back);
  94860. };
  94861. /**
  94862. * Remove all polygons in this BSP tree that are inside the other BSP tree
  94863. * `bsp`.
  94864. * @param bsp BSP containing polygons to remove from this BSP
  94865. */
  94866. Node.prototype.clipTo = function (bsp) {
  94867. this.polygons = bsp.clipPolygons(this.polygons);
  94868. if (this.front) {
  94869. this.front.clipTo(bsp);
  94870. }
  94871. if (this.back) {
  94872. this.back.clipTo(bsp);
  94873. }
  94874. };
  94875. /**
  94876. * Return a list of all polygons in this BSP tree
  94877. * @returns List of all polygons in this BSP tree
  94878. */
  94879. Node.prototype.allPolygons = function () {
  94880. var polygons = this.polygons.slice();
  94881. if (this.front) {
  94882. polygons = polygons.concat(this.front.allPolygons());
  94883. }
  94884. if (this.back) {
  94885. polygons = polygons.concat(this.back.allPolygons());
  94886. }
  94887. return polygons;
  94888. };
  94889. /**
  94890. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  94891. * new polygons are filtered down to the bottom of the tree and become new
  94892. * nodes there. Each set of polygons is partitioned using the first polygon
  94893. * (no heuristic is used to pick a good split)
  94894. * @param polygons Polygons used to construct the BSP tree
  94895. */
  94896. Node.prototype.build = function (polygons) {
  94897. if (!polygons.length) {
  94898. return;
  94899. }
  94900. if (!this.plane) {
  94901. this.plane = polygons[0].plane.clone();
  94902. }
  94903. var front = new Array(), back = new Array();
  94904. for (var i = 0; i < polygons.length; i++) {
  94905. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  94906. }
  94907. if (front.length) {
  94908. if (!this.front) {
  94909. this.front = new Node();
  94910. }
  94911. this.front.build(front);
  94912. }
  94913. if (back.length) {
  94914. if (!this.back) {
  94915. this.back = new Node();
  94916. }
  94917. this.back.build(back);
  94918. }
  94919. };
  94920. return Node;
  94921. }());
  94922. /**
  94923. * Class for building Constructive Solid Geometry
  94924. */
  94925. var CSG = /** @class */ (function () {
  94926. function CSG() {
  94927. this.polygons = new Array();
  94928. }
  94929. /**
  94930. * Convert the BABYLON.Mesh to BABYLON.CSG
  94931. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  94932. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  94933. */
  94934. CSG.FromMesh = function (mesh) {
  94935. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  94936. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  94937. if (mesh instanceof BABYLON.Mesh) {
  94938. mesh.computeWorldMatrix(true);
  94939. matrix = mesh.getWorldMatrix();
  94940. meshPosition = mesh.position.clone();
  94941. meshRotation = mesh.rotation.clone();
  94942. if (mesh.rotationQuaternion) {
  94943. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  94944. }
  94945. meshScaling = mesh.scaling.clone();
  94946. }
  94947. else {
  94948. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  94949. }
  94950. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94951. var subMeshes = mesh.subMeshes;
  94952. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  94953. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  94954. vertices = [];
  94955. for (var j = 0; j < 3; j++) {
  94956. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  94957. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  94958. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  94959. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  94960. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  94961. vertex = new Vertex(position, normal, uv);
  94962. vertices.push(vertex);
  94963. }
  94964. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  94965. // To handle the case of degenerated triangle
  94966. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  94967. if (polygon.plane) {
  94968. polygons.push(polygon);
  94969. }
  94970. }
  94971. }
  94972. var csg = CSG.FromPolygons(polygons);
  94973. csg.matrix = matrix;
  94974. csg.position = meshPosition;
  94975. csg.rotation = meshRotation;
  94976. csg.scaling = meshScaling;
  94977. csg.rotationQuaternion = meshRotationQuaternion;
  94978. currentCSGMeshId++;
  94979. return csg;
  94980. };
  94981. /**
  94982. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  94983. * @param polygons Polygons used to construct a BABYLON.CSG solid
  94984. */
  94985. CSG.FromPolygons = function (polygons) {
  94986. var csg = new CSG();
  94987. csg.polygons = polygons;
  94988. return csg;
  94989. };
  94990. /**
  94991. * Clones, or makes a deep copy, of the BABYLON.CSG
  94992. * @returns A new BABYLON.CSG
  94993. */
  94994. CSG.prototype.clone = function () {
  94995. var csg = new CSG();
  94996. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  94997. csg.copyTransformAttributes(this);
  94998. return csg;
  94999. };
  95000. /**
  95001. * Unions this CSG with another CSG
  95002. * @param csg The CSG to union against this CSG
  95003. * @returns The unioned CSG
  95004. */
  95005. CSG.prototype.union = function (csg) {
  95006. var a = new Node(this.clone().polygons);
  95007. var b = new Node(csg.clone().polygons);
  95008. a.clipTo(b);
  95009. b.clipTo(a);
  95010. b.invert();
  95011. b.clipTo(a);
  95012. b.invert();
  95013. a.build(b.allPolygons());
  95014. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95015. };
  95016. /**
  95017. * Unions this CSG with another CSG in place
  95018. * @param csg The CSG to union against this CSG
  95019. */
  95020. CSG.prototype.unionInPlace = function (csg) {
  95021. var a = new Node(this.polygons);
  95022. var b = new Node(csg.polygons);
  95023. a.clipTo(b);
  95024. b.clipTo(a);
  95025. b.invert();
  95026. b.clipTo(a);
  95027. b.invert();
  95028. a.build(b.allPolygons());
  95029. this.polygons = a.allPolygons();
  95030. };
  95031. /**
  95032. * Subtracts this CSG with another CSG
  95033. * @param csg The CSG to subtract against this CSG
  95034. * @returns A new BABYLON.CSG
  95035. */
  95036. CSG.prototype.subtract = function (csg) {
  95037. var a = new Node(this.clone().polygons);
  95038. var b = new Node(csg.clone().polygons);
  95039. a.invert();
  95040. a.clipTo(b);
  95041. b.clipTo(a);
  95042. b.invert();
  95043. b.clipTo(a);
  95044. b.invert();
  95045. a.build(b.allPolygons());
  95046. a.invert();
  95047. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95048. };
  95049. /**
  95050. * Subtracts this CSG with another CSG in place
  95051. * @param csg The CSG to subtact against this CSG
  95052. */
  95053. CSG.prototype.subtractInPlace = function (csg) {
  95054. var a = new Node(this.polygons);
  95055. var b = new Node(csg.polygons);
  95056. a.invert();
  95057. a.clipTo(b);
  95058. b.clipTo(a);
  95059. b.invert();
  95060. b.clipTo(a);
  95061. b.invert();
  95062. a.build(b.allPolygons());
  95063. a.invert();
  95064. this.polygons = a.allPolygons();
  95065. };
  95066. /**
  95067. * Intersect this CSG with another CSG
  95068. * @param csg The CSG to intersect against this CSG
  95069. * @returns A new BABYLON.CSG
  95070. */
  95071. CSG.prototype.intersect = function (csg) {
  95072. var a = new Node(this.clone().polygons);
  95073. var b = new Node(csg.clone().polygons);
  95074. a.invert();
  95075. b.clipTo(a);
  95076. b.invert();
  95077. a.clipTo(b);
  95078. b.clipTo(a);
  95079. a.build(b.allPolygons());
  95080. a.invert();
  95081. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95082. };
  95083. /**
  95084. * Intersects this CSG with another CSG in place
  95085. * @param csg The CSG to intersect against this CSG
  95086. */
  95087. CSG.prototype.intersectInPlace = function (csg) {
  95088. var a = new Node(this.polygons);
  95089. var b = new Node(csg.polygons);
  95090. a.invert();
  95091. b.clipTo(a);
  95092. b.invert();
  95093. a.clipTo(b);
  95094. b.clipTo(a);
  95095. a.build(b.allPolygons());
  95096. a.invert();
  95097. this.polygons = a.allPolygons();
  95098. };
  95099. /**
  95100. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  95101. * not modified.
  95102. * @returns A new BABYLON.CSG solid with solid and empty space switched
  95103. */
  95104. CSG.prototype.inverse = function () {
  95105. var csg = this.clone();
  95106. csg.inverseInPlace();
  95107. return csg;
  95108. };
  95109. /**
  95110. * Inverses the BABYLON.CSG in place
  95111. */
  95112. CSG.prototype.inverseInPlace = function () {
  95113. this.polygons.map(function (p) { p.flip(); });
  95114. };
  95115. /**
  95116. * This is used to keep meshes transformations so they can be restored
  95117. * when we build back a Babylon Mesh
  95118. * NB : All CSG operations are performed in world coordinates
  95119. * @param csg The BABYLON.CSG to copy the transform attributes from
  95120. * @returns This BABYLON.CSG
  95121. */
  95122. CSG.prototype.copyTransformAttributes = function (csg) {
  95123. this.matrix = csg.matrix;
  95124. this.position = csg.position;
  95125. this.rotation = csg.rotation;
  95126. this.scaling = csg.scaling;
  95127. this.rotationQuaternion = csg.rotationQuaternion;
  95128. return this;
  95129. };
  95130. /**
  95131. * Build Raw mesh from CSG
  95132. * Coordinates here are in world space
  95133. * @param name The name of the mesh geometry
  95134. * @param scene The BABYLON.Scene
  95135. * @param keepSubMeshes Specifies if the submeshes should be kept
  95136. * @returns A new BABYLON.Mesh
  95137. */
  95138. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  95139. var matrix = this.matrix.clone();
  95140. matrix.invert();
  95141. 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;
  95142. if (keepSubMeshes) {
  95143. // Sort Polygons, since subMeshes are indices range
  95144. polygons.sort(function (a, b) {
  95145. if (a.shared.meshId === b.shared.meshId) {
  95146. return a.shared.subMeshId - b.shared.subMeshId;
  95147. }
  95148. else {
  95149. return a.shared.meshId - b.shared.meshId;
  95150. }
  95151. });
  95152. }
  95153. for (var i = 0, il = polygons.length; i < il; i++) {
  95154. polygon = polygons[i];
  95155. // Building SubMeshes
  95156. if (!subMesh_dict[polygon.shared.meshId]) {
  95157. subMesh_dict[polygon.shared.meshId] = {};
  95158. }
  95159. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  95160. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  95161. indexStart: +Infinity,
  95162. indexEnd: -Infinity,
  95163. materialIndex: polygon.shared.materialIndex
  95164. };
  95165. }
  95166. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  95167. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  95168. polygonIndices[0] = 0;
  95169. polygonIndices[1] = j - 1;
  95170. polygonIndices[2] = j;
  95171. for (var k = 0; k < 3; k++) {
  95172. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  95173. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  95174. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  95175. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  95176. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  95177. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  95178. // Check if 2 points can be merged
  95179. if (!(typeof vertex_idx !== 'undefined' &&
  95180. normals[vertex_idx * 3] === localNormal.x &&
  95181. normals[vertex_idx * 3 + 1] === localNormal.y &&
  95182. normals[vertex_idx * 3 + 2] === localNormal.z &&
  95183. uvs[vertex_idx * 2] === uv.x &&
  95184. uvs[vertex_idx * 2 + 1] === uv.y)) {
  95185. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  95186. uvs.push(uv.x, uv.y);
  95187. normals.push(normal.x, normal.y, normal.z);
  95188. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  95189. }
  95190. indices.push(vertex_idx);
  95191. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  95192. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  95193. currentIndex++;
  95194. }
  95195. }
  95196. }
  95197. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  95198. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95199. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  95200. mesh.setIndices(indices, null);
  95201. if (keepSubMeshes) {
  95202. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  95203. var materialIndexOffset = 0, materialMaxIndex;
  95204. mesh.subMeshes = new Array();
  95205. for (var m in subMesh_dict) {
  95206. materialMaxIndex = -1;
  95207. for (var sm in subMesh_dict[m]) {
  95208. subMesh_obj = subMesh_dict[m][sm];
  95209. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  95210. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  95211. }
  95212. materialIndexOffset += ++materialMaxIndex;
  95213. }
  95214. }
  95215. return mesh;
  95216. };
  95217. /**
  95218. * Build Mesh from CSG taking material and transforms into account
  95219. * @param name The name of the BABYLON.Mesh
  95220. * @param material The material of the BABYLON.Mesh
  95221. * @param scene The BABYLON.Scene
  95222. * @param keepSubMeshes Specifies if submeshes should be kept
  95223. * @returns The new BABYLON.Mesh
  95224. */
  95225. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  95226. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  95227. mesh.material = material;
  95228. mesh.position.copyFrom(this.position);
  95229. mesh.rotation.copyFrom(this.rotation);
  95230. if (this.rotationQuaternion) {
  95231. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  95232. }
  95233. mesh.scaling.copyFrom(this.scaling);
  95234. mesh.computeWorldMatrix(true);
  95235. return mesh;
  95236. };
  95237. return CSG;
  95238. }());
  95239. BABYLON.CSG = CSG;
  95240. })(BABYLON || (BABYLON = {}));
  95241. //# sourceMappingURL=babylon.csg.js.map
  95242. var BABYLON;
  95243. (function (BABYLON) {
  95244. /**
  95245. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95246. * It controls one of the indiviual texture used in the effect.
  95247. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95248. */
  95249. var LensFlare = /** @class */ (function () {
  95250. /**
  95251. * Instantiates a new Lens Flare.
  95252. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95253. * It controls one of the indiviual texture used in the effect.
  95254. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95255. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  95256. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  95257. * @param color Define the lens color
  95258. * @param imgUrl Define the lens texture url
  95259. * @param system Define the `lensFlareSystem` this flare is part of
  95260. */
  95261. function LensFlare(
  95262. /**
  95263. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  95264. */
  95265. size,
  95266. /**
  95267. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  95268. */
  95269. position, color, imgUrl, system) {
  95270. this.size = size;
  95271. this.position = position;
  95272. /**
  95273. * Define the alpha mode to render this particular lens.
  95274. */
  95275. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  95276. this.color = color || new BABYLON.Color3(1, 1, 1);
  95277. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  95278. this._system = system;
  95279. system.lensFlares.push(this);
  95280. }
  95281. /**
  95282. * Creates a new Lens Flare.
  95283. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95284. * It controls one of the indiviual texture used in the effect.
  95285. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95286. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  95287. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  95288. * @param color Define the lens color
  95289. * @param imgUrl Define the lens texture url
  95290. * @param system Define the `lensFlareSystem` this flare is part of
  95291. * @returns The newly created Lens Flare
  95292. */
  95293. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  95294. return new LensFlare(size, position, color, imgUrl, system);
  95295. };
  95296. /**
  95297. * Dispose and release the lens flare with its associated resources.
  95298. */
  95299. LensFlare.prototype.dispose = function () {
  95300. if (this.texture) {
  95301. this.texture.dispose();
  95302. }
  95303. // Remove from scene
  95304. var index = this._system.lensFlares.indexOf(this);
  95305. this._system.lensFlares.splice(index, 1);
  95306. };
  95307. return LensFlare;
  95308. }());
  95309. BABYLON.LensFlare = LensFlare;
  95310. })(BABYLON || (BABYLON = {}));
  95311. //# sourceMappingURL=babylon.lensFlare.js.map
  95312. var BABYLON;
  95313. (function (BABYLON) {
  95314. // Adds the parser to the scene parsers.
  95315. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  95316. // Lens flares
  95317. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  95318. if (!container.lensFlareSystems) {
  95319. container.lensFlareSystems = new Array();
  95320. }
  95321. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  95322. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  95323. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  95324. container.lensFlareSystems.push(lf);
  95325. }
  95326. }
  95327. });
  95328. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  95329. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95330. if (this.lensFlareSystems[index].name === name) {
  95331. return this.lensFlareSystems[index];
  95332. }
  95333. }
  95334. return null;
  95335. };
  95336. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  95337. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95338. if (this.lensFlareSystems[index].id === id) {
  95339. return this.lensFlareSystems[index];
  95340. }
  95341. }
  95342. return null;
  95343. };
  95344. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  95345. var index = this.lensFlareSystems.indexOf(toRemove);
  95346. if (index !== -1) {
  95347. this.lensFlareSystems.splice(index, 1);
  95348. }
  95349. return index;
  95350. };
  95351. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  95352. this.lensFlareSystems.push(newLensFlareSystem);
  95353. };
  95354. /**
  95355. * Defines the lens flare scene component responsible to manage any lens flares
  95356. * in a given scene.
  95357. */
  95358. var LensFlareSystemSceneComponent = /** @class */ (function () {
  95359. /**
  95360. * Creates a new instance of the component for the given scene
  95361. * @param scene Defines the scene to register the component in
  95362. */
  95363. function LensFlareSystemSceneComponent(scene) {
  95364. /**
  95365. * The component name helpfull to identify the component in the list of scene components.
  95366. */
  95367. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  95368. this.scene = scene;
  95369. scene.lensFlareSystems = new Array();
  95370. }
  95371. /**
  95372. * Registers the component in a given scene
  95373. */
  95374. LensFlareSystemSceneComponent.prototype.register = function () {
  95375. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  95376. };
  95377. /**
  95378. * Rebuilds the elements related to this component in case of
  95379. * context lost for instance.
  95380. */
  95381. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  95382. // Nothing to do for lens flare
  95383. };
  95384. /**
  95385. * Adds all the element from the container to the scene
  95386. * @param container the container holding the elements
  95387. */
  95388. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  95389. var _this = this;
  95390. if (!container.lensFlareSystems) {
  95391. return;
  95392. }
  95393. container.lensFlareSystems.forEach(function (o) {
  95394. _this.scene.addLensFlareSystem(o);
  95395. });
  95396. };
  95397. /**
  95398. * Removes all the elements in the container from the scene
  95399. * @param container contains the elements to remove
  95400. */
  95401. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  95402. var _this = this;
  95403. if (!container.lensFlareSystems) {
  95404. return;
  95405. }
  95406. container.lensFlareSystems.forEach(function (o) {
  95407. _this.scene.removeLensFlareSystem(o);
  95408. });
  95409. };
  95410. /**
  95411. * Serializes the component data to the specified json object
  95412. * @param serializationObject The object to serialize to
  95413. */
  95414. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  95415. // Lens flares
  95416. serializationObject.lensFlareSystems = [];
  95417. var lensFlareSystems = this.scene.lensFlareSystems;
  95418. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  95419. var lensFlareSystem = lensFlareSystems_1[_i];
  95420. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  95421. }
  95422. };
  95423. /**
  95424. * Disposes the component and the associated ressources.
  95425. */
  95426. LensFlareSystemSceneComponent.prototype.dispose = function () {
  95427. var lensFlareSystems = this.scene.lensFlareSystems;
  95428. while (lensFlareSystems.length) {
  95429. lensFlareSystems[0].dispose();
  95430. }
  95431. };
  95432. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  95433. // Lens flares
  95434. if (this.scene.lensFlaresEnabled) {
  95435. var lensFlareSystems = this.scene.lensFlareSystems;
  95436. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95437. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  95438. var lensFlareSystem = lensFlareSystems_2[_i];
  95439. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  95440. lensFlareSystem.render();
  95441. }
  95442. }
  95443. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95444. }
  95445. };
  95446. return LensFlareSystemSceneComponent;
  95447. }());
  95448. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  95449. })(BABYLON || (BABYLON = {}));
  95450. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  95451. var BABYLON;
  95452. (function (BABYLON) {
  95453. /**
  95454. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95455. * It is usually composed of several `BABYLON.lensFlare`.
  95456. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95457. */
  95458. var LensFlareSystem = /** @class */ (function () {
  95459. /**
  95460. * Instantiates a lens flare system.
  95461. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95462. * It is usually composed of several `BABYLON.lensFlare`.
  95463. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95464. * @param name Define the name of the lens flare system in the scene
  95465. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  95466. * @param scene Define the scene the lens flare system belongs to
  95467. */
  95468. function LensFlareSystem(
  95469. /**
  95470. * Define the name of the lens flare system
  95471. */
  95472. name, emitter, scene) {
  95473. this.name = name;
  95474. /**
  95475. * List of lens flares used in this system.
  95476. */
  95477. this.lensFlares = new Array();
  95478. /**
  95479. * Define a limit from the border the lens flare can be visible.
  95480. */
  95481. this.borderLimit = 300;
  95482. /**
  95483. * Define a viewport border we do not want to see the lens flare in.
  95484. */
  95485. this.viewportBorder = 0;
  95486. /**
  95487. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  95488. */
  95489. this.layerMask = 0x0FFFFFFF;
  95490. this._vertexBuffers = {};
  95491. this._isEnabled = true;
  95492. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95493. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  95494. if (!component) {
  95495. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  95496. scene._addComponent(component);
  95497. }
  95498. this._emitter = emitter;
  95499. this.id = name;
  95500. scene.lensFlareSystems.push(this);
  95501. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  95502. var engine = scene.getEngine();
  95503. // VBO
  95504. var vertices = [];
  95505. vertices.push(1, 1);
  95506. vertices.push(-1, 1);
  95507. vertices.push(-1, -1);
  95508. vertices.push(1, -1);
  95509. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95510. // Indices
  95511. var indices = [];
  95512. indices.push(0);
  95513. indices.push(1);
  95514. indices.push(2);
  95515. indices.push(0);
  95516. indices.push(2);
  95517. indices.push(3);
  95518. this._indexBuffer = engine.createIndexBuffer(indices);
  95519. // Effects
  95520. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  95521. }
  95522. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  95523. /**
  95524. * Define if the lens flare system is enabled.
  95525. */
  95526. get: function () {
  95527. return this._isEnabled;
  95528. },
  95529. set: function (value) {
  95530. this._isEnabled = value;
  95531. },
  95532. enumerable: true,
  95533. configurable: true
  95534. });
  95535. /**
  95536. * Get the scene the effects belongs to.
  95537. * @returns the scene holding the lens flare system
  95538. */
  95539. LensFlareSystem.prototype.getScene = function () {
  95540. return this._scene;
  95541. };
  95542. /**
  95543. * Get the emitter of the lens flare system.
  95544. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95545. * @returns the emitter of the lens flare system
  95546. */
  95547. LensFlareSystem.prototype.getEmitter = function () {
  95548. return this._emitter;
  95549. };
  95550. /**
  95551. * Set the emitter of the lens flare system.
  95552. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95553. * @param newEmitter Define the new emitter of the system
  95554. */
  95555. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  95556. this._emitter = newEmitter;
  95557. };
  95558. /**
  95559. * Get the lens flare system emitter position.
  95560. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  95561. * @returns the position
  95562. */
  95563. LensFlareSystem.prototype.getEmitterPosition = function () {
  95564. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  95565. };
  95566. /**
  95567. * @hidden
  95568. */
  95569. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  95570. var position = this.getEmitterPosition();
  95571. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  95572. this._positionX = position.x;
  95573. this._positionY = position.y;
  95574. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  95575. if (this.viewportBorder > 0) {
  95576. globalViewport.x -= this.viewportBorder;
  95577. globalViewport.y -= this.viewportBorder;
  95578. globalViewport.width += this.viewportBorder * 2;
  95579. globalViewport.height += this.viewportBorder * 2;
  95580. position.x += this.viewportBorder;
  95581. position.y += this.viewportBorder;
  95582. this._positionX += this.viewportBorder;
  95583. this._positionY += this.viewportBorder;
  95584. }
  95585. if (position.z > 0) {
  95586. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  95587. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  95588. return true;
  95589. }
  95590. }
  95591. return true;
  95592. }
  95593. return false;
  95594. };
  95595. /** @hidden */
  95596. LensFlareSystem.prototype._isVisible = function () {
  95597. if (!this._isEnabled || !this._scene.activeCamera) {
  95598. return false;
  95599. }
  95600. var emitterPosition = this.getEmitterPosition();
  95601. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  95602. var distance = direction.length();
  95603. direction.normalize();
  95604. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  95605. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  95606. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  95607. };
  95608. /**
  95609. * @hidden
  95610. */
  95611. LensFlareSystem.prototype.render = function () {
  95612. if (!this._effect.isReady() || !this._scene.activeCamera) {
  95613. return false;
  95614. }
  95615. var engine = this._scene.getEngine();
  95616. var viewport = this._scene.activeCamera.viewport;
  95617. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  95618. // Position
  95619. if (!this.computeEffectivePosition(globalViewport)) {
  95620. return false;
  95621. }
  95622. // Visibility
  95623. if (!this._isVisible()) {
  95624. return false;
  95625. }
  95626. // Intensity
  95627. var awayX;
  95628. var awayY;
  95629. if (this._positionX < this.borderLimit + globalViewport.x) {
  95630. awayX = this.borderLimit + globalViewport.x - this._positionX;
  95631. }
  95632. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  95633. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  95634. }
  95635. else {
  95636. awayX = 0;
  95637. }
  95638. if (this._positionY < this.borderLimit + globalViewport.y) {
  95639. awayY = this.borderLimit + globalViewport.y - this._positionY;
  95640. }
  95641. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  95642. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  95643. }
  95644. else {
  95645. awayY = 0;
  95646. }
  95647. var away = (awayX > awayY) ? awayX : awayY;
  95648. away -= this.viewportBorder;
  95649. if (away > this.borderLimit) {
  95650. away = this.borderLimit;
  95651. }
  95652. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  95653. if (intensity < 0) {
  95654. return false;
  95655. }
  95656. if (intensity > 1.0) {
  95657. intensity = 1.0;
  95658. }
  95659. if (this.viewportBorder > 0) {
  95660. globalViewport.x += this.viewportBorder;
  95661. globalViewport.y += this.viewportBorder;
  95662. globalViewport.width -= this.viewportBorder * 2;
  95663. globalViewport.height -= this.viewportBorder * 2;
  95664. this._positionX -= this.viewportBorder;
  95665. this._positionY -= this.viewportBorder;
  95666. }
  95667. // Position
  95668. var centerX = globalViewport.x + globalViewport.width / 2;
  95669. var centerY = globalViewport.y + globalViewport.height / 2;
  95670. var distX = centerX - this._positionX;
  95671. var distY = centerY - this._positionY;
  95672. // Effects
  95673. engine.enableEffect(this._effect);
  95674. engine.setState(false);
  95675. engine.setDepthBuffer(false);
  95676. // VBOs
  95677. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  95678. // Flares
  95679. for (var index = 0; index < this.lensFlares.length; index++) {
  95680. var flare = this.lensFlares[index];
  95681. engine.setAlphaMode(flare.alphaMode);
  95682. var x = centerX - (distX * flare.position);
  95683. var y = centerY - (distY * flare.position);
  95684. var cw = flare.size;
  95685. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  95686. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  95687. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  95688. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  95689. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  95690. // Texture
  95691. this._effect.setTexture("textureSampler", flare.texture);
  95692. // Color
  95693. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  95694. // Draw order
  95695. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95696. }
  95697. engine.setDepthBuffer(true);
  95698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95699. return true;
  95700. };
  95701. /**
  95702. * Dispose and release the lens flare with its associated resources.
  95703. */
  95704. LensFlareSystem.prototype.dispose = function () {
  95705. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95706. if (vertexBuffer) {
  95707. vertexBuffer.dispose();
  95708. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95709. }
  95710. if (this._indexBuffer) {
  95711. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95712. this._indexBuffer = null;
  95713. }
  95714. while (this.lensFlares.length) {
  95715. this.lensFlares[0].dispose();
  95716. }
  95717. // Remove from scene
  95718. var index = this._scene.lensFlareSystems.indexOf(this);
  95719. this._scene.lensFlareSystems.splice(index, 1);
  95720. };
  95721. /**
  95722. * Parse a lens flare system from a JSON repressentation
  95723. * @param parsedLensFlareSystem Define the JSON to parse
  95724. * @param scene Define the scene the parsed system should be instantiated in
  95725. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  95726. * @returns the parsed system
  95727. */
  95728. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  95729. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  95730. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  95731. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  95732. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  95733. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  95734. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  95735. var parsedFlare = parsedLensFlareSystem.flares[index];
  95736. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  95737. }
  95738. return lensFlareSystem;
  95739. };
  95740. /**
  95741. * Serialize the current Lens Flare System into a JSON representation.
  95742. * @returns the serialized JSON
  95743. */
  95744. LensFlareSystem.prototype.serialize = function () {
  95745. var serializationObject = {};
  95746. serializationObject.id = this.id;
  95747. serializationObject.name = this.name;
  95748. serializationObject.emitterId = this.getEmitter().id;
  95749. serializationObject.borderLimit = this.borderLimit;
  95750. serializationObject.flares = [];
  95751. for (var index = 0; index < this.lensFlares.length; index++) {
  95752. var flare = this.lensFlares[index];
  95753. serializationObject.flares.push({
  95754. size: flare.size,
  95755. position: flare.position,
  95756. color: flare.color.asArray(),
  95757. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  95758. });
  95759. }
  95760. return serializationObject;
  95761. };
  95762. return LensFlareSystem;
  95763. }());
  95764. BABYLON.LensFlareSystem = LensFlareSystem;
  95765. })(BABYLON || (BABYLON = {}));
  95766. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  95767. var BABYLON;
  95768. (function (BABYLON) {
  95769. /**
  95770. * This is a holder class for the physics joint created by the physics plugin
  95771. * It holds a set of functions to control the underlying joint
  95772. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95773. */
  95774. var PhysicsJoint = /** @class */ (function () {
  95775. /**
  95776. * Initializes the physics joint
  95777. * @param type The type of the physics joint
  95778. * @param jointData The data for the physics joint
  95779. */
  95780. function PhysicsJoint(
  95781. /**
  95782. * The type of the physics joint
  95783. */
  95784. type,
  95785. /**
  95786. * The data for the physics joint
  95787. */
  95788. jointData) {
  95789. this.type = type;
  95790. this.jointData = jointData;
  95791. jointData.nativeParams = jointData.nativeParams || {};
  95792. }
  95793. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  95794. /**
  95795. * Gets the physics joint
  95796. */
  95797. get: function () {
  95798. return this._physicsJoint;
  95799. },
  95800. /**
  95801. * Sets the physics joint
  95802. */
  95803. set: function (newJoint) {
  95804. if (this._physicsJoint) {
  95805. //remove from the wolrd
  95806. }
  95807. this._physicsJoint = newJoint;
  95808. },
  95809. enumerable: true,
  95810. configurable: true
  95811. });
  95812. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  95813. /**
  95814. * Sets the physics plugin
  95815. */
  95816. set: function (physicsPlugin) {
  95817. this._physicsPlugin = physicsPlugin;
  95818. },
  95819. enumerable: true,
  95820. configurable: true
  95821. });
  95822. /**
  95823. * Execute a function that is physics-plugin specific.
  95824. * @param {Function} func the function that will be executed.
  95825. * It accepts two parameters: the physics world and the physics joint
  95826. */
  95827. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  95828. func(this._physicsPlugin.world, this._physicsJoint);
  95829. };
  95830. //TODO check if the native joints are the same
  95831. //Joint Types
  95832. /**
  95833. * Distance-Joint type
  95834. */
  95835. PhysicsJoint.DistanceJoint = 0;
  95836. /**
  95837. * Hinge-Joint type
  95838. */
  95839. PhysicsJoint.HingeJoint = 1;
  95840. /**
  95841. * Ball-and-Socket joint type
  95842. */
  95843. PhysicsJoint.BallAndSocketJoint = 2;
  95844. /**
  95845. * Wheel-Joint type
  95846. */
  95847. PhysicsJoint.WheelJoint = 3;
  95848. /**
  95849. * Slider-Joint type
  95850. */
  95851. PhysicsJoint.SliderJoint = 4;
  95852. //OIMO
  95853. /**
  95854. * Prismatic-Joint type
  95855. */
  95856. PhysicsJoint.PrismaticJoint = 5;
  95857. //
  95858. /**
  95859. * Universal-Joint type
  95860. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  95861. */
  95862. PhysicsJoint.UniversalJoint = 6;
  95863. /**
  95864. * Hinge-Joint 2 type
  95865. */
  95866. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  95867. //Cannon
  95868. /**
  95869. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  95870. */
  95871. PhysicsJoint.PointToPointJoint = 8;
  95872. //Cannon only at the moment
  95873. /**
  95874. * Spring-Joint type
  95875. */
  95876. PhysicsJoint.SpringJoint = 9;
  95877. /**
  95878. * Lock-Joint type
  95879. */
  95880. PhysicsJoint.LockJoint = 10;
  95881. return PhysicsJoint;
  95882. }());
  95883. BABYLON.PhysicsJoint = PhysicsJoint;
  95884. /**
  95885. * A class representing a physics distance joint
  95886. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95887. */
  95888. var DistanceJoint = /** @class */ (function (_super) {
  95889. __extends(DistanceJoint, _super);
  95890. /**
  95891. *
  95892. * @param jointData The data for the Distance-Joint
  95893. */
  95894. function DistanceJoint(jointData) {
  95895. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  95896. }
  95897. /**
  95898. * Update the predefined distance.
  95899. * @param maxDistance The maximum preferred distance
  95900. * @param minDistance The minimum preferred distance
  95901. */
  95902. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  95903. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  95904. };
  95905. return DistanceJoint;
  95906. }(PhysicsJoint));
  95907. BABYLON.DistanceJoint = DistanceJoint;
  95908. /**
  95909. * Represents a Motor-Enabled Joint
  95910. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95911. */
  95912. var MotorEnabledJoint = /** @class */ (function (_super) {
  95913. __extends(MotorEnabledJoint, _super);
  95914. /**
  95915. * Initializes the Motor-Enabled Joint
  95916. * @param type The type of the joint
  95917. * @param jointData The physica joint data for the joint
  95918. */
  95919. function MotorEnabledJoint(type, jointData) {
  95920. return _super.call(this, type, jointData) || this;
  95921. }
  95922. /**
  95923. * Set the motor values.
  95924. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95925. * @param force the force to apply
  95926. * @param maxForce max force for this motor.
  95927. */
  95928. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  95929. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95930. };
  95931. /**
  95932. * Set the motor's limits.
  95933. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95934. * @param upperLimit The upper limit of the motor
  95935. * @param lowerLimit The lower limit of the motor
  95936. */
  95937. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95938. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95939. };
  95940. return MotorEnabledJoint;
  95941. }(PhysicsJoint));
  95942. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  95943. /**
  95944. * This class represents a single physics Hinge-Joint
  95945. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95946. */
  95947. var HingeJoint = /** @class */ (function (_super) {
  95948. __extends(HingeJoint, _super);
  95949. /**
  95950. * Initializes the Hinge-Joint
  95951. * @param jointData The joint data for the Hinge-Joint
  95952. */
  95953. function HingeJoint(jointData) {
  95954. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  95955. }
  95956. /**
  95957. * Set the motor values.
  95958. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95959. * @param {number} force the force to apply
  95960. * @param {number} maxForce max force for this motor.
  95961. */
  95962. HingeJoint.prototype.setMotor = function (force, maxForce) {
  95963. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95964. };
  95965. /**
  95966. * Set the motor's limits.
  95967. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95968. * @param upperLimit The upper limit of the motor
  95969. * @param lowerLimit The lower limit of the motor
  95970. */
  95971. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95972. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95973. };
  95974. return HingeJoint;
  95975. }(MotorEnabledJoint));
  95976. BABYLON.HingeJoint = HingeJoint;
  95977. /**
  95978. * This class represents a dual hinge physics joint (same as wheel joint)
  95979. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95980. */
  95981. var Hinge2Joint = /** @class */ (function (_super) {
  95982. __extends(Hinge2Joint, _super);
  95983. /**
  95984. * Initializes the Hinge2-Joint
  95985. * @param jointData The joint data for the Hinge2-Joint
  95986. */
  95987. function Hinge2Joint(jointData) {
  95988. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  95989. }
  95990. /**
  95991. * Set the motor values.
  95992. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95993. * @param {number} force the force to apply
  95994. * @param {number} maxForce max force for this motor.
  95995. * @param {motorIndex} the motor's index, 0 or 1.
  95996. */
  95997. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  95998. if (motorIndex === void 0) { motorIndex = 0; }
  95999. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  96000. };
  96001. /**
  96002. * Set the motor limits.
  96003. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96004. * @param {number} upperLimit the upper limit
  96005. * @param {number} lowerLimit lower limit
  96006. * @param {motorIndex} the motor's index, 0 or 1.
  96007. */
  96008. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  96009. if (motorIndex === void 0) { motorIndex = 0; }
  96010. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  96011. };
  96012. return Hinge2Joint;
  96013. }(MotorEnabledJoint));
  96014. BABYLON.Hinge2Joint = Hinge2Joint;
  96015. })(BABYLON || (BABYLON = {}));
  96016. //# sourceMappingURL=babylon.physicsJoint.js.map
  96017. var BABYLON;
  96018. (function (BABYLON) {
  96019. /**
  96020. * Represents a physics imposter
  96021. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96022. */
  96023. var PhysicsImpostor = /** @class */ (function () {
  96024. /**
  96025. * Initializes the physics imposter
  96026. * @param object The physics-enabled object used as the physics imposter
  96027. * @param type The type of the physics imposter
  96028. * @param _options The options for the physics imposter
  96029. * @param _scene The Babylon scene
  96030. */
  96031. function PhysicsImpostor(
  96032. /**
  96033. * The physics-enabled object used as the physics imposter
  96034. */
  96035. object,
  96036. /**
  96037. * The type of the physics imposter
  96038. */
  96039. type, _options, _scene) {
  96040. if (_options === void 0) { _options = { mass: 0 }; }
  96041. var _this = this;
  96042. this.object = object;
  96043. this.type = type;
  96044. this._options = _options;
  96045. this._scene = _scene;
  96046. this._bodyUpdateRequired = false;
  96047. this._onBeforePhysicsStepCallbacks = new Array();
  96048. this._onAfterPhysicsStepCallbacks = new Array();
  96049. this._onPhysicsCollideCallbacks = [];
  96050. this._deltaPosition = BABYLON.Vector3.Zero();
  96051. this._isDisposed = false;
  96052. //temp variables for parent rotation calculations
  96053. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  96054. this._tmpQuat = new BABYLON.Quaternion();
  96055. this._tmpQuat2 = new BABYLON.Quaternion();
  96056. /**
  96057. * this function is executed by the physics engine.
  96058. */
  96059. this.beforeStep = function () {
  96060. if (!_this._physicsEngine) {
  96061. return;
  96062. }
  96063. _this.object.translate(_this._deltaPosition, -1);
  96064. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  96065. _this.object.computeWorldMatrix(false);
  96066. if (_this.object.parent && _this.object.rotationQuaternion) {
  96067. _this.getParentsRotation();
  96068. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  96069. }
  96070. else {
  96071. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  96072. }
  96073. if (!_this._options.disableBidirectionalTransformation) {
  96074. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  96075. }
  96076. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  96077. func(_this);
  96078. });
  96079. };
  96080. /**
  96081. * this function is executed by the physics engine
  96082. */
  96083. this.afterStep = function () {
  96084. if (!_this._physicsEngine) {
  96085. return;
  96086. }
  96087. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  96088. func(_this);
  96089. });
  96090. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  96091. // object has now its world rotation. needs to be converted to local.
  96092. if (_this.object.parent && _this.object.rotationQuaternion) {
  96093. _this.getParentsRotation();
  96094. _this._tmpQuat.conjugateInPlace();
  96095. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  96096. }
  96097. // take the position set and make it the absolute position of this object.
  96098. _this.object.setAbsolutePosition(_this.object.position);
  96099. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  96100. _this.object.translate(_this._deltaPosition, 1);
  96101. };
  96102. /**
  96103. * Legacy collision detection event support
  96104. */
  96105. this.onCollideEvent = null;
  96106. /**
  96107. * event and body object due to cannon's event-based architecture.
  96108. */
  96109. this.onCollide = function (e) {
  96110. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  96111. return;
  96112. }
  96113. if (!_this._physicsEngine) {
  96114. return;
  96115. }
  96116. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  96117. if (otherImpostor) {
  96118. // Legacy collision detection event support
  96119. if (_this.onCollideEvent) {
  96120. _this.onCollideEvent(_this, otherImpostor);
  96121. }
  96122. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  96123. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  96124. }).forEach(function (obj) {
  96125. obj.callback(_this, otherImpostor);
  96126. });
  96127. }
  96128. };
  96129. //sanity check!
  96130. if (!this.object) {
  96131. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  96132. return;
  96133. }
  96134. //legacy support for old syntax.
  96135. if (!this._scene && object.getScene) {
  96136. this._scene = object.getScene();
  96137. }
  96138. if (!this._scene) {
  96139. return;
  96140. }
  96141. this._physicsEngine = this._scene.getPhysicsEngine();
  96142. if (!this._physicsEngine) {
  96143. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  96144. }
  96145. else {
  96146. //set the object's quaternion, if not set
  96147. if (!this.object.rotationQuaternion) {
  96148. if (this.object.rotation) {
  96149. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  96150. }
  96151. else {
  96152. this.object.rotationQuaternion = new BABYLON.Quaternion();
  96153. }
  96154. }
  96155. //default options params
  96156. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  96157. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  96158. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  96159. this._joints = [];
  96160. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  96161. if (!this.object.parent || this._options.ignoreParent) {
  96162. this._init();
  96163. }
  96164. else if (this.object.parent.physicsImpostor) {
  96165. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  96166. }
  96167. }
  96168. }
  96169. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  96170. /**
  96171. * Specifies if the physics imposter is disposed
  96172. */
  96173. get: function () {
  96174. return this._isDisposed;
  96175. },
  96176. enumerable: true,
  96177. configurable: true
  96178. });
  96179. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  96180. /**
  96181. * Gets the mass of the physics imposter
  96182. */
  96183. get: function () {
  96184. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  96185. },
  96186. set: function (value) {
  96187. this.setMass(value);
  96188. },
  96189. enumerable: true,
  96190. configurable: true
  96191. });
  96192. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  96193. /**
  96194. * Gets the coefficient of friction
  96195. */
  96196. get: function () {
  96197. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  96198. },
  96199. /**
  96200. * Sets the coefficient of friction
  96201. */
  96202. set: function (value) {
  96203. if (!this._physicsEngine) {
  96204. return;
  96205. }
  96206. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  96207. },
  96208. enumerable: true,
  96209. configurable: true
  96210. });
  96211. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  96212. /**
  96213. * Gets the coefficient of restitution
  96214. */
  96215. get: function () {
  96216. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  96217. },
  96218. /**
  96219. * Sets the coefficient of restitution
  96220. */
  96221. set: function (value) {
  96222. if (!this._physicsEngine) {
  96223. return;
  96224. }
  96225. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  96226. },
  96227. enumerable: true,
  96228. configurable: true
  96229. });
  96230. /**
  96231. * This function will completly initialize this impostor.
  96232. * It will create a new body - but only if this mesh has no parent.
  96233. * If it has, this impostor will not be used other than to define the impostor
  96234. * of the child mesh.
  96235. * @hidden
  96236. */
  96237. PhysicsImpostor.prototype._init = function () {
  96238. if (!this._physicsEngine) {
  96239. return;
  96240. }
  96241. this._physicsEngine.removeImpostor(this);
  96242. this.physicsBody = null;
  96243. this._parent = this._parent || this._getPhysicsParent();
  96244. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  96245. this._physicsEngine.addImpostor(this);
  96246. }
  96247. };
  96248. PhysicsImpostor.prototype._getPhysicsParent = function () {
  96249. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  96250. var parentMesh = this.object.parent;
  96251. return parentMesh.physicsImpostor;
  96252. }
  96253. return null;
  96254. };
  96255. /**
  96256. * Should a new body be generated.
  96257. * @returns boolean specifying if body initialization is required
  96258. */
  96259. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  96260. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  96261. };
  96262. /**
  96263. * Sets the updated scaling
  96264. * @param updated Specifies if the scaling is updated
  96265. */
  96266. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  96267. this.forceUpdate();
  96268. };
  96269. /**
  96270. * Force a regeneration of this or the parent's impostor's body.
  96271. * Use under cautious - This will remove all joints already implemented.
  96272. */
  96273. PhysicsImpostor.prototype.forceUpdate = function () {
  96274. this._init();
  96275. if (this.parent && !this._options.ignoreParent) {
  96276. this.parent.forceUpdate();
  96277. }
  96278. };
  96279. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  96280. /*public get mesh(): AbstractMesh {
  96281. return this._mesh;
  96282. }*/
  96283. /**
  96284. * Gets the body that holds this impostor. Either its own, or its parent.
  96285. */
  96286. get: function () {
  96287. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  96288. },
  96289. /**
  96290. * Set the physics body. Used mainly by the physics engine/plugin
  96291. */
  96292. set: function (physicsBody) {
  96293. if (this._physicsBody && this._physicsEngine) {
  96294. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  96295. }
  96296. this._physicsBody = physicsBody;
  96297. this.resetUpdateFlags();
  96298. },
  96299. enumerable: true,
  96300. configurable: true
  96301. });
  96302. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  96303. /**
  96304. * Get the parent of the physics imposter
  96305. * @returns Physics imposter or null
  96306. */
  96307. get: function () {
  96308. return !this._options.ignoreParent && this._parent ? this._parent : null;
  96309. },
  96310. /**
  96311. * Sets the parent of the physics imposter
  96312. */
  96313. set: function (value) {
  96314. this._parent = value;
  96315. },
  96316. enumerable: true,
  96317. configurable: true
  96318. });
  96319. /**
  96320. * Resets the update flags
  96321. */
  96322. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  96323. this._bodyUpdateRequired = false;
  96324. };
  96325. /**
  96326. * Gets the object extend size
  96327. * @returns the object extend size
  96328. */
  96329. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  96330. if (this.object.getBoundingInfo) {
  96331. var q = this.object.rotationQuaternion;
  96332. //reset rotation
  96333. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  96334. //calculate the world matrix with no rotation
  96335. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96336. var boundingInfo = this.object.getBoundingInfo();
  96337. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  96338. //bring back the rotation
  96339. this.object.rotationQuaternion = q;
  96340. //calculate the world matrix with the new rotation
  96341. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96342. return size;
  96343. }
  96344. else {
  96345. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  96346. }
  96347. };
  96348. /**
  96349. * Gets the object center
  96350. * @returns The object center
  96351. */
  96352. PhysicsImpostor.prototype.getObjectCenter = function () {
  96353. if (this.object.getBoundingInfo) {
  96354. var boundingInfo = this.object.getBoundingInfo();
  96355. return boundingInfo.boundingBox.centerWorld;
  96356. }
  96357. else {
  96358. return this.object.position;
  96359. }
  96360. };
  96361. /**
  96362. * Get a specific parametes from the options parameter
  96363. * @param paramName The object parameter name
  96364. * @returns The object parameter
  96365. */
  96366. PhysicsImpostor.prototype.getParam = function (paramName) {
  96367. return this._options[paramName];
  96368. };
  96369. /**
  96370. * Sets a specific parameter in the options given to the physics plugin
  96371. * @param paramName The parameter name
  96372. * @param value The value of the parameter
  96373. */
  96374. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  96375. this._options[paramName] = value;
  96376. this._bodyUpdateRequired = true;
  96377. };
  96378. /**
  96379. * Specifically change the body's mass option. Won't recreate the physics body object
  96380. * @param mass The mass of the physics imposter
  96381. */
  96382. PhysicsImpostor.prototype.setMass = function (mass) {
  96383. if (this.getParam("mass") !== mass) {
  96384. this.setParam("mass", mass);
  96385. }
  96386. if (this._physicsEngine) {
  96387. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  96388. }
  96389. };
  96390. /**
  96391. * Gets the linear velocity
  96392. * @returns linear velocity or null
  96393. */
  96394. PhysicsImpostor.prototype.getLinearVelocity = function () {
  96395. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  96396. };
  96397. /**
  96398. * Sets the linear velocity
  96399. * @param velocity linear velocity or null
  96400. */
  96401. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  96402. if (this._physicsEngine) {
  96403. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  96404. }
  96405. };
  96406. /**
  96407. * Gets the angular velocity
  96408. * @returns angular velocity or null
  96409. */
  96410. PhysicsImpostor.prototype.getAngularVelocity = function () {
  96411. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  96412. };
  96413. /**
  96414. * Sets the angular velocity
  96415. * @param velocity The velocity or null
  96416. */
  96417. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  96418. if (this._physicsEngine) {
  96419. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  96420. }
  96421. };
  96422. /**
  96423. * Execute a function with the physics plugin native code
  96424. * Provide a function the will have two variables - the world object and the physics body object
  96425. * @param func The function to execute with the physics plugin native code
  96426. */
  96427. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  96428. if (this._physicsEngine) {
  96429. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  96430. }
  96431. };
  96432. /**
  96433. * Register a function that will be executed before the physics world is stepping forward
  96434. * @param func The function to execute before the physics world is stepped forward
  96435. */
  96436. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  96437. this._onBeforePhysicsStepCallbacks.push(func);
  96438. };
  96439. /**
  96440. * Unregister a function that will be executed before the physics world is stepping forward
  96441. * @param func The function to execute before the physics world is stepped forward
  96442. */
  96443. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  96444. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  96445. if (index > -1) {
  96446. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  96447. }
  96448. else {
  96449. BABYLON.Tools.Warn("Function to remove was not found");
  96450. }
  96451. };
  96452. /**
  96453. * Register a function that will be executed after the physics step
  96454. * @param func The function to execute after physics step
  96455. */
  96456. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  96457. this._onAfterPhysicsStepCallbacks.push(func);
  96458. };
  96459. /**
  96460. * Unregisters a function that will be executed after the physics step
  96461. * @param func The function to execute after physics step
  96462. */
  96463. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  96464. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  96465. if (index > -1) {
  96466. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  96467. }
  96468. else {
  96469. BABYLON.Tools.Warn("Function to remove was not found");
  96470. }
  96471. };
  96472. /**
  96473. * register a function that will be executed when this impostor collides against a different body
  96474. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  96475. * @param func Callback that is executed on collision
  96476. */
  96477. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  96478. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96479. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  96480. };
  96481. /**
  96482. * Unregisters the physics imposter on contact
  96483. * @param collideAgainst The physics object to collide against
  96484. * @param func Callback to execute on collision
  96485. */
  96486. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  96487. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96488. var index = -1;
  96489. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  96490. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  96491. // chcek the arrays match
  96492. var sameList = cbDef.otherImpostors.every(function (impostor) {
  96493. return collidedAgainstList.indexOf(impostor) > -1;
  96494. });
  96495. if (sameList) {
  96496. index = idx;
  96497. }
  96498. return sameList;
  96499. }
  96500. return false;
  96501. });
  96502. if (found) {
  96503. this._onPhysicsCollideCallbacks.splice(index, 1);
  96504. }
  96505. else {
  96506. BABYLON.Tools.Warn("Function to remove was not found");
  96507. }
  96508. };
  96509. /**
  96510. * Get the parent rotation
  96511. * @returns The parent rotation
  96512. */
  96513. PhysicsImpostor.prototype.getParentsRotation = function () {
  96514. var parent = this.object.parent;
  96515. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  96516. while (parent) {
  96517. if (parent.rotationQuaternion) {
  96518. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  96519. }
  96520. else {
  96521. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  96522. }
  96523. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  96524. parent = parent.parent;
  96525. }
  96526. return this._tmpQuat;
  96527. };
  96528. /**
  96529. * Apply a force
  96530. * @param force The force to apply
  96531. * @param contactPoint The contact point for the force
  96532. * @returns The physics imposter
  96533. */
  96534. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  96535. if (this._physicsEngine) {
  96536. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  96537. }
  96538. return this;
  96539. };
  96540. /**
  96541. * Apply an impulse
  96542. * @param force The impulse force
  96543. * @param contactPoint The contact point for the impulse force
  96544. * @returns The physics imposter
  96545. */
  96546. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  96547. if (this._physicsEngine) {
  96548. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  96549. }
  96550. return this;
  96551. };
  96552. /**
  96553. * A help function to create a joint
  96554. * @param otherImpostor A physics imposter used to create a joint
  96555. * @param jointType The type of joint
  96556. * @param jointData The data for the joint
  96557. * @returns The physics imposter
  96558. */
  96559. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  96560. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  96561. this.addJoint(otherImpostor, joint);
  96562. return this;
  96563. };
  96564. /**
  96565. * Add a joint to this impostor with a different impostor
  96566. * @param otherImpostor A physics imposter used to add a joint
  96567. * @param joint The joint to add
  96568. * @returns The physics imposter
  96569. */
  96570. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  96571. this._joints.push({
  96572. otherImpostor: otherImpostor,
  96573. joint: joint
  96574. });
  96575. if (this._physicsEngine) {
  96576. this._physicsEngine.addJoint(this, otherImpostor, joint);
  96577. }
  96578. return this;
  96579. };
  96580. /**
  96581. * Will keep this body still, in a sleep mode.
  96582. * @returns the physics imposter
  96583. */
  96584. PhysicsImpostor.prototype.sleep = function () {
  96585. if (this._physicsEngine) {
  96586. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  96587. }
  96588. return this;
  96589. };
  96590. /**
  96591. * Wake the body up.
  96592. * @returns The physics imposter
  96593. */
  96594. PhysicsImpostor.prototype.wakeUp = function () {
  96595. if (this._physicsEngine) {
  96596. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  96597. }
  96598. return this;
  96599. };
  96600. /**
  96601. * Clones the physics imposter
  96602. * @param newObject The physics imposter clones to this physics-enabled object
  96603. * @returns A nullable physics imposter
  96604. */
  96605. PhysicsImpostor.prototype.clone = function (newObject) {
  96606. if (!newObject) {
  96607. return null;
  96608. }
  96609. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  96610. };
  96611. /**
  96612. * Disposes the physics imposter
  96613. */
  96614. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  96615. var _this = this;
  96616. //no dispose if no physics engine is available.
  96617. if (!this._physicsEngine) {
  96618. return;
  96619. }
  96620. this._joints.forEach(function (j) {
  96621. if (_this._physicsEngine) {
  96622. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  96623. }
  96624. });
  96625. //dispose the physics body
  96626. this._physicsEngine.removeImpostor(this);
  96627. if (this.parent) {
  96628. this.parent.forceUpdate();
  96629. }
  96630. else {
  96631. /*this._object.getChildMeshes().forEach(function(mesh) {
  96632. if (mesh.physicsImpostor) {
  96633. if (disposeChildren) {
  96634. mesh.physicsImpostor.dispose();
  96635. mesh.physicsImpostor = null;
  96636. }
  96637. }
  96638. })*/
  96639. }
  96640. this._isDisposed = true;
  96641. };
  96642. /**
  96643. * Sets the delta position
  96644. * @param position The delta position amount
  96645. */
  96646. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  96647. this._deltaPosition.copyFrom(position);
  96648. };
  96649. /**
  96650. * Sets the delta rotation
  96651. * @param rotation The delta rotation amount
  96652. */
  96653. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  96654. if (!this._deltaRotation) {
  96655. this._deltaRotation = new BABYLON.Quaternion();
  96656. }
  96657. this._deltaRotation.copyFrom(rotation);
  96658. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  96659. };
  96660. /**
  96661. * Gets the box size of the physics imposter and stores the result in the input parameter
  96662. * @param result Stores the box size
  96663. * @returns The physics imposter
  96664. */
  96665. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  96666. if (this._physicsEngine) {
  96667. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  96668. }
  96669. return this;
  96670. };
  96671. /**
  96672. * Gets the radius of the physics imposter
  96673. * @returns Radius of the physics imposter
  96674. */
  96675. PhysicsImpostor.prototype.getRadius = function () {
  96676. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  96677. };
  96678. /**
  96679. * Sync a bone with this impostor
  96680. * @param bone The bone to sync to the impostor.
  96681. * @param boneMesh The mesh that the bone is influencing.
  96682. * @param jointPivot The pivot of the joint / bone in local space.
  96683. * @param distToJoint Optional distance from the impostor to the joint.
  96684. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96685. */
  96686. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  96687. var tempVec = PhysicsImpostor._tmpVecs[0];
  96688. var mesh = this.object;
  96689. if (mesh.rotationQuaternion) {
  96690. if (adjustRotation) {
  96691. var tempQuat = PhysicsImpostor._tmpQuat;
  96692. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  96693. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  96694. }
  96695. else {
  96696. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  96697. }
  96698. }
  96699. tempVec.x = 0;
  96700. tempVec.y = 0;
  96701. tempVec.z = 0;
  96702. if (jointPivot) {
  96703. tempVec.x = jointPivot.x;
  96704. tempVec.y = jointPivot.y;
  96705. tempVec.z = jointPivot.z;
  96706. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  96707. if (distToJoint === undefined || distToJoint === null) {
  96708. distToJoint = jointPivot.length();
  96709. }
  96710. tempVec.x *= distToJoint;
  96711. tempVec.y *= distToJoint;
  96712. tempVec.z *= distToJoint;
  96713. }
  96714. if (bone.getParent()) {
  96715. tempVec.addInPlace(mesh.getAbsolutePosition());
  96716. bone.setAbsolutePosition(tempVec, boneMesh);
  96717. }
  96718. else {
  96719. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  96720. boneMesh.position.x -= tempVec.x;
  96721. boneMesh.position.y -= tempVec.y;
  96722. boneMesh.position.z -= tempVec.z;
  96723. }
  96724. };
  96725. /**
  96726. * Sync impostor to a bone
  96727. * @param bone The bone that the impostor will be synced to.
  96728. * @param boneMesh The mesh that the bone is influencing.
  96729. * @param jointPivot The pivot of the joint / bone in local space.
  96730. * @param distToJoint Optional distance from the impostor to the joint.
  96731. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96732. * @param boneAxis Optional vector3 axis the bone is aligned with
  96733. */
  96734. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  96735. var mesh = this.object;
  96736. if (mesh.rotationQuaternion) {
  96737. if (adjustRotation) {
  96738. var tempQuat = PhysicsImpostor._tmpQuat;
  96739. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  96740. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  96741. }
  96742. else {
  96743. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  96744. }
  96745. }
  96746. var pos = PhysicsImpostor._tmpVecs[0];
  96747. var boneDir = PhysicsImpostor._tmpVecs[1];
  96748. if (!boneAxis) {
  96749. boneAxis = PhysicsImpostor._tmpVecs[2];
  96750. boneAxis.x = 0;
  96751. boneAxis.y = 1;
  96752. boneAxis.z = 0;
  96753. }
  96754. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  96755. bone.getAbsolutePositionToRef(boneMesh, pos);
  96756. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  96757. distToJoint = jointPivot.length();
  96758. }
  96759. if (distToJoint !== undefined && distToJoint !== null) {
  96760. pos.x += boneDir.x * distToJoint;
  96761. pos.y += boneDir.y * distToJoint;
  96762. pos.z += boneDir.z * distToJoint;
  96763. }
  96764. mesh.setAbsolutePosition(pos);
  96765. };
  96766. /**
  96767. * The default object size of the imposter
  96768. */
  96769. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  96770. /**
  96771. * The identity quaternion of the imposter
  96772. */
  96773. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  96774. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  96775. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  96776. //Impostor types
  96777. /**
  96778. * No-Imposter type
  96779. */
  96780. PhysicsImpostor.NoImpostor = 0;
  96781. /**
  96782. * Sphere-Imposter type
  96783. */
  96784. PhysicsImpostor.SphereImpostor = 1;
  96785. /**
  96786. * Box-Imposter type
  96787. */
  96788. PhysicsImpostor.BoxImpostor = 2;
  96789. /**
  96790. * Plane-Imposter type
  96791. */
  96792. PhysicsImpostor.PlaneImpostor = 3;
  96793. /**
  96794. * Mesh-imposter type
  96795. */
  96796. PhysicsImpostor.MeshImpostor = 4;
  96797. /**
  96798. * Cylinder-Imposter type
  96799. */
  96800. PhysicsImpostor.CylinderImpostor = 7;
  96801. /**
  96802. * Particle-Imposter type
  96803. */
  96804. PhysicsImpostor.ParticleImpostor = 8;
  96805. /**
  96806. * Heightmap-Imposter type
  96807. */
  96808. PhysicsImpostor.HeightmapImpostor = 9;
  96809. return PhysicsImpostor;
  96810. }());
  96811. BABYLON.PhysicsImpostor = PhysicsImpostor;
  96812. })(BABYLON || (BABYLON = {}));
  96813. //# sourceMappingURL=babylon.physicsImpostor.js.map
  96814. var BABYLON;
  96815. (function (BABYLON) {
  96816. /**
  96817. * Class used to control physics engine
  96818. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  96819. */
  96820. var PhysicsEngine = /** @class */ (function () {
  96821. /**
  96822. * Creates a new Physics Engine
  96823. * @param gravity defines the gravity vector used by the simulation
  96824. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  96825. */
  96826. function PhysicsEngine(gravity, _physicsPlugin) {
  96827. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  96828. this._physicsPlugin = _physicsPlugin;
  96829. this._impostors = [];
  96830. this._joints = [];
  96831. if (!this._physicsPlugin.isSupported()) {
  96832. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  96833. + "Please make sure it is included.");
  96834. }
  96835. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  96836. this.setGravity(gravity);
  96837. this.setTimeStep();
  96838. }
  96839. /**
  96840. * Sets the gravity vector used by the simulation
  96841. * @param gravity defines the gravity vector to use
  96842. */
  96843. PhysicsEngine.prototype.setGravity = function (gravity) {
  96844. this.gravity = gravity;
  96845. this._physicsPlugin.setGravity(this.gravity);
  96846. };
  96847. /**
  96848. * Set the time step of the physics engine.
  96849. * Default is 1/60.
  96850. * To slow it down, enter 1/600 for example.
  96851. * To speed it up, 1/30
  96852. * @param newTimeStep defines the new timestep to apply to this world.
  96853. */
  96854. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  96855. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  96856. this._physicsPlugin.setTimeStep(newTimeStep);
  96857. };
  96858. /**
  96859. * Get the time step of the physics engine.
  96860. * @returns the current time step
  96861. */
  96862. PhysicsEngine.prototype.getTimeStep = function () {
  96863. return this._physicsPlugin.getTimeStep();
  96864. };
  96865. /**
  96866. * Release all resources
  96867. */
  96868. PhysicsEngine.prototype.dispose = function () {
  96869. this._impostors.forEach(function (impostor) {
  96870. impostor.dispose();
  96871. });
  96872. this._physicsPlugin.dispose();
  96873. };
  96874. /**
  96875. * Gets the name of the current physics plugin
  96876. * @returns the name of the plugin
  96877. */
  96878. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  96879. return this._physicsPlugin.name;
  96880. };
  96881. /**
  96882. * Adding a new impostor for the impostor tracking.
  96883. * This will be done by the impostor itself.
  96884. * @param impostor the impostor to add
  96885. */
  96886. PhysicsEngine.prototype.addImpostor = function (impostor) {
  96887. impostor.uniqueId = this._impostors.push(impostor);
  96888. //if no parent, generate the body
  96889. if (!impostor.parent) {
  96890. this._physicsPlugin.generatePhysicsBody(impostor);
  96891. }
  96892. };
  96893. /**
  96894. * Remove an impostor from the engine.
  96895. * This impostor and its mesh will not longer be updated by the physics engine.
  96896. * @param impostor the impostor to remove
  96897. */
  96898. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  96899. var index = this._impostors.indexOf(impostor);
  96900. if (index > -1) {
  96901. var removed = this._impostors.splice(index, 1);
  96902. //Is it needed?
  96903. if (removed.length) {
  96904. //this will also remove it from the world.
  96905. removed[0].physicsBody = null;
  96906. }
  96907. }
  96908. };
  96909. /**
  96910. * Add a joint to the physics engine
  96911. * @param mainImpostor defines the main impostor to which the joint is added.
  96912. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  96913. * @param joint defines the joint that will connect both impostors.
  96914. */
  96915. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  96916. var impostorJoint = {
  96917. mainImpostor: mainImpostor,
  96918. connectedImpostor: connectedImpostor,
  96919. joint: joint
  96920. };
  96921. joint.physicsPlugin = this._physicsPlugin;
  96922. this._joints.push(impostorJoint);
  96923. this._physicsPlugin.generateJoint(impostorJoint);
  96924. };
  96925. /**
  96926. * Removes a joint from the simulation
  96927. * @param mainImpostor defines the impostor used with the joint
  96928. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  96929. * @param joint defines the joint to remove
  96930. */
  96931. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  96932. var matchingJoints = this._joints.filter(function (impostorJoint) {
  96933. return (impostorJoint.connectedImpostor === connectedImpostor
  96934. && impostorJoint.joint === joint
  96935. && impostorJoint.mainImpostor === mainImpostor);
  96936. });
  96937. if (matchingJoints.length) {
  96938. this._physicsPlugin.removeJoint(matchingJoints[0]);
  96939. //TODO remove it from the list as well
  96940. }
  96941. };
  96942. /**
  96943. * Called by the scene. No need to call it.
  96944. * @param delta defines the timespam between frames
  96945. */
  96946. PhysicsEngine.prototype._step = function (delta) {
  96947. var _this = this;
  96948. //check if any mesh has no body / requires an update
  96949. this._impostors.forEach(function (impostor) {
  96950. if (impostor.isBodyInitRequired()) {
  96951. _this._physicsPlugin.generatePhysicsBody(impostor);
  96952. }
  96953. });
  96954. if (delta > 0.1) {
  96955. delta = 0.1;
  96956. }
  96957. else if (delta <= 0) {
  96958. delta = 1.0 / 60.0;
  96959. }
  96960. this._physicsPlugin.executeStep(delta, this._impostors);
  96961. };
  96962. /**
  96963. * Gets the current plugin used to run the simulation
  96964. * @returns current plugin
  96965. */
  96966. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  96967. return this._physicsPlugin;
  96968. };
  96969. /**
  96970. * Gets the list of physic impostors
  96971. * @returns an array of PhysicsImpostor
  96972. */
  96973. PhysicsEngine.prototype.getImpostors = function () {
  96974. return this._impostors;
  96975. };
  96976. /**
  96977. * Gets the impostor for a physics enabled object
  96978. * @param object defines the object impersonated by the impostor
  96979. * @returns the PhysicsImpostor or null if not found
  96980. */
  96981. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  96982. for (var i = 0; i < this._impostors.length; ++i) {
  96983. if (this._impostors[i].object === object) {
  96984. return this._impostors[i];
  96985. }
  96986. }
  96987. return null;
  96988. };
  96989. /**
  96990. * Gets the impostor for a physics body object
  96991. * @param body defines physics body used by the impostor
  96992. * @returns the PhysicsImpostor or null if not found
  96993. */
  96994. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  96995. for (var i = 0; i < this._impostors.length; ++i) {
  96996. if (this._impostors[i].physicsBody === body) {
  96997. return this._impostors[i];
  96998. }
  96999. }
  97000. return null;
  97001. };
  97002. /**
  97003. * Global value used to control the smallest number supported by the simulation
  97004. */
  97005. PhysicsEngine.Epsilon = 0.001;
  97006. return PhysicsEngine;
  97007. }());
  97008. BABYLON.PhysicsEngine = PhysicsEngine;
  97009. })(BABYLON || (BABYLON = {}));
  97010. //# sourceMappingURL=babylon.physicsEngine.js.map
  97011. var BABYLON;
  97012. (function (BABYLON) {
  97013. /**
  97014. * A helper for physics simulations
  97015. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97016. */
  97017. var PhysicsHelper = /** @class */ (function () {
  97018. /**
  97019. * Initializes the Physics helper
  97020. * @param scene Babylon.js scene
  97021. */
  97022. function PhysicsHelper(scene) {
  97023. this._scene = scene;
  97024. this._physicsEngine = this._scene.getPhysicsEngine();
  97025. if (!this._physicsEngine) {
  97026. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  97027. }
  97028. }
  97029. /**
  97030. * Applies a radial explosion impulse
  97031. * @param origin the origin of the explosion
  97032. * @param radius the explosion radius
  97033. * @param strength the explosion strength
  97034. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97035. * @returns A physics radial explosion event, or null
  97036. */
  97037. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  97038. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97039. if (!this._physicsEngine) {
  97040. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  97041. return null;
  97042. }
  97043. var impostors = this._physicsEngine.getImpostors();
  97044. if (impostors.length === 0) {
  97045. return null;
  97046. }
  97047. var event = new PhysicsRadialExplosionEvent(this._scene);
  97048. impostors.forEach(function (impostor) {
  97049. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97050. if (!impostorForceAndContactPoint) {
  97051. return;
  97052. }
  97053. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97054. });
  97055. event.dispose(false);
  97056. return event;
  97057. };
  97058. /**
  97059. * Applies a radial explosion force
  97060. * @param origin the origin of the explosion
  97061. * @param radius the explosion radius
  97062. * @param strength the explosion strength
  97063. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97064. * @returns A physics radial explosion event, or null
  97065. */
  97066. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  97067. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97068. if (!this._physicsEngine) {
  97069. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97070. return null;
  97071. }
  97072. var impostors = this._physicsEngine.getImpostors();
  97073. if (impostors.length === 0) {
  97074. return null;
  97075. }
  97076. var event = new PhysicsRadialExplosionEvent(this._scene);
  97077. impostors.forEach(function (impostor) {
  97078. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97079. if (!impostorForceAndContactPoint) {
  97080. return;
  97081. }
  97082. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97083. });
  97084. event.dispose(false);
  97085. return event;
  97086. };
  97087. /**
  97088. * Creates a gravitational field
  97089. * @param origin the origin of the explosion
  97090. * @param radius the explosion radius
  97091. * @param strength the explosion strength
  97092. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97093. * @returns A physics gravitational field event, or null
  97094. */
  97095. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  97096. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97097. if (!this._physicsEngine) {
  97098. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97099. return null;
  97100. }
  97101. var impostors = this._physicsEngine.getImpostors();
  97102. if (impostors.length === 0) {
  97103. return null;
  97104. }
  97105. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  97106. event.dispose(false);
  97107. return event;
  97108. };
  97109. /**
  97110. * Creates a physics updraft event
  97111. * @param origin the origin of the updraft
  97112. * @param radius the radius of the updraft
  97113. * @param strength the strength of the updraft
  97114. * @param height the height of the updraft
  97115. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  97116. * @returns A physics updraft event, or null
  97117. */
  97118. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  97119. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  97120. if (!this._physicsEngine) {
  97121. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97122. return null;
  97123. }
  97124. if (this._physicsEngine.getImpostors().length === 0) {
  97125. return null;
  97126. }
  97127. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  97128. event.dispose(false);
  97129. return event;
  97130. };
  97131. /**
  97132. * Creates a physics vortex event
  97133. * @param origin the of the vortex
  97134. * @param radius the radius of the vortex
  97135. * @param strength the strength of the vortex
  97136. * @param height the height of the vortex
  97137. * @returns a Physics vortex event, or null
  97138. * A physics vortex event or null
  97139. */
  97140. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  97141. if (!this._physicsEngine) {
  97142. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97143. return null;
  97144. }
  97145. if (this._physicsEngine.getImpostors().length === 0) {
  97146. return null;
  97147. }
  97148. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  97149. event.dispose(false);
  97150. return event;
  97151. };
  97152. return PhysicsHelper;
  97153. }());
  97154. BABYLON.PhysicsHelper = PhysicsHelper;
  97155. /**
  97156. * Represents a physics radial explosion event
  97157. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97158. */
  97159. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  97160. /**
  97161. * Initializes a radial explosioin event
  97162. * @param scene BabylonJS scene
  97163. */
  97164. function PhysicsRadialExplosionEvent(scene) {
  97165. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  97166. this._rays = [];
  97167. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  97168. this._scene = scene;
  97169. }
  97170. /**
  97171. * Returns the data related to the radial explosion event (sphere & rays).
  97172. * @returns The radial explosion event data
  97173. */
  97174. PhysicsRadialExplosionEvent.prototype.getData = function () {
  97175. this._dataFetched = true;
  97176. return {
  97177. sphere: this._sphere,
  97178. rays: this._rays,
  97179. };
  97180. };
  97181. /**
  97182. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  97183. * @param impostor A physics imposter
  97184. * @param origin the origin of the explosion
  97185. * @param radius the explosion radius
  97186. * @param strength the explosion strength
  97187. * @param falloff possible options: Constant & Linear
  97188. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  97189. */
  97190. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  97191. if (impostor.mass === 0) {
  97192. return null;
  97193. }
  97194. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  97195. return null;
  97196. }
  97197. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97198. return null;
  97199. }
  97200. var impostorObjectCenter = impostor.getObjectCenter();
  97201. var direction = impostorObjectCenter.subtract(origin);
  97202. var ray = new BABYLON.Ray(origin, direction, radius);
  97203. this._rays.push(ray);
  97204. var hit = ray.intersectsMesh(impostor.object);
  97205. var contactPoint = hit.pickedPoint;
  97206. if (!contactPoint) {
  97207. return null;
  97208. }
  97209. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  97210. if (distanceFromOrigin > radius) {
  97211. return null;
  97212. }
  97213. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  97214. ? strength
  97215. : strength * (1 - (distanceFromOrigin / radius));
  97216. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97217. return { force: force, contactPoint: contactPoint };
  97218. };
  97219. /**
  97220. * Disposes the sphere.
  97221. * @param force Specifies if the sphere should be disposed by force
  97222. */
  97223. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  97224. var _this = this;
  97225. if (force === void 0) { force = true; }
  97226. if (force) {
  97227. this._sphere.dispose();
  97228. }
  97229. else {
  97230. setTimeout(function () {
  97231. if (!_this._dataFetched) {
  97232. _this._sphere.dispose();
  97233. }
  97234. }, 0);
  97235. }
  97236. };
  97237. /*** Helpers ***/
  97238. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  97239. if (!this._sphere) {
  97240. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  97241. this._sphere.isVisible = false;
  97242. }
  97243. };
  97244. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  97245. var impostorObject = impostor.object;
  97246. this._prepareSphere();
  97247. this._sphere.position = origin;
  97248. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  97249. this._sphere._updateBoundingInfo();
  97250. this._sphere.computeWorldMatrix(true);
  97251. return this._sphere.intersectsMesh(impostorObject, true);
  97252. };
  97253. return PhysicsRadialExplosionEvent;
  97254. }());
  97255. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  97256. /**
  97257. * Represents a gravitational field event
  97258. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97259. */
  97260. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  97261. /**
  97262. * Initializes the physics gravitational field event
  97263. * @param physicsHelper A physics helper
  97264. * @param scene BabylonJS scene
  97265. * @param origin The origin position of the gravitational field event
  97266. * @param radius The radius of the gravitational field event
  97267. * @param strength The strength of the gravitational field event
  97268. * @param falloff The falloff for the gravitational field event
  97269. */
  97270. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  97271. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97272. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97273. this._physicsHelper = physicsHelper;
  97274. this._scene = scene;
  97275. this._origin = origin;
  97276. this._radius = radius;
  97277. this._strength = strength;
  97278. this._falloff = falloff;
  97279. this._tickCallback = this._tick.bind(this);
  97280. }
  97281. /**
  97282. * Returns the data related to the gravitational field event (sphere).
  97283. * @returns A gravitational field event
  97284. */
  97285. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  97286. this._dataFetched = true;
  97287. return {
  97288. sphere: this._sphere,
  97289. };
  97290. };
  97291. /**
  97292. * Enables the gravitational field.
  97293. */
  97294. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  97295. this._tickCallback.call(this);
  97296. this._scene.registerBeforeRender(this._tickCallback);
  97297. };
  97298. /**
  97299. * Disables the gravitational field.
  97300. */
  97301. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  97302. this._scene.unregisterBeforeRender(this._tickCallback);
  97303. };
  97304. /**
  97305. * Disposes the sphere.
  97306. * @param force The force to dispose from the gravitational field event
  97307. */
  97308. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  97309. var _this = this;
  97310. if (force === void 0) { force = true; }
  97311. if (force) {
  97312. this._sphere.dispose();
  97313. }
  97314. else {
  97315. setTimeout(function () {
  97316. if (!_this._dataFetched) {
  97317. _this._sphere.dispose();
  97318. }
  97319. }, 0);
  97320. }
  97321. };
  97322. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  97323. // Since the params won't change, we fetch the event only once
  97324. if (this._sphere) {
  97325. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97326. }
  97327. else {
  97328. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97329. if (radialExplosionEvent) {
  97330. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  97331. }
  97332. }
  97333. };
  97334. return PhysicsGravitationalFieldEvent;
  97335. }());
  97336. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  97337. /**
  97338. * Represents a physics updraft event
  97339. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97340. */
  97341. var PhysicsUpdraftEvent = /** @class */ (function () {
  97342. /**
  97343. * Initializes the physics updraft event
  97344. * @param _scene BabylonJS scene
  97345. * @param _origin The origin position of the updraft
  97346. * @param _radius The radius of the updraft
  97347. * @param _strength The strength of the updraft
  97348. * @param _height The height of the updraft
  97349. * @param _updraftMode The mode of the updraft
  97350. */
  97351. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  97352. this._scene = _scene;
  97353. this._origin = _origin;
  97354. this._radius = _radius;
  97355. this._strength = _strength;
  97356. this._height = _height;
  97357. this._updraftMode = _updraftMode;
  97358. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97359. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  97360. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97361. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97362. this._physicsEngine = this._scene.getPhysicsEngine();
  97363. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97364. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97365. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97366. this._originDirection = this._origin.subtract(this._originTop).normalize();
  97367. }
  97368. this._tickCallback = this._tick.bind(this);
  97369. }
  97370. /**
  97371. * Returns the data related to the updraft event (cylinder).
  97372. * @returns A physics updraft event
  97373. */
  97374. PhysicsUpdraftEvent.prototype.getData = function () {
  97375. this._dataFetched = true;
  97376. return {
  97377. cylinder: this._cylinder,
  97378. };
  97379. };
  97380. /**
  97381. * Enables the updraft.
  97382. */
  97383. PhysicsUpdraftEvent.prototype.enable = function () {
  97384. this._tickCallback.call(this);
  97385. this._scene.registerBeforeRender(this._tickCallback);
  97386. };
  97387. /**
  97388. * Disables the cortex.
  97389. */
  97390. PhysicsUpdraftEvent.prototype.disable = function () {
  97391. this._scene.unregisterBeforeRender(this._tickCallback);
  97392. };
  97393. /**
  97394. * Disposes the sphere.
  97395. * @param force Specifies if the updraft should be disposed by force
  97396. */
  97397. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  97398. var _this = this;
  97399. if (force === void 0) { force = true; }
  97400. if (force) {
  97401. this._cylinder.dispose();
  97402. }
  97403. else {
  97404. setTimeout(function () {
  97405. if (!_this._dataFetched) {
  97406. _this._cylinder.dispose();
  97407. }
  97408. }, 0);
  97409. }
  97410. };
  97411. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97412. if (impostor.mass === 0) {
  97413. return null;
  97414. }
  97415. if (!this._intersectsWithCylinder(impostor)) {
  97416. return null;
  97417. }
  97418. var impostorObjectCenter = impostor.getObjectCenter();
  97419. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97420. var direction = this._originDirection;
  97421. }
  97422. else {
  97423. var direction = impostorObjectCenter.subtract(this._originTop);
  97424. }
  97425. var multiplier = this._strength * -1;
  97426. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97427. return { force: force, contactPoint: impostorObjectCenter };
  97428. };
  97429. PhysicsUpdraftEvent.prototype._tick = function () {
  97430. var _this = this;
  97431. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97432. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97433. if (!impostorForceAndContactPoint) {
  97434. return;
  97435. }
  97436. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97437. });
  97438. };
  97439. /*** Helpers ***/
  97440. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  97441. if (!this._cylinder) {
  97442. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  97443. height: this._height,
  97444. diameter: this._radius * 2,
  97445. }, this._scene);
  97446. this._cylinder.isVisible = false;
  97447. }
  97448. };
  97449. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  97450. var impostorObject = impostor.object;
  97451. this._prepareCylinder();
  97452. this._cylinder.position = this._cylinderPosition;
  97453. return this._cylinder.intersectsMesh(impostorObject, true);
  97454. };
  97455. return PhysicsUpdraftEvent;
  97456. }());
  97457. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  97458. /**
  97459. * Represents a physics vortex event
  97460. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97461. */
  97462. var PhysicsVortexEvent = /** @class */ (function () {
  97463. /**
  97464. * Initializes the physics vortex event
  97465. * @param _scene The BabylonJS scene
  97466. * @param _origin The origin position of the vortex
  97467. * @param _radius The radius of the vortex
  97468. * @param _strength The strength of the vortex
  97469. * @param _height The height of the vortex
  97470. */
  97471. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  97472. this._scene = _scene;
  97473. this._origin = _origin;
  97474. this._radius = _radius;
  97475. this._strength = _strength;
  97476. this._height = _height;
  97477. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97478. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  97479. this._updraftMultiplier = 0.02;
  97480. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97481. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97482. this._physicsEngine = this._scene.getPhysicsEngine();
  97483. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97484. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97485. this._tickCallback = this._tick.bind(this);
  97486. }
  97487. /**
  97488. * Returns the data related to the vortex event (cylinder).
  97489. * @returns The physics vortex event data
  97490. */
  97491. PhysicsVortexEvent.prototype.getData = function () {
  97492. this._dataFetched = true;
  97493. return {
  97494. cylinder: this._cylinder,
  97495. };
  97496. };
  97497. /**
  97498. * Enables the vortex.
  97499. */
  97500. PhysicsVortexEvent.prototype.enable = function () {
  97501. this._tickCallback.call(this);
  97502. this._scene.registerBeforeRender(this._tickCallback);
  97503. };
  97504. /**
  97505. * Disables the cortex.
  97506. */
  97507. PhysicsVortexEvent.prototype.disable = function () {
  97508. this._scene.unregisterBeforeRender(this._tickCallback);
  97509. };
  97510. /**
  97511. * Disposes the sphere.
  97512. * @param force
  97513. */
  97514. PhysicsVortexEvent.prototype.dispose = function (force) {
  97515. var _this = this;
  97516. if (force === void 0) { force = true; }
  97517. if (force) {
  97518. this._cylinder.dispose();
  97519. }
  97520. else {
  97521. setTimeout(function () {
  97522. if (!_this._dataFetched) {
  97523. _this._cylinder.dispose();
  97524. }
  97525. }, 0);
  97526. }
  97527. };
  97528. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97529. if (impostor.mass === 0) {
  97530. return null;
  97531. }
  97532. if (!this._intersectsWithCylinder(impostor)) {
  97533. return null;
  97534. }
  97535. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97536. return null;
  97537. }
  97538. var impostorObjectCenter = impostor.getObjectCenter();
  97539. 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)
  97540. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  97541. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  97542. var hit = ray.intersectsMesh(impostor.object);
  97543. var contactPoint = hit.pickedPoint;
  97544. if (!contactPoint) {
  97545. return null;
  97546. }
  97547. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  97548. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  97549. var directionToOrigin = contactPoint.normalize();
  97550. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97551. directionToOrigin = directionToOrigin.negate();
  97552. }
  97553. // TODO: find a more physically based solution
  97554. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97555. var forceX = directionToOrigin.x * this._strength / 8;
  97556. var forceY = directionToOrigin.y * this._updraftMultiplier;
  97557. var forceZ = directionToOrigin.z * this._strength / 8;
  97558. }
  97559. else {
  97560. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  97561. var forceY = this._originTop.y * this._updraftMultiplier;
  97562. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  97563. }
  97564. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  97565. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  97566. return { force: force, contactPoint: impostorObjectCenter };
  97567. };
  97568. PhysicsVortexEvent.prototype._tick = function () {
  97569. var _this = this;
  97570. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97571. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97572. if (!impostorForceAndContactPoint) {
  97573. return;
  97574. }
  97575. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97576. });
  97577. };
  97578. /*** Helpers ***/
  97579. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  97580. if (!this._cylinder) {
  97581. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  97582. height: this._height,
  97583. diameter: this._radius * 2,
  97584. }, this._scene);
  97585. this._cylinder.isVisible = false;
  97586. }
  97587. };
  97588. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  97589. var impostorObject = impostor.object;
  97590. this._prepareCylinder();
  97591. this._cylinder.position = this._cylinderPosition;
  97592. return this._cylinder.intersectsMesh(impostorObject, true);
  97593. };
  97594. return PhysicsVortexEvent;
  97595. }());
  97596. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  97597. /**
  97598. * The strenght of the force in correspondence to the distance of the affected object
  97599. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97600. */
  97601. var PhysicsRadialImpulseFalloff;
  97602. (function (PhysicsRadialImpulseFalloff) {
  97603. /** Defines that impulse is constant in strength across it's whole radius */
  97604. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  97605. /** DEfines that impulse gets weaker if it's further from the origin */
  97606. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  97607. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  97608. /**
  97609. * The strength of the force in correspondence to the distance of the affected object
  97610. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97611. */
  97612. var PhysicsUpdraftMode;
  97613. (function (PhysicsUpdraftMode) {
  97614. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  97615. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  97616. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  97617. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  97618. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  97619. })(BABYLON || (BABYLON = {}));
  97620. //# sourceMappingURL=babylon.physicsHelper.js.map
  97621. var BABYLON;
  97622. (function (BABYLON) {
  97623. /** @hidden */
  97624. var CannonJSPlugin = /** @class */ (function () {
  97625. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  97626. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  97627. if (iterations === void 0) { iterations = 10; }
  97628. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  97629. this.name = "CannonJSPlugin";
  97630. this._physicsMaterials = new Array();
  97631. this._fixedTimeStep = 1 / 60;
  97632. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  97633. this.BJSCANNON = CANNON;
  97634. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  97635. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  97636. this._tmpPosition = BABYLON.Vector3.Zero();
  97637. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  97638. this._tmpUnityRotation = new BABYLON.Quaternion();
  97639. if (!this.isSupported()) {
  97640. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  97641. return;
  97642. }
  97643. this._extendNamespace();
  97644. this.world = new this.BJSCANNON.World();
  97645. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  97646. this.world.solver.iterations = iterations;
  97647. }
  97648. CannonJSPlugin.prototype.setGravity = function (gravity) {
  97649. this.world.gravity.copy(gravity);
  97650. };
  97651. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  97652. this._fixedTimeStep = timeStep;
  97653. };
  97654. CannonJSPlugin.prototype.getTimeStep = function () {
  97655. return this._fixedTimeStep;
  97656. };
  97657. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  97658. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  97659. };
  97660. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  97661. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97662. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97663. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  97664. };
  97665. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  97666. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97667. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97668. impostor.physicsBody.applyForce(impulse, worldPoint);
  97669. };
  97670. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  97671. //parent-child relationship. Does this impostor has a parent impostor?
  97672. if (impostor.parent) {
  97673. if (impostor.physicsBody) {
  97674. this.removePhysicsBody(impostor);
  97675. //TODO is that needed?
  97676. impostor.forceUpdate();
  97677. }
  97678. return;
  97679. }
  97680. //should a new body be created for this impostor?
  97681. if (impostor.isBodyInitRequired()) {
  97682. var shape = this._createShape(impostor);
  97683. //unregister events, if body is being changed
  97684. var oldBody = impostor.physicsBody;
  97685. if (oldBody) {
  97686. this.removePhysicsBody(impostor);
  97687. }
  97688. //create the body and material
  97689. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  97690. var bodyCreationObject = {
  97691. mass: impostor.getParam("mass"),
  97692. material: material
  97693. };
  97694. // A simple extend, in case native options were used.
  97695. var nativeOptions = impostor.getParam("nativeOptions");
  97696. for (var key in nativeOptions) {
  97697. if (nativeOptions.hasOwnProperty(key)) {
  97698. bodyCreationObject[key] = nativeOptions[key];
  97699. }
  97700. }
  97701. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  97702. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  97703. this.world.addEventListener("preStep", impostor.beforeStep);
  97704. this.world.addEventListener("postStep", impostor.afterStep);
  97705. impostor.physicsBody.addShape(shape);
  97706. this.world.add(impostor.physicsBody);
  97707. //try to keep the body moving in the right direction by taking old properties.
  97708. //Should be tested!
  97709. if (oldBody) {
  97710. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  97711. impostor.physicsBody[param].copy(oldBody[param]);
  97712. });
  97713. }
  97714. this._processChildMeshes(impostor);
  97715. }
  97716. //now update the body's transformation
  97717. this._updatePhysicsBodyTransformation(impostor);
  97718. };
  97719. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  97720. var _this = this;
  97721. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  97722. var currentRotation = mainImpostor.object.rotationQuaternion;
  97723. if (meshChildren.length) {
  97724. var processMesh = function (localPosition, mesh) {
  97725. if (!currentRotation || !mesh.rotationQuaternion) {
  97726. return;
  97727. }
  97728. var childImpostor = mesh.getPhysicsImpostor();
  97729. if (childImpostor) {
  97730. var parent = childImpostor.parent;
  97731. if (parent !== mainImpostor) {
  97732. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  97733. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  97734. if (childImpostor.physicsBody) {
  97735. _this.removePhysicsBody(childImpostor);
  97736. childImpostor.physicsBody = null;
  97737. }
  97738. childImpostor.parent = mainImpostor;
  97739. childImpostor.resetUpdateFlags();
  97740. 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));
  97741. //Add the mass of the children.
  97742. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  97743. }
  97744. }
  97745. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  97746. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  97747. };
  97748. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  97749. }
  97750. };
  97751. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97752. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  97753. this.world.removeEventListener("preStep", impostor.beforeStep);
  97754. this.world.removeEventListener("postStep", impostor.afterStep);
  97755. this.world.remove(impostor.physicsBody);
  97756. };
  97757. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97758. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97759. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97760. if (!mainBody || !connectedBody) {
  97761. return;
  97762. }
  97763. var constraint;
  97764. var jointData = impostorJoint.joint.jointData;
  97765. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  97766. var constraintData = {
  97767. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  97768. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  97769. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  97770. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  97771. maxForce: jointData.nativeParams.maxForce,
  97772. collideConnected: !!jointData.collision
  97773. };
  97774. switch (impostorJoint.joint.type) {
  97775. case BABYLON.PhysicsJoint.HingeJoint:
  97776. case BABYLON.PhysicsJoint.Hinge2Joint:
  97777. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  97778. break;
  97779. case BABYLON.PhysicsJoint.DistanceJoint:
  97780. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  97781. break;
  97782. case BABYLON.PhysicsJoint.SpringJoint:
  97783. var springData = jointData;
  97784. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  97785. restLength: springData.length,
  97786. stiffness: springData.stiffness,
  97787. damping: springData.damping,
  97788. localAnchorA: constraintData.pivotA,
  97789. localAnchorB: constraintData.pivotB
  97790. });
  97791. break;
  97792. case BABYLON.PhysicsJoint.LockJoint:
  97793. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  97794. break;
  97795. case BABYLON.PhysicsJoint.PointToPointJoint:
  97796. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97797. default:
  97798. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  97799. break;
  97800. }
  97801. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  97802. constraint.collideConnected = !!jointData.collision;
  97803. impostorJoint.joint.physicsJoint = constraint;
  97804. //don't add spring as constraint, as it is not one.
  97805. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97806. this.world.addConstraint(constraint);
  97807. }
  97808. else {
  97809. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  97810. constraint.applyForce();
  97811. };
  97812. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97813. }
  97814. };
  97815. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97816. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97817. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  97818. }
  97819. else {
  97820. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97821. }
  97822. };
  97823. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  97824. var index;
  97825. var mat;
  97826. for (index = 0; index < this._physicsMaterials.length; index++) {
  97827. mat = this._physicsMaterials[index];
  97828. if (mat.friction === friction && mat.restitution === restitution) {
  97829. return mat;
  97830. }
  97831. }
  97832. var currentMat = new this.BJSCANNON.Material(name);
  97833. currentMat.friction = friction;
  97834. currentMat.restitution = restitution;
  97835. this._physicsMaterials.push(currentMat);
  97836. return currentMat;
  97837. };
  97838. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  97839. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  97840. };
  97841. CannonJSPlugin.prototype._createShape = function (impostor) {
  97842. var object = impostor.object;
  97843. var returnValue;
  97844. var extendSize = impostor.getObjectExtendSize();
  97845. switch (impostor.type) {
  97846. case BABYLON.PhysicsImpostor.SphereImpostor:
  97847. var radiusX = extendSize.x;
  97848. var radiusY = extendSize.y;
  97849. var radiusZ = extendSize.z;
  97850. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  97851. break;
  97852. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  97853. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97854. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  97855. break;
  97856. case BABYLON.PhysicsImpostor.BoxImpostor:
  97857. var box = extendSize.scale(0.5);
  97858. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  97859. break;
  97860. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97861. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  97862. returnValue = new this.BJSCANNON.Plane();
  97863. break;
  97864. case BABYLON.PhysicsImpostor.MeshImpostor:
  97865. // should transform the vertex data to world coordinates!!
  97866. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  97867. var rawFaces = object.getIndices ? object.getIndices() : [];
  97868. if (!rawVerts) {
  97869. return;
  97870. }
  97871. // get only scale! so the object could transform correctly.
  97872. var oldPosition = object.position.clone();
  97873. var oldRotation = object.rotation && object.rotation.clone();
  97874. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  97875. object.position.copyFromFloats(0, 0, 0);
  97876. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97877. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97878. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97879. var transform = object.computeWorldMatrix(true);
  97880. // convert rawVerts to object space
  97881. var temp = new Array();
  97882. var index;
  97883. for (index = 0; index < rawVerts.length; index += 3) {
  97884. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  97885. }
  97886. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  97887. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  97888. //now set back the transformation!
  97889. object.position.copyFrom(oldPosition);
  97890. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  97891. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  97892. break;
  97893. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  97894. var oldPosition2 = object.position.clone();
  97895. var oldRotation2 = object.rotation && object.rotation.clone();
  97896. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  97897. object.position.copyFromFloats(0, 0, 0);
  97898. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97899. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97900. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97901. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  97902. returnValue = this._createHeightmap(object);
  97903. object.position.copyFrom(oldPosition2);
  97904. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  97905. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  97906. object.computeWorldMatrix(true);
  97907. break;
  97908. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97909. returnValue = new this.BJSCANNON.Particle();
  97910. break;
  97911. }
  97912. return returnValue;
  97913. };
  97914. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  97915. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97916. var transform = object.computeWorldMatrix(true);
  97917. // convert rawVerts to object space
  97918. var temp = new Array();
  97919. var index;
  97920. for (index = 0; index < pos.length; index += 3) {
  97921. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  97922. }
  97923. pos = temp;
  97924. var matrix = new Array();
  97925. //For now pointDepth will not be used and will be automatically calculated.
  97926. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  97927. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  97928. var boundingInfo = object.getBoundingInfo();
  97929. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  97930. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  97931. var elementSize = dim * 2 / arraySize;
  97932. for (var i = 0; i < pos.length; i = i + 3) {
  97933. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  97934. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  97935. var y = -pos[i + 2] + minY;
  97936. if (!matrix[x]) {
  97937. matrix[x] = [];
  97938. }
  97939. if (!matrix[x][z]) {
  97940. matrix[x][z] = y;
  97941. }
  97942. matrix[x][z] = Math.max(y, matrix[x][z]);
  97943. }
  97944. for (var x = 0; x <= arraySize; ++x) {
  97945. if (!matrix[x]) {
  97946. var loc = 1;
  97947. while (!matrix[(x + loc) % arraySize]) {
  97948. loc++;
  97949. }
  97950. matrix[x] = matrix[(x + loc) % arraySize].slice();
  97951. //console.log("missing x", x);
  97952. }
  97953. for (var z = 0; z <= arraySize; ++z) {
  97954. if (!matrix[x][z]) {
  97955. var loc = 1;
  97956. var newValue;
  97957. while (newValue === undefined) {
  97958. newValue = matrix[x][(z + loc++) % arraySize];
  97959. }
  97960. matrix[x][z] = newValue;
  97961. }
  97962. }
  97963. }
  97964. var shape = new this.BJSCANNON.Heightfield(matrix, {
  97965. elementSize: elementSize
  97966. });
  97967. //For future reference, needed for body transformation
  97968. shape.minY = minY;
  97969. return shape;
  97970. };
  97971. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  97972. var object = impostor.object;
  97973. //make sure it is updated...
  97974. object.computeWorldMatrix && object.computeWorldMatrix(true);
  97975. // The delta between the mesh position and the mesh bounding box center
  97976. var bInfo = object.getBoundingInfo();
  97977. if (!bInfo) {
  97978. return;
  97979. }
  97980. var center = impostor.getObjectCenter();
  97981. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  97982. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  97983. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  97984. this._tmpPosition.copyFrom(center);
  97985. var quaternion = object.rotationQuaternion;
  97986. if (!quaternion) {
  97987. return;
  97988. }
  97989. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  97990. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  97991. //-90 DEG in X, precalculated
  97992. quaternion = quaternion.multiply(this._minus90X);
  97993. //Invert! (Precalculated, 90 deg in X)
  97994. //No need to clone. this will never change.
  97995. impostor.setDeltaRotation(this._plus90X);
  97996. }
  97997. //If it is a heightfield, if should be centered.
  97998. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  97999. var mesh = object;
  98000. var boundingInfo = mesh.getBoundingInfo();
  98001. //calculate the correct body position:
  98002. var rotationQuaternion = mesh.rotationQuaternion;
  98003. mesh.rotationQuaternion = this._tmpUnityRotation;
  98004. mesh.computeWorldMatrix(true);
  98005. //get original center with no rotation
  98006. var c = center.clone();
  98007. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  98008. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  98009. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  98010. mesh.setPreTransformMatrix(p);
  98011. mesh.computeWorldMatrix(true);
  98012. //calculate the translation
  98013. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  98014. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  98015. //add it inverted to the delta
  98016. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  98017. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  98018. //rotation is back
  98019. mesh.rotationQuaternion = rotationQuaternion;
  98020. mesh.setPreTransformMatrix(oldPivot);
  98021. mesh.computeWorldMatrix(true);
  98022. }
  98023. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  98024. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  98025. //this._tmpPosition.copyFrom(object.position);
  98026. }
  98027. impostor.setDeltaPosition(this._tmpDeltaPosition);
  98028. //Now update the impostor object
  98029. impostor.physicsBody.position.copy(this._tmpPosition);
  98030. impostor.physicsBody.quaternion.copy(quaternion);
  98031. };
  98032. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98033. impostor.object.position.copyFrom(impostor.physicsBody.position);
  98034. if (impostor.object.rotationQuaternion) {
  98035. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  98036. }
  98037. };
  98038. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98039. impostor.physicsBody.position.copy(newPosition);
  98040. impostor.physicsBody.quaternion.copy(newRotation);
  98041. };
  98042. CannonJSPlugin.prototype.isSupported = function () {
  98043. return this.BJSCANNON !== undefined;
  98044. };
  98045. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98046. impostor.physicsBody.velocity.copy(velocity);
  98047. };
  98048. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98049. impostor.physicsBody.angularVelocity.copy(velocity);
  98050. };
  98051. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98052. var v = impostor.physicsBody.velocity;
  98053. if (!v) {
  98054. return null;
  98055. }
  98056. return new BABYLON.Vector3(v.x, v.y, v.z);
  98057. };
  98058. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98059. var v = impostor.physicsBody.angularVelocity;
  98060. if (!v) {
  98061. return null;
  98062. }
  98063. return new BABYLON.Vector3(v.x, v.y, v.z);
  98064. };
  98065. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98066. impostor.physicsBody.mass = mass;
  98067. impostor.physicsBody.updateMassProperties();
  98068. };
  98069. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  98070. return impostor.physicsBody.mass;
  98071. };
  98072. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  98073. return impostor.physicsBody.material.friction;
  98074. };
  98075. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98076. impostor.physicsBody.material.friction = friction;
  98077. };
  98078. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98079. return impostor.physicsBody.material.restitution;
  98080. };
  98081. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98082. impostor.physicsBody.material.restitution = restitution;
  98083. };
  98084. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  98085. impostor.physicsBody.sleep();
  98086. };
  98087. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  98088. impostor.physicsBody.wakeUp();
  98089. };
  98090. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98091. joint.physicsJoint.distance = maxDistance;
  98092. };
  98093. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98094. // if (!motorIndex) {
  98095. // joint.physicsJoint.enableMotor();
  98096. // }
  98097. // }
  98098. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98099. // if (!motorIndex) {
  98100. // joint.physicsJoint.disableMotor();
  98101. // }
  98102. // }
  98103. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98104. if (!motorIndex) {
  98105. joint.physicsJoint.enableMotor();
  98106. joint.physicsJoint.setMotorSpeed(speed);
  98107. if (maxForce) {
  98108. this.setLimit(joint, maxForce);
  98109. }
  98110. }
  98111. };
  98112. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  98113. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  98114. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  98115. };
  98116. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98117. var body = impostor.physicsBody;
  98118. mesh.position.x = body.position.x;
  98119. mesh.position.y = body.position.y;
  98120. mesh.position.z = body.position.z;
  98121. if (mesh.rotationQuaternion) {
  98122. mesh.rotationQuaternion.x = body.quaternion.x;
  98123. mesh.rotationQuaternion.y = body.quaternion.y;
  98124. mesh.rotationQuaternion.z = body.quaternion.z;
  98125. mesh.rotationQuaternion.w = body.quaternion.w;
  98126. }
  98127. };
  98128. CannonJSPlugin.prototype.getRadius = function (impostor) {
  98129. var shape = impostor.physicsBody.shapes[0];
  98130. return shape.boundingSphereRadius;
  98131. };
  98132. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98133. var shape = impostor.physicsBody.shapes[0];
  98134. result.x = shape.halfExtents.x * 2;
  98135. result.y = shape.halfExtents.y * 2;
  98136. result.z = shape.halfExtents.z * 2;
  98137. };
  98138. CannonJSPlugin.prototype.dispose = function () {
  98139. };
  98140. CannonJSPlugin.prototype._extendNamespace = function () {
  98141. //this will force cannon to execute at least one step when using interpolation
  98142. var step_tmp1 = new this.BJSCANNON.Vec3();
  98143. var Engine = this.BJSCANNON;
  98144. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  98145. maxSubSteps = maxSubSteps || 10;
  98146. timeSinceLastCalled = timeSinceLastCalled || 0;
  98147. if (timeSinceLastCalled === 0) {
  98148. this.internalStep(dt);
  98149. this.time += dt;
  98150. }
  98151. else {
  98152. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  98153. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  98154. var t0 = performance.now();
  98155. for (var i = 0; i !== internalSteps; i++) {
  98156. this.internalStep(dt);
  98157. if (performance.now() - t0 > dt * 1000) {
  98158. break;
  98159. }
  98160. }
  98161. this.time += timeSinceLastCalled;
  98162. var h = this.time % dt;
  98163. var h_div_dt = h / dt;
  98164. var interpvelo = step_tmp1;
  98165. var bodies = this.bodies;
  98166. for (var j = 0; j !== bodies.length; j++) {
  98167. var b = bodies[j];
  98168. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  98169. b.position.vsub(b.previousPosition, interpvelo);
  98170. interpvelo.scale(h_div_dt, interpvelo);
  98171. b.position.vadd(interpvelo, b.interpolatedPosition);
  98172. }
  98173. else {
  98174. b.interpolatedPosition.copy(b.position);
  98175. b.interpolatedQuaternion.copy(b.quaternion);
  98176. }
  98177. }
  98178. }
  98179. };
  98180. };
  98181. return CannonJSPlugin;
  98182. }());
  98183. BABYLON.CannonJSPlugin = CannonJSPlugin;
  98184. })(BABYLON || (BABYLON = {}));
  98185. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  98186. var BABYLON;
  98187. (function (BABYLON) {
  98188. /** @hidden */
  98189. var OimoJSPlugin = /** @class */ (function () {
  98190. function OimoJSPlugin(iterations) {
  98191. this.name = "OimoJSPlugin";
  98192. this._tmpImpostorsArray = [];
  98193. this._tmpPositionVector = BABYLON.Vector3.Zero();
  98194. this.BJSOIMO = OIMO;
  98195. this.world = new this.BJSOIMO.World({
  98196. iterations: iterations
  98197. });
  98198. this.world.clear();
  98199. }
  98200. OimoJSPlugin.prototype.setGravity = function (gravity) {
  98201. this.world.gravity.copy(gravity);
  98202. };
  98203. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  98204. this.world.timeStep = timeStep;
  98205. };
  98206. OimoJSPlugin.prototype.getTimeStep = function () {
  98207. return this.world.timeStep;
  98208. };
  98209. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  98210. var _this = this;
  98211. impostors.forEach(function (impostor) {
  98212. impostor.beforeStep();
  98213. });
  98214. this.world.step();
  98215. impostors.forEach(function (impostor) {
  98216. impostor.afterStep();
  98217. //update the ordered impostors array
  98218. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  98219. });
  98220. //check for collisions
  98221. var contact = this.world.contacts;
  98222. while (contact !== null) {
  98223. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  98224. contact = contact.next;
  98225. continue;
  98226. }
  98227. //is this body colliding with any other? get the impostor
  98228. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  98229. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  98230. if (!mainImpostor || !collidingImpostor) {
  98231. contact = contact.next;
  98232. continue;
  98233. }
  98234. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  98235. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  98236. contact = contact.next;
  98237. }
  98238. };
  98239. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98240. var mass = impostor.physicsBody.mass;
  98241. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  98242. };
  98243. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98244. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  98245. this.applyImpulse(impostor, force, contactPoint);
  98246. };
  98247. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98248. var _this = this;
  98249. //parent-child relationship. Does this impostor has a parent impostor?
  98250. if (impostor.parent) {
  98251. if (impostor.physicsBody) {
  98252. this.removePhysicsBody(impostor);
  98253. //TODO is that needed?
  98254. impostor.forceUpdate();
  98255. }
  98256. return;
  98257. }
  98258. if (impostor.isBodyInitRequired()) {
  98259. var bodyConfig = {
  98260. name: impostor.uniqueId,
  98261. //Oimo must have mass, also for static objects.
  98262. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  98263. size: [],
  98264. type: [],
  98265. pos: [],
  98266. posShape: [],
  98267. rot: [],
  98268. rotShape: [],
  98269. move: impostor.getParam("mass") !== 0,
  98270. density: impostor.getParam("mass"),
  98271. friction: impostor.getParam("friction"),
  98272. restitution: impostor.getParam("restitution"),
  98273. //Supporting older versions of Oimo
  98274. world: this.world
  98275. };
  98276. var impostors = [impostor];
  98277. var addToArray = function (parent) {
  98278. if (!parent.getChildMeshes) {
  98279. return;
  98280. }
  98281. parent.getChildMeshes().forEach(function (m) {
  98282. if (m.physicsImpostor) {
  98283. impostors.push(m.physicsImpostor);
  98284. //m.physicsImpostor._init();
  98285. }
  98286. });
  98287. };
  98288. addToArray(impostor.object);
  98289. var checkWithEpsilon_1 = function (value) {
  98290. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  98291. };
  98292. var globalQuaternion_1 = new BABYLON.Quaternion();
  98293. impostors.forEach(function (i) {
  98294. if (!i.object.rotationQuaternion) {
  98295. return;
  98296. }
  98297. //get the correct bounding box
  98298. var oldQuaternion = i.object.rotationQuaternion;
  98299. globalQuaternion_1 = oldQuaternion.clone();
  98300. var rot = oldQuaternion.toEulerAngles();
  98301. var extendSize = i.getObjectExtendSize();
  98302. var radToDeg = 57.295779513082320876;
  98303. if (i === impostor) {
  98304. var center = impostor.getObjectCenter();
  98305. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  98306. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  98307. //Can also use Array.prototype.push.apply
  98308. bodyConfig.pos.push(center.x);
  98309. bodyConfig.pos.push(center.y);
  98310. bodyConfig.pos.push(center.z);
  98311. bodyConfig.posShape.push(0, 0, 0);
  98312. //tmp solution
  98313. bodyConfig.rot.push(0);
  98314. bodyConfig.rot.push(0);
  98315. bodyConfig.rot.push(0);
  98316. bodyConfig.rotShape.push(0, 0, 0);
  98317. }
  98318. else {
  98319. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  98320. bodyConfig.posShape.push(localPosition.x);
  98321. bodyConfig.posShape.push(localPosition.y);
  98322. bodyConfig.posShape.push(localPosition.z);
  98323. bodyConfig.pos.push(0, 0, 0);
  98324. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  98325. bodyConfig.rot.push(0);
  98326. bodyConfig.rot.push(0);
  98327. bodyConfig.rot.push(0);
  98328. bodyConfig.rotShape.push(rot.x * radToDeg);
  98329. bodyConfig.rotShape.push(rot.y * radToDeg);
  98330. bodyConfig.rotShape.push(rot.z * radToDeg);
  98331. }
  98332. // register mesh
  98333. switch (i.type) {
  98334. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98335. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  98336. case BABYLON.PhysicsImpostor.SphereImpostor:
  98337. var radiusX = extendSize.x;
  98338. var radiusY = extendSize.y;
  98339. var radiusZ = extendSize.z;
  98340. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  98341. bodyConfig.type.push('sphere');
  98342. //due to the way oimo works with compounds, add 3 times
  98343. bodyConfig.size.push(size);
  98344. bodyConfig.size.push(size);
  98345. bodyConfig.size.push(size);
  98346. break;
  98347. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98348. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  98349. var sizeY = checkWithEpsilon_1(extendSize.y);
  98350. bodyConfig.type.push('cylinder');
  98351. bodyConfig.size.push(sizeX);
  98352. bodyConfig.size.push(sizeY);
  98353. //due to the way oimo works with compounds, add one more value.
  98354. bodyConfig.size.push(sizeY);
  98355. break;
  98356. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98357. case BABYLON.PhysicsImpostor.BoxImpostor:
  98358. default:
  98359. var sizeX = checkWithEpsilon_1(extendSize.x);
  98360. var sizeY = checkWithEpsilon_1(extendSize.y);
  98361. var sizeZ = checkWithEpsilon_1(extendSize.z);
  98362. bodyConfig.type.push('box');
  98363. //if (i === impostor) {
  98364. bodyConfig.size.push(sizeX);
  98365. bodyConfig.size.push(sizeY);
  98366. bodyConfig.size.push(sizeZ);
  98367. //} else {
  98368. // bodyConfig.size.push(0,0,0);
  98369. //}
  98370. break;
  98371. }
  98372. //actually not needed, but hey...
  98373. i.object.rotationQuaternion = oldQuaternion;
  98374. });
  98375. impostor.physicsBody = this.world.add(bodyConfig);
  98376. // set the quaternion, ignoring the previously defined (euler) rotation
  98377. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  98378. // update with delta 0, so the body will reveive the new rotation.
  98379. impostor.physicsBody.updatePosition(0);
  98380. }
  98381. else {
  98382. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  98383. }
  98384. impostor.setDeltaPosition(this._tmpPositionVector);
  98385. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  98386. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  98387. };
  98388. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98389. //impostor.physicsBody.dispose();
  98390. //Same as : (older oimo versions)
  98391. this.world.removeRigidBody(impostor.physicsBody);
  98392. };
  98393. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98394. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98395. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98396. if (!mainBody || !connectedBody) {
  98397. return;
  98398. }
  98399. var jointData = impostorJoint.joint.jointData;
  98400. var options = jointData.nativeParams || {};
  98401. var type;
  98402. var nativeJointData = {
  98403. body1: mainBody,
  98404. body2: connectedBody,
  98405. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  98406. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  98407. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  98408. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  98409. min: options.min,
  98410. max: options.max,
  98411. collision: options.collision || jointData.collision,
  98412. spring: options.spring,
  98413. //supporting older version of Oimo
  98414. world: this.world
  98415. };
  98416. switch (impostorJoint.joint.type) {
  98417. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98418. type = "jointBall";
  98419. break;
  98420. case BABYLON.PhysicsJoint.SpringJoint:
  98421. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  98422. var springData = jointData;
  98423. nativeJointData.min = springData.length || nativeJointData.min;
  98424. //Max should also be set, just make sure it is at least min
  98425. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  98426. case BABYLON.PhysicsJoint.DistanceJoint:
  98427. type = "jointDistance";
  98428. nativeJointData.max = jointData.maxDistance;
  98429. break;
  98430. case BABYLON.PhysicsJoint.PrismaticJoint:
  98431. type = "jointPrisme";
  98432. break;
  98433. case BABYLON.PhysicsJoint.SliderJoint:
  98434. type = "jointSlide";
  98435. break;
  98436. case BABYLON.PhysicsJoint.WheelJoint:
  98437. type = "jointWheel";
  98438. break;
  98439. case BABYLON.PhysicsJoint.HingeJoint:
  98440. default:
  98441. type = "jointHinge";
  98442. break;
  98443. }
  98444. nativeJointData.type = type;
  98445. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  98446. };
  98447. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98448. //Bug in Oimo prevents us from disposing a joint in the playground
  98449. //joint.joint.physicsJoint.dispose();
  98450. //So we will bruteforce it!
  98451. try {
  98452. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  98453. }
  98454. catch (e) {
  98455. BABYLON.Tools.Warn(e);
  98456. }
  98457. };
  98458. OimoJSPlugin.prototype.isSupported = function () {
  98459. return this.BJSOIMO !== undefined;
  98460. };
  98461. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98462. if (!impostor.physicsBody.sleeping) {
  98463. //TODO check that
  98464. /*if (impostor.physicsBody.shapes.next) {
  98465. var parentShape = this._getLastShape(impostor.physicsBody);
  98466. impostor.object.position.copyFrom(parentShape.position);
  98467. console.log(parentShape.position);
  98468. } else {*/
  98469. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  98470. //}
  98471. if (impostor.object.rotationQuaternion) {
  98472. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  98473. }
  98474. }
  98475. };
  98476. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98477. var body = impostor.physicsBody;
  98478. body.position.copy(newPosition);
  98479. body.orientation.copy(newRotation);
  98480. body.syncShapes();
  98481. body.awake();
  98482. };
  98483. /*private _getLastShape(body: any): any {
  98484. var lastShape = body.shapes;
  98485. while (lastShape.next) {
  98486. lastShape = lastShape.next;
  98487. }
  98488. return lastShape;
  98489. }*/
  98490. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98491. impostor.physicsBody.linearVelocity.copy(velocity);
  98492. };
  98493. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98494. impostor.physicsBody.angularVelocity.copy(velocity);
  98495. };
  98496. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98497. var v = impostor.physicsBody.linearVelocity;
  98498. if (!v) {
  98499. return null;
  98500. }
  98501. return new BABYLON.Vector3(v.x, v.y, v.z);
  98502. };
  98503. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98504. var v = impostor.physicsBody.angularVelocity;
  98505. if (!v) {
  98506. return null;
  98507. }
  98508. return new BABYLON.Vector3(v.x, v.y, v.z);
  98509. };
  98510. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98511. var staticBody = mass === 0;
  98512. //this will actually set the body's density and not its mass.
  98513. //But this is how oimo treats the mass variable.
  98514. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  98515. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  98516. };
  98517. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  98518. return impostor.physicsBody.shapes.density;
  98519. };
  98520. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  98521. return impostor.physicsBody.shapes.friction;
  98522. };
  98523. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98524. impostor.physicsBody.shapes.friction = friction;
  98525. };
  98526. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98527. return impostor.physicsBody.shapes.restitution;
  98528. };
  98529. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98530. impostor.physicsBody.shapes.restitution = restitution;
  98531. };
  98532. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  98533. impostor.physicsBody.sleep();
  98534. };
  98535. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  98536. impostor.physicsBody.awake();
  98537. };
  98538. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98539. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  98540. if (minDistance !== void 0) {
  98541. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  98542. }
  98543. };
  98544. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98545. //TODO separate rotational and transational motors.
  98546. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98547. if (motor) {
  98548. motor.setMotor(speed, maxForce);
  98549. }
  98550. };
  98551. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  98552. //TODO separate rotational and transational motors.
  98553. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98554. if (motor) {
  98555. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  98556. }
  98557. };
  98558. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98559. var body = impostor.physicsBody;
  98560. mesh.position.x = body.position.x;
  98561. mesh.position.y = body.position.y;
  98562. mesh.position.z = body.position.z;
  98563. if (mesh.rotationQuaternion) {
  98564. mesh.rotationQuaternion.x = body.orientation.x;
  98565. mesh.rotationQuaternion.y = body.orientation.y;
  98566. mesh.rotationQuaternion.z = body.orientation.z;
  98567. mesh.rotationQuaternion.w = body.orientation.s;
  98568. }
  98569. };
  98570. OimoJSPlugin.prototype.getRadius = function (impostor) {
  98571. return impostor.physicsBody.shapes.radius;
  98572. };
  98573. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98574. var shape = impostor.physicsBody.shapes;
  98575. result.x = shape.halfWidth * 2;
  98576. result.y = shape.halfHeight * 2;
  98577. result.z = shape.halfDepth * 2;
  98578. };
  98579. OimoJSPlugin.prototype.dispose = function () {
  98580. this.world.clear();
  98581. };
  98582. return OimoJSPlugin;
  98583. }());
  98584. BABYLON.OimoJSPlugin = OimoJSPlugin;
  98585. })(BABYLON || (BABYLON = {}));
  98586. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  98587. var BABYLON;
  98588. (function (BABYLON) {
  98589. /**
  98590. * Gets the current physics engine
  98591. * @returns a IPhysicsEngine or null if none attached
  98592. */
  98593. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  98594. return this._physicsEngine;
  98595. };
  98596. /**
  98597. * Enables physics to the current scene
  98598. * @param gravity defines the scene's gravity for the physics engine
  98599. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  98600. * @return a boolean indicating if the physics engine was initialized
  98601. */
  98602. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  98603. if (gravity === void 0) { gravity = null; }
  98604. if (this._physicsEngine) {
  98605. return true;
  98606. }
  98607. // Register the component to the scene
  98608. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  98609. if (!component) {
  98610. component = new PhysicsEngineSceneComponent(this);
  98611. this._addComponent(component);
  98612. }
  98613. try {
  98614. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  98615. return true;
  98616. }
  98617. catch (e) {
  98618. BABYLON.Tools.Error(e.message);
  98619. return false;
  98620. }
  98621. };
  98622. /**
  98623. * Disables and disposes the physics engine associated with the scene
  98624. */
  98625. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  98626. if (!this._physicsEngine) {
  98627. return;
  98628. }
  98629. this._physicsEngine.dispose();
  98630. this._physicsEngine = null;
  98631. };
  98632. /**
  98633. * Gets a boolean indicating if there is an active physics engine
  98634. * @returns a boolean indicating if there is an active physics engine
  98635. */
  98636. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  98637. return this._physicsEngine !== undefined;
  98638. };
  98639. /**
  98640. * Deletes a physics compound impostor
  98641. * @param compound defines the compound to delete
  98642. */
  98643. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  98644. var mesh = compound.parts[0].mesh;
  98645. if (mesh.physicsImpostor) {
  98646. mesh.physicsImpostor.dispose( /*true*/);
  98647. mesh.physicsImpostor = null;
  98648. }
  98649. };
  98650. /** @hidden */
  98651. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  98652. if (this._physicsEngine) {
  98653. this.onBeforePhysicsObservable.notifyObservers(this);
  98654. this._physicsEngine._step(step / 1000);
  98655. this.onAfterPhysicsObservable.notifyObservers(this);
  98656. }
  98657. };
  98658. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  98659. get: function () {
  98660. return this._physicsImpostor;
  98661. },
  98662. set: function (value) {
  98663. var _this = this;
  98664. if (this._physicsImpostor === value) {
  98665. return;
  98666. }
  98667. if (this._disposePhysicsObserver) {
  98668. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  98669. }
  98670. this._physicsImpostor = value;
  98671. if (value) {
  98672. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  98673. // Physics
  98674. if (_this.physicsImpostor) {
  98675. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  98676. _this.physicsImpostor = null;
  98677. }
  98678. });
  98679. }
  98680. },
  98681. enumerable: true,
  98682. configurable: true
  98683. });
  98684. /**
  98685. * Gets the current physics impostor
  98686. * @see http://doc.babylonjs.com/features/physics_engine
  98687. * @returns a physics impostor or null
  98688. */
  98689. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  98690. return this.physicsImpostor;
  98691. };
  98692. /**
  98693. * Apply a physic impulse to the mesh
  98694. * @param force defines the force to apply
  98695. * @param contactPoint defines where to apply the force
  98696. * @returns the current mesh
  98697. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  98698. */
  98699. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  98700. if (!this.physicsImpostor) {
  98701. return this;
  98702. }
  98703. this.physicsImpostor.applyImpulse(force, contactPoint);
  98704. return this;
  98705. };
  98706. /**
  98707. * Creates a physic joint between two meshes
  98708. * @param otherMesh defines the other mesh to use
  98709. * @param pivot1 defines the pivot to use on this mesh
  98710. * @param pivot2 defines the pivot to use on the other mesh
  98711. * @param options defines additional options (can be plugin dependent)
  98712. * @returns the current mesh
  98713. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  98714. */
  98715. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  98716. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  98717. return this;
  98718. }
  98719. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  98720. mainPivot: pivot1,
  98721. connectedPivot: pivot2,
  98722. nativeParams: options
  98723. });
  98724. return this;
  98725. };
  98726. /**
  98727. * Defines the physics engine scene component responsible to manage a physics engine
  98728. */
  98729. var PhysicsEngineSceneComponent = /** @class */ (function () {
  98730. /**
  98731. * Creates a new instance of the component for the given scene
  98732. * @param scene Defines the scene to register the component in
  98733. */
  98734. function PhysicsEngineSceneComponent(scene) {
  98735. var _this = this;
  98736. /**
  98737. * The component name helpful to identify the component in the list of scene components.
  98738. */
  98739. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  98740. this.scene = scene;
  98741. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  98742. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  98743. // Replace the function used to get the deterministic frame time
  98744. this.scene.getDeterministicFrameTime = function () {
  98745. if (_this.scene._physicsEngine) {
  98746. return _this.scene._physicsEngine.getTimeStep() * 1000;
  98747. }
  98748. return 1000.0 / 60.0;
  98749. };
  98750. }
  98751. /**
  98752. * Registers the component in a given scene
  98753. */
  98754. PhysicsEngineSceneComponent.prototype.register = function () {
  98755. };
  98756. /**
  98757. * Rebuilds the elements related to this component in case of
  98758. * context lost for instance.
  98759. */
  98760. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  98761. // Nothing to do for this component
  98762. };
  98763. /**
  98764. * Disposes the component and the associated ressources
  98765. */
  98766. PhysicsEngineSceneComponent.prototype.dispose = function () {
  98767. this.scene.onBeforePhysicsObservable.clear();
  98768. this.scene.onAfterPhysicsObservable.clear();
  98769. if (this.scene._physicsEngine) {
  98770. this.scene.disablePhysicsEngine();
  98771. }
  98772. };
  98773. return PhysicsEngineSceneComponent;
  98774. }());
  98775. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  98776. })(BABYLON || (BABYLON = {}));
  98777. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  98778. var BABYLON;
  98779. (function (BABYLON) {
  98780. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  98781. // All values and structures referenced from:
  98782. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  98783. var DDS_MAGIC = 0x20534444;
  98784. var
  98785. //DDSD_CAPS = 0x1,
  98786. //DDSD_HEIGHT = 0x2,
  98787. //DDSD_WIDTH = 0x4,
  98788. //DDSD_PITCH = 0x8,
  98789. //DDSD_PIXELFORMAT = 0x1000,
  98790. DDSD_MIPMAPCOUNT = 0x20000;
  98791. //DDSD_LINEARSIZE = 0x80000,
  98792. //DDSD_DEPTH = 0x800000;
  98793. // var DDSCAPS_COMPLEX = 0x8,
  98794. // DDSCAPS_MIPMAP = 0x400000,
  98795. // DDSCAPS_TEXTURE = 0x1000;
  98796. var DDSCAPS2_CUBEMAP = 0x200;
  98797. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  98798. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  98799. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  98800. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  98801. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  98802. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  98803. // DDSCAPS2_VOLUME = 0x200000;
  98804. var
  98805. //DDPF_ALPHAPIXELS = 0x1,
  98806. //DDPF_ALPHA = 0x2,
  98807. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  98808. //DDPF_YUV = 0x200,
  98809. DDPF_LUMINANCE = 0x20000;
  98810. function FourCCToInt32(value) {
  98811. return value.charCodeAt(0) +
  98812. (value.charCodeAt(1) << 8) +
  98813. (value.charCodeAt(2) << 16) +
  98814. (value.charCodeAt(3) << 24);
  98815. }
  98816. function Int32ToFourCC(value) {
  98817. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  98818. }
  98819. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  98820. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  98821. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  98822. var FOURCC_DX10 = FourCCToInt32("DX10");
  98823. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  98824. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  98825. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  98826. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  98827. var headerLengthInt = 31; // The header length in 32 bit ints
  98828. // Offsets into the header array
  98829. var off_magic = 0;
  98830. var off_size = 1;
  98831. var off_flags = 2;
  98832. var off_height = 3;
  98833. var off_width = 4;
  98834. var off_mipmapCount = 7;
  98835. var off_pfFlags = 20;
  98836. var off_pfFourCC = 21;
  98837. var off_RGBbpp = 22;
  98838. var off_RMask = 23;
  98839. var off_GMask = 24;
  98840. var off_BMask = 25;
  98841. var off_AMask = 26;
  98842. // var off_caps1 = 27;
  98843. var off_caps2 = 28;
  98844. // var off_caps3 = 29;
  98845. // var off_caps4 = 30;
  98846. var off_dxgiFormat = 32;
  98847. /**
  98848. * Class used to provide DDS decompression tools
  98849. */
  98850. var DDSTools = /** @class */ (function () {
  98851. function DDSTools() {
  98852. }
  98853. /**
  98854. * Gets DDS information from an array buffer
  98855. * @param arrayBuffer defines the array buffer to read data from
  98856. * @returns the DDS information
  98857. */
  98858. DDSTools.GetDDSInfo = function (arrayBuffer) {
  98859. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  98860. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  98861. var mipmapCount = 1;
  98862. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  98863. mipmapCount = Math.max(1, header[off_mipmapCount]);
  98864. }
  98865. var fourCC = header[off_pfFourCC];
  98866. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  98867. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98868. switch (fourCC) {
  98869. case FOURCC_D3DFMT_R16G16B16A16F:
  98870. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98871. break;
  98872. case FOURCC_D3DFMT_R32G32B32A32F:
  98873. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98874. break;
  98875. case FOURCC_DX10:
  98876. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  98877. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98878. break;
  98879. }
  98880. }
  98881. return {
  98882. width: header[off_width],
  98883. height: header[off_height],
  98884. mipmapCount: mipmapCount,
  98885. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  98886. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  98887. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  98888. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  98889. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  98890. dxgiFormat: dxgiFormat,
  98891. textureType: textureType
  98892. };
  98893. };
  98894. DDSTools._ToHalfFloat = function (value) {
  98895. if (!DDSTools._FloatView) {
  98896. DDSTools._FloatView = new Float32Array(1);
  98897. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  98898. }
  98899. DDSTools._FloatView[0] = value;
  98900. var x = DDSTools._Int32View[0];
  98901. var bits = (x >> 16) & 0x8000; /* Get the sign */
  98902. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  98903. var e = (x >> 23) & 0xff; /* Using int is faster here */
  98904. /* If zero, or denormal, or exponent underflows too much for a denormal
  98905. * half, return signed zero. */
  98906. if (e < 103) {
  98907. return bits;
  98908. }
  98909. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  98910. if (e > 142) {
  98911. bits |= 0x7c00;
  98912. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  98913. * not Inf, so make sure we set one mantissa bit too. */
  98914. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  98915. return bits;
  98916. }
  98917. /* If exponent underflows but not too much, return a denormal */
  98918. if (e < 113) {
  98919. m |= 0x0800;
  98920. /* Extra rounding may overflow and set mantissa to 0 and exponent
  98921. * to 1, which is OK. */
  98922. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  98923. return bits;
  98924. }
  98925. bits |= ((e - 112) << 10) | (m >> 1);
  98926. bits += m & 1;
  98927. return bits;
  98928. };
  98929. DDSTools._FromHalfFloat = function (value) {
  98930. var s = (value & 0x8000) >> 15;
  98931. var e = (value & 0x7C00) >> 10;
  98932. var f = value & 0x03FF;
  98933. if (e === 0) {
  98934. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  98935. }
  98936. else if (e == 0x1F) {
  98937. return f ? NaN : ((s ? -1 : 1) * Infinity);
  98938. }
  98939. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  98940. };
  98941. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98942. var destArray = new Float32Array(dataLength);
  98943. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98944. var index = 0;
  98945. for (var y = 0; y < height; y++) {
  98946. for (var x = 0; x < width; x++) {
  98947. var srcPos = (x + y * width) * 4;
  98948. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  98949. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  98950. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  98951. if (DDSTools.StoreLODInAlphaChannel) {
  98952. destArray[index + 3] = lod;
  98953. }
  98954. else {
  98955. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  98956. }
  98957. index += 4;
  98958. }
  98959. }
  98960. return destArray;
  98961. };
  98962. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98963. if (DDSTools.StoreLODInAlphaChannel) {
  98964. var destArray = new Uint16Array(dataLength);
  98965. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98966. var index = 0;
  98967. for (var y = 0; y < height; y++) {
  98968. for (var x = 0; x < width; x++) {
  98969. var srcPos = (x + y * width) * 4;
  98970. destArray[index] = srcData[srcPos];
  98971. destArray[index + 1] = srcData[srcPos + 1];
  98972. destArray[index + 2] = srcData[srcPos + 2];
  98973. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  98974. index += 4;
  98975. }
  98976. }
  98977. return destArray;
  98978. }
  98979. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  98980. };
  98981. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98982. if (DDSTools.StoreLODInAlphaChannel) {
  98983. var destArray = new Float32Array(dataLength);
  98984. var srcData = new Float32Array(arrayBuffer, dataOffset);
  98985. var index = 0;
  98986. for (var y = 0; y < height; y++) {
  98987. for (var x = 0; x < width; x++) {
  98988. var srcPos = (x + y * width) * 4;
  98989. destArray[index] = srcData[srcPos];
  98990. destArray[index + 1] = srcData[srcPos + 1];
  98991. destArray[index + 2] = srcData[srcPos + 2];
  98992. destArray[index + 3] = lod;
  98993. index += 4;
  98994. }
  98995. }
  98996. return destArray;
  98997. }
  98998. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  98999. };
  99000. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99001. var destArray = new Uint8Array(dataLength);
  99002. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99003. var index = 0;
  99004. for (var y = 0; y < height; y++) {
  99005. for (var x = 0; x < width; x++) {
  99006. var srcPos = (x + y * width) * 4;
  99007. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  99008. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  99009. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  99010. if (DDSTools.StoreLODInAlphaChannel) {
  99011. destArray[index + 3] = lod;
  99012. }
  99013. else {
  99014. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  99015. }
  99016. index += 4;
  99017. }
  99018. }
  99019. return destArray;
  99020. };
  99021. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99022. var destArray = new Uint8Array(dataLength);
  99023. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99024. var index = 0;
  99025. for (var y = 0; y < height; y++) {
  99026. for (var x = 0; x < width; x++) {
  99027. var srcPos = (x + y * width) * 4;
  99028. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  99029. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  99030. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  99031. if (DDSTools.StoreLODInAlphaChannel) {
  99032. destArray[index + 3] = lod;
  99033. }
  99034. else {
  99035. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  99036. }
  99037. index += 4;
  99038. }
  99039. }
  99040. return destArray;
  99041. };
  99042. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  99043. var byteArray = new Uint8Array(dataLength);
  99044. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99045. var index = 0;
  99046. for (var y = 0; y < height; y++) {
  99047. for (var x = 0; x < width; x++) {
  99048. var srcPos = (x + y * width) * 4;
  99049. byteArray[index] = srcData[srcPos + rOffset];
  99050. byteArray[index + 1] = srcData[srcPos + gOffset];
  99051. byteArray[index + 2] = srcData[srcPos + bOffset];
  99052. byteArray[index + 3] = srcData[srcPos + aOffset];
  99053. index += 4;
  99054. }
  99055. }
  99056. return byteArray;
  99057. };
  99058. DDSTools._ExtractLongWordOrder = function (value) {
  99059. if (value === 0 || value === 255 || value === -16777216) {
  99060. return 0;
  99061. }
  99062. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  99063. };
  99064. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  99065. var byteArray = new Uint8Array(dataLength);
  99066. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99067. var index = 0;
  99068. for (var y = 0; y < height; y++) {
  99069. for (var x = 0; x < width; x++) {
  99070. var srcPos = (x + y * width) * 3;
  99071. byteArray[index] = srcData[srcPos + rOffset];
  99072. byteArray[index + 1] = srcData[srcPos + gOffset];
  99073. byteArray[index + 2] = srcData[srcPos + bOffset];
  99074. index += 3;
  99075. }
  99076. }
  99077. return byteArray;
  99078. };
  99079. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  99080. var byteArray = new Uint8Array(dataLength);
  99081. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99082. var index = 0;
  99083. for (var y = 0; y < height; y++) {
  99084. for (var x = 0; x < width; x++) {
  99085. var srcPos = (x + y * width);
  99086. byteArray[index] = srcData[srcPos];
  99087. index++;
  99088. }
  99089. }
  99090. return byteArray;
  99091. };
  99092. /**
  99093. * Uploads DDS Levels to a Babylon Texture
  99094. * @hidden
  99095. */
  99096. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  99097. if (lodIndex === void 0) { lodIndex = -1; }
  99098. var sphericalPolynomialFaces = null;
  99099. if (info.sphericalPolynomial) {
  99100. sphericalPolynomialFaces = new Array();
  99101. }
  99102. var ext = engine.getCaps().s3tc;
  99103. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99104. var fourCC, width, height, dataLength = 0, dataOffset;
  99105. var byteArray, mipmapCount, mip;
  99106. var internalCompressedFormat = 0;
  99107. var blockBytes = 1;
  99108. if (header[off_magic] !== DDS_MAGIC) {
  99109. BABYLON.Tools.Error("Invalid magic number in DDS header");
  99110. return;
  99111. }
  99112. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  99113. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  99114. return;
  99115. }
  99116. if (info.isCompressed && !ext) {
  99117. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  99118. return;
  99119. }
  99120. var bpp = header[off_RGBbpp];
  99121. dataOffset = header[off_size] + 4;
  99122. var computeFormats = false;
  99123. if (info.isFourCC) {
  99124. fourCC = header[off_pfFourCC];
  99125. switch (fourCC) {
  99126. case FOURCC_DXT1:
  99127. blockBytes = 8;
  99128. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  99129. break;
  99130. case FOURCC_DXT3:
  99131. blockBytes = 16;
  99132. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  99133. break;
  99134. case FOURCC_DXT5:
  99135. blockBytes = 16;
  99136. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  99137. break;
  99138. case FOURCC_D3DFMT_R16G16B16A16F:
  99139. computeFormats = true;
  99140. break;
  99141. case FOURCC_D3DFMT_R32G32B32A32F:
  99142. computeFormats = true;
  99143. break;
  99144. case FOURCC_DX10:
  99145. // There is an additionnal header so dataOffset need to be changed
  99146. dataOffset += 5 * 4; // 5 uints
  99147. var supported = false;
  99148. switch (info.dxgiFormat) {
  99149. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  99150. computeFormats = true;
  99151. supported = true;
  99152. break;
  99153. case DXGI_FORMAT_B8G8R8X8_UNORM:
  99154. info.isRGB = true;
  99155. info.isFourCC = false;
  99156. bpp = 32;
  99157. supported = true;
  99158. break;
  99159. }
  99160. if (supported) {
  99161. break;
  99162. }
  99163. default:
  99164. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  99165. return;
  99166. }
  99167. }
  99168. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  99169. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  99170. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  99171. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  99172. if (computeFormats) {
  99173. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  99174. }
  99175. mipmapCount = 1;
  99176. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  99177. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99178. }
  99179. for (var face = 0; face < faces; face++) {
  99180. width = header[off_width];
  99181. height = header[off_height];
  99182. for (mip = 0; mip < mipmapCount; ++mip) {
  99183. if (lodIndex === -1 || lodIndex === mip) {
  99184. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  99185. var i = (lodIndex === -1) ? mip : 0;
  99186. if (!info.isCompressed && info.isFourCC) {
  99187. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99188. dataLength = width * height * 4;
  99189. var floatArray = null;
  99190. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  99191. if (bpp === 128) {
  99192. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99193. if (sphericalPolynomialFaces && i == 0) {
  99194. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99195. }
  99196. }
  99197. else if (bpp === 64) {
  99198. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99199. if (sphericalPolynomialFaces && i == 0) {
  99200. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99201. }
  99202. }
  99203. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99204. }
  99205. else {
  99206. if (bpp === 128) {
  99207. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99208. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99209. if (sphericalPolynomialFaces && i == 0) {
  99210. sphericalPolynomialFaces.push(floatArray);
  99211. }
  99212. }
  99213. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  99214. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99215. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99216. if (sphericalPolynomialFaces && i == 0) {
  99217. sphericalPolynomialFaces.push(floatArray);
  99218. }
  99219. }
  99220. else { // 64
  99221. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99222. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99223. if (sphericalPolynomialFaces && i == 0) {
  99224. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99225. }
  99226. }
  99227. }
  99228. if (floatArray) {
  99229. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  99230. }
  99231. }
  99232. else if (info.isRGB) {
  99233. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99234. if (bpp === 24) {
  99235. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  99236. dataLength = width * height * 3;
  99237. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  99238. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99239. }
  99240. else { // 32
  99241. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99242. dataLength = width * height * 4;
  99243. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  99244. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99245. }
  99246. }
  99247. else if (info.isLuminance) {
  99248. var unpackAlignment = engine._getUnpackAlignement();
  99249. var unpaddedRowSize = width;
  99250. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  99251. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  99252. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  99253. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  99254. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99255. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99256. }
  99257. else {
  99258. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  99259. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  99260. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99261. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  99262. }
  99263. }
  99264. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  99265. width *= 0.5;
  99266. height *= 0.5;
  99267. width = Math.max(1.0, width);
  99268. height = Math.max(1.0, height);
  99269. }
  99270. if (currentFace !== undefined) {
  99271. // Loading a single face
  99272. break;
  99273. }
  99274. }
  99275. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  99276. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  99277. size: header[off_width],
  99278. right: sphericalPolynomialFaces[0],
  99279. left: sphericalPolynomialFaces[1],
  99280. up: sphericalPolynomialFaces[2],
  99281. down: sphericalPolynomialFaces[3],
  99282. front: sphericalPolynomialFaces[4],
  99283. back: sphericalPolynomialFaces[5],
  99284. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  99285. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  99286. gammaSpace: false,
  99287. });
  99288. }
  99289. else {
  99290. info.sphericalPolynomial = undefined;
  99291. }
  99292. };
  99293. /**
  99294. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  99295. */
  99296. DDSTools.StoreLODInAlphaChannel = false;
  99297. return DDSTools;
  99298. }());
  99299. BABYLON.DDSTools = DDSTools;
  99300. })(BABYLON || (BABYLON = {}));
  99301. //# sourceMappingURL=babylon.dds.js.map
  99302. var BABYLON;
  99303. (function (BABYLON) {
  99304. /**
  99305. * Implementation of the DDS Texture Loader.
  99306. */
  99307. var DDSTextureLoader = /** @class */ (function () {
  99308. function DDSTextureLoader() {
  99309. /**
  99310. * Defines wether the loader supports cascade loading the different faces.
  99311. */
  99312. this.supportCascades = true;
  99313. }
  99314. /**
  99315. * This returns if the loader support the current file information.
  99316. * @param extension defines the file extension of the file being loaded
  99317. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99318. * @param fallback defines the fallback internal texture if any
  99319. * @param isBase64 defines whether the texture is encoded as a base64
  99320. * @param isBuffer defines whether the texture data are stored as a buffer
  99321. * @returns true if the loader can load the specified file
  99322. */
  99323. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99324. return extension.indexOf(".dds") === 0;
  99325. };
  99326. /**
  99327. * Transform the url before loading if required.
  99328. * @param rootUrl the url of the texture
  99329. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99330. * @returns the transformed texture
  99331. */
  99332. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99333. return rootUrl;
  99334. };
  99335. /**
  99336. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99337. * @param rootUrl the url of the texture
  99338. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99339. * @returns the fallback texture
  99340. */
  99341. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99342. return null;
  99343. };
  99344. /**
  99345. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99346. * @param data contains the texture data
  99347. * @param texture defines the BabylonJS internal texture
  99348. * @param createPolynomials will be true if polynomials have been requested
  99349. * @param onLoad defines the callback to trigger once the texture is ready
  99350. * @param onError defines the callback to trigger in case of error
  99351. */
  99352. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  99353. var engine = texture.getEngine();
  99354. var info;
  99355. var loadMipmap = false;
  99356. if (Array.isArray(imgs)) {
  99357. for (var index = 0; index < imgs.length; index++) {
  99358. var data_1 = imgs[index];
  99359. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  99360. texture.width = info.width;
  99361. texture.height = info.height;
  99362. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99363. engine._unpackFlipY(info.isCompressed);
  99364. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  99365. if (!info.isFourCC && info.mipmapCount === 1) {
  99366. engine.generateMipMapsForCubemap(texture);
  99367. }
  99368. }
  99369. }
  99370. else {
  99371. var data = imgs;
  99372. info = BABYLON.DDSTools.GetDDSInfo(data);
  99373. texture.width = info.width;
  99374. texture.height = info.height;
  99375. if (createPolynomials) {
  99376. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  99377. }
  99378. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99379. engine._unpackFlipY(info.isCompressed);
  99380. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  99381. if (!info.isFourCC && info.mipmapCount === 1) {
  99382. engine.generateMipMapsForCubemap(texture);
  99383. }
  99384. }
  99385. engine._setCubeMapTextureParams(loadMipmap);
  99386. texture.isReady = true;
  99387. if (onLoad) {
  99388. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  99389. }
  99390. };
  99391. /**
  99392. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99393. * @param data contains the texture data
  99394. * @param texture defines the BabylonJS internal texture
  99395. * @param callback defines the method to call once ready to upload
  99396. */
  99397. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  99398. var info = BABYLON.DDSTools.GetDDSInfo(data);
  99399. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  99400. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  99401. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  99402. });
  99403. };
  99404. return DDSTextureLoader;
  99405. }());
  99406. // Register the loader.
  99407. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  99408. })(BABYLON || (BABYLON = {}));
  99409. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  99410. var BABYLON;
  99411. (function (BABYLON) {
  99412. /**
  99413. * Based on jsTGALoader - Javascript loader for TGA file
  99414. * By Vincent Thibault
  99415. * @see http://blog.robrowser.com/javascript-tga-loader.html
  99416. */
  99417. var TGATools = /** @class */ (function () {
  99418. function TGATools() {
  99419. }
  99420. /**
  99421. * Gets the header of a TGA file
  99422. * @param data defines the TGA data
  99423. * @returns the header
  99424. */
  99425. TGATools.GetTGAHeader = function (data) {
  99426. var offset = 0;
  99427. var header = {
  99428. id_length: data[offset++],
  99429. colormap_type: data[offset++],
  99430. image_type: data[offset++],
  99431. colormap_index: data[offset++] | data[offset++] << 8,
  99432. colormap_length: data[offset++] | data[offset++] << 8,
  99433. colormap_size: data[offset++],
  99434. origin: [
  99435. data[offset++] | data[offset++] << 8,
  99436. data[offset++] | data[offset++] << 8
  99437. ],
  99438. width: data[offset++] | data[offset++] << 8,
  99439. height: data[offset++] | data[offset++] << 8,
  99440. pixel_size: data[offset++],
  99441. flags: data[offset++]
  99442. };
  99443. return header;
  99444. };
  99445. /**
  99446. * Uploads TGA content to a Babylon Texture
  99447. * @hidden
  99448. */
  99449. TGATools.UploadContent = function (texture, data) {
  99450. // Not enough data to contain header ?
  99451. if (data.length < 19) {
  99452. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  99453. return;
  99454. }
  99455. // Read Header
  99456. var offset = 18;
  99457. var header = TGATools.GetTGAHeader(data);
  99458. // Assume it's a valid Targa file.
  99459. if (header.id_length + offset > data.length) {
  99460. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  99461. return;
  99462. }
  99463. // Skip not needed data
  99464. offset += header.id_length;
  99465. var use_rle = false;
  99466. var use_pal = false;
  99467. var use_grey = false;
  99468. // Get some informations.
  99469. switch (header.image_type) {
  99470. case TGATools._TYPE_RLE_INDEXED:
  99471. use_rle = true;
  99472. case TGATools._TYPE_INDEXED:
  99473. use_pal = true;
  99474. break;
  99475. case TGATools._TYPE_RLE_RGB:
  99476. use_rle = true;
  99477. case TGATools._TYPE_RGB:
  99478. // use_rgb = true;
  99479. break;
  99480. case TGATools._TYPE_RLE_GREY:
  99481. use_rle = true;
  99482. case TGATools._TYPE_GREY:
  99483. use_grey = true;
  99484. break;
  99485. }
  99486. var pixel_data;
  99487. // var numAlphaBits = header.flags & 0xf;
  99488. var pixel_size = header.pixel_size >> 3;
  99489. var pixel_total = header.width * header.height * pixel_size;
  99490. // Read palettes
  99491. var palettes;
  99492. if (use_pal) {
  99493. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  99494. }
  99495. // Read LRE
  99496. if (use_rle) {
  99497. pixel_data = new Uint8Array(pixel_total);
  99498. var c, count, i;
  99499. var localOffset = 0;
  99500. var pixels = new Uint8Array(pixel_size);
  99501. while (offset < pixel_total && localOffset < pixel_total) {
  99502. c = data[offset++];
  99503. count = (c & 0x7f) + 1;
  99504. // RLE pixels
  99505. if (c & 0x80) {
  99506. // Bind pixel tmp array
  99507. for (i = 0; i < pixel_size; ++i) {
  99508. pixels[i] = data[offset++];
  99509. }
  99510. // Copy pixel array
  99511. for (i = 0; i < count; ++i) {
  99512. pixel_data.set(pixels, localOffset + i * pixel_size);
  99513. }
  99514. localOffset += pixel_size * count;
  99515. }
  99516. // Raw pixels
  99517. else {
  99518. count *= pixel_size;
  99519. for (i = 0; i < count; ++i) {
  99520. pixel_data[localOffset + i] = data[offset++];
  99521. }
  99522. localOffset += count;
  99523. }
  99524. }
  99525. }
  99526. // RAW Pixels
  99527. else {
  99528. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  99529. }
  99530. // Load to texture
  99531. var x_start, y_start, x_step, y_step, y_end, x_end;
  99532. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  99533. default:
  99534. case TGATools._ORIGIN_UL:
  99535. x_start = 0;
  99536. x_step = 1;
  99537. x_end = header.width;
  99538. y_start = 0;
  99539. y_step = 1;
  99540. y_end = header.height;
  99541. break;
  99542. case TGATools._ORIGIN_BL:
  99543. x_start = 0;
  99544. x_step = 1;
  99545. x_end = header.width;
  99546. y_start = header.height - 1;
  99547. y_step = -1;
  99548. y_end = -1;
  99549. break;
  99550. case TGATools._ORIGIN_UR:
  99551. x_start = header.width - 1;
  99552. x_step = -1;
  99553. x_end = -1;
  99554. y_start = 0;
  99555. y_step = 1;
  99556. y_end = header.height;
  99557. break;
  99558. case TGATools._ORIGIN_BR:
  99559. x_start = header.width - 1;
  99560. x_step = -1;
  99561. x_end = -1;
  99562. y_start = header.height - 1;
  99563. y_step = -1;
  99564. y_end = -1;
  99565. break;
  99566. }
  99567. // Load the specify method
  99568. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  99569. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  99570. var engine = texture.getEngine();
  99571. engine._uploadDataToTextureDirectly(texture, imageData);
  99572. };
  99573. /** @hidden */
  99574. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99575. var image = pixel_data, colormap = palettes;
  99576. var width = header.width, height = header.height;
  99577. var color, i = 0, x, y;
  99578. var imageData = new Uint8Array(width * height * 4);
  99579. for (y = y_start; y !== y_end; y += y_step) {
  99580. for (x = x_start; x !== x_end; x += x_step, i++) {
  99581. color = image[i];
  99582. imageData[(x + width * y) * 4 + 3] = 255;
  99583. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  99584. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  99585. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  99586. }
  99587. }
  99588. return imageData;
  99589. };
  99590. /** @hidden */
  99591. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99592. var image = pixel_data;
  99593. var width = header.width, height = header.height;
  99594. var color, i = 0, x, y;
  99595. var imageData = new Uint8Array(width * height * 4);
  99596. for (y = y_start; y !== y_end; y += y_step) {
  99597. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99598. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  99599. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  99600. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  99601. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  99602. imageData[(x + width * y) * 4 + 0] = r;
  99603. imageData[(x + width * y) * 4 + 1] = g;
  99604. imageData[(x + width * y) * 4 + 2] = b;
  99605. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  99606. }
  99607. }
  99608. return imageData;
  99609. };
  99610. /** @hidden */
  99611. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99612. var image = pixel_data;
  99613. var width = header.width, height = header.height;
  99614. var i = 0, x, y;
  99615. var imageData = new Uint8Array(width * height * 4);
  99616. for (y = y_start; y !== y_end; y += y_step) {
  99617. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  99618. imageData[(x + width * y) * 4 + 3] = 255;
  99619. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99620. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99621. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99622. }
  99623. }
  99624. return imageData;
  99625. };
  99626. /** @hidden */
  99627. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99628. var image = pixel_data;
  99629. var width = header.width, height = header.height;
  99630. var i = 0, x, y;
  99631. var imageData = new Uint8Array(width * height * 4);
  99632. for (y = y_start; y !== y_end; y += y_step) {
  99633. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  99634. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99635. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99636. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99637. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  99638. }
  99639. }
  99640. return imageData;
  99641. };
  99642. /** @hidden */
  99643. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99644. var image = pixel_data;
  99645. var width = header.width, height = header.height;
  99646. var color, i = 0, x, y;
  99647. var imageData = new Uint8Array(width * height * 4);
  99648. for (y = y_start; y !== y_end; y += y_step) {
  99649. for (x = x_start; x !== x_end; x += x_step, i++) {
  99650. color = image[i];
  99651. imageData[(x + width * y) * 4 + 0] = color;
  99652. imageData[(x + width * y) * 4 + 1] = color;
  99653. imageData[(x + width * y) * 4 + 2] = color;
  99654. imageData[(x + width * y) * 4 + 3] = 255;
  99655. }
  99656. }
  99657. return imageData;
  99658. };
  99659. /** @hidden */
  99660. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99661. var image = pixel_data;
  99662. var width = header.width, height = header.height;
  99663. var i = 0, x, y;
  99664. var imageData = new Uint8Array(width * height * 4);
  99665. for (y = y_start; y !== y_end; y += y_step) {
  99666. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99667. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  99668. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  99669. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99670. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  99671. }
  99672. }
  99673. return imageData;
  99674. };
  99675. //private static _TYPE_NO_DATA = 0;
  99676. TGATools._TYPE_INDEXED = 1;
  99677. TGATools._TYPE_RGB = 2;
  99678. TGATools._TYPE_GREY = 3;
  99679. TGATools._TYPE_RLE_INDEXED = 9;
  99680. TGATools._TYPE_RLE_RGB = 10;
  99681. TGATools._TYPE_RLE_GREY = 11;
  99682. TGATools._ORIGIN_MASK = 0x30;
  99683. TGATools._ORIGIN_SHIFT = 0x04;
  99684. TGATools._ORIGIN_BL = 0x00;
  99685. TGATools._ORIGIN_BR = 0x01;
  99686. TGATools._ORIGIN_UL = 0x02;
  99687. TGATools._ORIGIN_UR = 0x03;
  99688. return TGATools;
  99689. }());
  99690. BABYLON.TGATools = TGATools;
  99691. })(BABYLON || (BABYLON = {}));
  99692. //# sourceMappingURL=babylon.tga.js.map
  99693. var BABYLON;
  99694. (function (BABYLON) {
  99695. /**
  99696. * Implementation of the TGA Texture Loader.
  99697. */
  99698. var TGATextureLoader = /** @class */ (function () {
  99699. function TGATextureLoader() {
  99700. /**
  99701. * Defines wether the loader supports cascade loading the different faces.
  99702. */
  99703. this.supportCascades = false;
  99704. }
  99705. /**
  99706. * This returns if the loader support the current file information.
  99707. * @param extension defines the file extension of the file being loaded
  99708. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99709. * @param fallback defines the fallback internal texture if any
  99710. * @param isBase64 defines whether the texture is encoded as a base64
  99711. * @param isBuffer defines whether the texture data are stored as a buffer
  99712. * @returns true if the loader can load the specified file
  99713. */
  99714. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99715. return extension.indexOf(".tga") === 0;
  99716. };
  99717. /**
  99718. * Transform the url before loading if required.
  99719. * @param rootUrl the url of the texture
  99720. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99721. * @returns the transformed texture
  99722. */
  99723. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99724. return rootUrl;
  99725. };
  99726. /**
  99727. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99728. * @param rootUrl the url of the texture
  99729. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99730. * @returns the fallback texture
  99731. */
  99732. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99733. return null;
  99734. };
  99735. /**
  99736. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99737. * @param data contains the texture data
  99738. * @param texture defines the BabylonJS internal texture
  99739. * @param createPolynomials will be true if polynomials have been requested
  99740. * @param onLoad defines the callback to trigger once the texture is ready
  99741. * @param onError defines the callback to trigger in case of error
  99742. */
  99743. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99744. throw ".env not supported in Cube.";
  99745. };
  99746. /**
  99747. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99748. * @param data contains the texture data
  99749. * @param texture defines the BabylonJS internal texture
  99750. * @param callback defines the method to call once ready to upload
  99751. */
  99752. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  99753. var uintData = new Uint8Array(data);
  99754. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  99755. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  99756. BABYLON.TGATools.UploadContent(texture, uintData);
  99757. });
  99758. };
  99759. return TGATextureLoader;
  99760. }());
  99761. // Register the loader.
  99762. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  99763. })(BABYLON || (BABYLON = {}));
  99764. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  99765. var BABYLON;
  99766. (function (BABYLON) {
  99767. /**
  99768. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  99769. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  99770. */
  99771. var KhronosTextureContainer = /** @class */ (function () {
  99772. /**
  99773. * Creates a new KhronosTextureContainer
  99774. * @param arrayBuffer contents of the KTX container file
  99775. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  99776. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  99777. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  99778. */
  99779. function KhronosTextureContainer(
  99780. /** contents of the KTX container file */
  99781. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  99782. this.arrayBuffer = arrayBuffer;
  99783. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  99784. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  99785. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  99786. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  99787. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  99788. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  99789. BABYLON.Tools.Error("texture missing KTX identifier");
  99790. return;
  99791. }
  99792. // load the reset of the header in native 32 bit int
  99793. var header = new Int32Array(this.arrayBuffer, 12, 13);
  99794. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  99795. var oppositeEndianess = header[0] === 0x01020304;
  99796. // read all the header elements in order they exist in the file, without modification (sans endainness)
  99797. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  99798. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  99799. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  99800. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  99801. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  99802. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  99803. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  99804. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  99805. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  99806. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  99807. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  99808. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  99809. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  99810. if (this.glType !== 0) {
  99811. BABYLON.Tools.Error("only compressed formats currently supported");
  99812. return;
  99813. }
  99814. else {
  99815. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  99816. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  99817. }
  99818. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  99819. BABYLON.Tools.Error("only 2D textures currently supported");
  99820. return;
  99821. }
  99822. if (this.numberOfArrayElements !== 0) {
  99823. BABYLON.Tools.Error("texture arrays not currently supported");
  99824. return;
  99825. }
  99826. if (this.numberOfFaces !== facesExpected) {
  99827. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  99828. return;
  99829. }
  99830. // we now have a completely validated file, so could use existence of loadType as success
  99831. // would need to make this more elaborate & adjust checks above to support more than one load type
  99832. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  99833. }
  99834. //
  99835. /**
  99836. * Revert the endianness of a value.
  99837. * Not as fast hardware based, but will probably never need to use
  99838. * @param val defines the value to convert
  99839. * @returns the new value
  99840. */
  99841. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  99842. return ((val & 0xFF) << 24)
  99843. | ((val & 0xFF00) << 8)
  99844. | ((val >> 8) & 0xFF00)
  99845. | ((val >> 24) & 0xFF);
  99846. };
  99847. /**
  99848. * Uploads KTX content to a Babylon Texture.
  99849. * It is assumed that the texture has already been created & is currently bound
  99850. * @hidden
  99851. */
  99852. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  99853. switch (this.loadType) {
  99854. case KhronosTextureContainer.COMPRESSED_2D:
  99855. this._upload2DCompressedLevels(texture, loadMipmaps);
  99856. break;
  99857. case KhronosTextureContainer.TEX_2D:
  99858. case KhronosTextureContainer.COMPRESSED_3D:
  99859. case KhronosTextureContainer.TEX_3D:
  99860. }
  99861. };
  99862. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  99863. // initialize width & height for level 1
  99864. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  99865. var width = this.pixelWidth;
  99866. var height = this.pixelHeight;
  99867. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  99868. for (var level = 0; level < mipmapCount; level++) {
  99869. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  99870. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  99871. for (var face = 0; face < this.numberOfFaces; face++) {
  99872. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  99873. var engine = texture.getEngine();
  99874. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  99875. dataOffset += imageSize; // add size of the image for the next face/mipmap
  99876. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  99877. }
  99878. width = Math.max(1.0, width * 0.5);
  99879. height = Math.max(1.0, height * 0.5);
  99880. }
  99881. };
  99882. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  99883. // load types
  99884. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  99885. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  99886. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  99887. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  99888. return KhronosTextureContainer;
  99889. }());
  99890. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  99891. })(BABYLON || (BABYLON = {}));
  99892. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  99893. var BABYLON;
  99894. (function (BABYLON) {
  99895. /**
  99896. * Implementation of the KTX Texture Loader.
  99897. */
  99898. var KTXTextureLoader = /** @class */ (function () {
  99899. function KTXTextureLoader() {
  99900. /**
  99901. * Defines wether the loader supports cascade loading the different faces.
  99902. */
  99903. this.supportCascades = false;
  99904. }
  99905. /**
  99906. * This returns if the loader support the current file information.
  99907. * @param extension defines the file extension of the file being loaded
  99908. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99909. * @param fallback defines the fallback internal texture if any
  99910. * @param isBase64 defines whether the texture is encoded as a base64
  99911. * @param isBuffer defines whether the texture data are stored as a buffer
  99912. * @returns true if the loader can load the specified file
  99913. */
  99914. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99915. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  99916. return true;
  99917. }
  99918. return false;
  99919. };
  99920. /**
  99921. * Transform the url before loading if required.
  99922. * @param rootUrl the url of the texture
  99923. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99924. * @returns the transformed texture
  99925. */
  99926. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99927. var lastDot = rootUrl.lastIndexOf('.');
  99928. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  99929. };
  99930. /**
  99931. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99932. * @param rootUrl the url of the texture
  99933. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99934. * @returns the fallback texture
  99935. */
  99936. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99937. // remove the format appended to the rootUrl in the original createCubeTexture call.
  99938. var exp = new RegExp("" + textureFormatInUse + "$");
  99939. return rootUrl.replace(exp, "");
  99940. };
  99941. /**
  99942. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99943. * @param data contains the texture data
  99944. * @param texture defines the BabylonJS internal texture
  99945. * @param createPolynomials will be true if polynomials have been requested
  99946. * @param onLoad defines the callback to trigger once the texture is ready
  99947. * @param onError defines the callback to trigger in case of error
  99948. */
  99949. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99950. if (Array.isArray(data)) {
  99951. return;
  99952. }
  99953. var engine = texture.getEngine();
  99954. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  99955. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  99956. engine._unpackFlipY(true);
  99957. ktx.uploadLevels(texture, texture.generateMipMaps);
  99958. texture.width = ktx.pixelWidth;
  99959. texture.height = ktx.pixelHeight;
  99960. engine._setCubeMapTextureParams(loadMipmap);
  99961. texture.isReady = true;
  99962. };
  99963. /**
  99964. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99965. * @param data contains the texture data
  99966. * @param texture defines the BabylonJS internal texture
  99967. * @param callback defines the method to call once ready to upload
  99968. */
  99969. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  99970. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  99971. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  99972. ktx.uploadLevels(texture, texture.generateMipMaps);
  99973. });
  99974. };
  99975. return KTXTextureLoader;
  99976. }());
  99977. // Register the loader.
  99978. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  99979. })(BABYLON || (BABYLON = {}));
  99980. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  99981. var BABYLON;
  99982. (function (BABYLON) {
  99983. /**
  99984. * Sets of helpers addressing the serialization and deserialization of environment texture
  99985. * stored in a BabylonJS env file.
  99986. * Those files are usually stored as .env files.
  99987. */
  99988. var EnvironmentTextureTools = /** @class */ (function () {
  99989. function EnvironmentTextureTools() {
  99990. }
  99991. /**
  99992. * Gets the environment info from an env file.
  99993. * @param data The array buffer containing the .env bytes.
  99994. * @returns the environment file info (the json header) if successfully parsed.
  99995. */
  99996. EnvironmentTextureTools.GetEnvInfo = function (data) {
  99997. var dataView = new DataView(data);
  99998. var pos = 0;
  99999. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100000. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  100001. BABYLON.Tools.Error('Not a babylon environment map');
  100002. return null;
  100003. }
  100004. }
  100005. // Read json manifest - collect characters up to null terminator
  100006. var manifestString = '';
  100007. var charCode = 0x00;
  100008. while ((charCode = dataView.getUint8(pos++))) {
  100009. manifestString += String.fromCharCode(charCode);
  100010. }
  100011. var manifest = JSON.parse(manifestString);
  100012. if (manifest.specular) {
  100013. // Extend the header with the position of the payload.
  100014. manifest.specular.specularDataPosition = pos;
  100015. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  100016. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  100017. }
  100018. return manifest;
  100019. };
  100020. /**
  100021. * Creates an environment texture from a loaded cube texture.
  100022. * @param texture defines the cube texture to convert in env file
  100023. * @return a promise containing the environment data if succesfull.
  100024. */
  100025. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  100026. var _this = this;
  100027. var internalTexture = texture.getInternalTexture();
  100028. if (!internalTexture) {
  100029. return Promise.reject("The cube texture is invalid.");
  100030. }
  100031. if (!texture._prefiltered) {
  100032. return Promise.reject("The cube texture is invalid (not prefiltered).");
  100033. }
  100034. var engine = internalTexture.getEngine();
  100035. if (engine && engine.premultipliedAlpha) {
  100036. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  100037. }
  100038. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  100039. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  100040. }
  100041. var canvas = engine.getRenderingCanvas();
  100042. if (!canvas) {
  100043. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  100044. }
  100045. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100046. if (!engine.getCaps().textureFloatRender) {
  100047. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100048. if (!engine.getCaps().textureHalfFloatRender) {
  100049. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  100050. }
  100051. }
  100052. var cubeWidth = internalTexture.width;
  100053. var hostingScene = new BABYLON.Scene(engine);
  100054. var specularTextures = {};
  100055. var promises = [];
  100056. // Read and collect all mipmaps data from the cube.
  100057. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  100058. mipmapsCount = Math.round(mipmapsCount);
  100059. var _loop_1 = function (i) {
  100060. var faceWidth = Math.pow(2, mipmapsCount - i);
  100061. var _loop_2 = function (face) {
  100062. var data = texture.readPixels(face, i);
  100063. // Creates a temp texture with the face data.
  100064. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  100065. // And rgbdEncode them.
  100066. var promise = new Promise(function (resolve, reject) {
  100067. 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);
  100068. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100069. rgbdPostProcess.onApply = function (effect) {
  100070. effect._bindTexture("textureSampler", tempTexture);
  100071. };
  100072. // As the process needs to happen on the main canvas, keep track of the current size
  100073. var currentW = engine.getRenderWidth();
  100074. var currentH = engine.getRenderHeight();
  100075. // Set the desired size for the texture
  100076. engine.setSize(faceWidth, faceWidth);
  100077. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  100078. // Reading datas from WebGL
  100079. BABYLON.Tools.ToBlob(canvas, function (blob) {
  100080. var fileReader = new FileReader();
  100081. fileReader.onload = function (event) {
  100082. var arrayBuffer = event.target.result;
  100083. specularTextures[i * 6 + face] = arrayBuffer;
  100084. resolve();
  100085. };
  100086. fileReader.readAsArrayBuffer(blob);
  100087. });
  100088. // Reapply the previous canvas size
  100089. engine.setSize(currentW, currentH);
  100090. });
  100091. });
  100092. promises.push(promise);
  100093. };
  100094. // All faces of the cube.
  100095. for (var face = 0; face < 6; face++) {
  100096. _loop_2(face);
  100097. }
  100098. };
  100099. for (var i = 0; i <= mipmapsCount; i++) {
  100100. _loop_1(i);
  100101. }
  100102. // Once all the textures haves been collected as RGBD stored in PNGs
  100103. return Promise.all(promises).then(function () {
  100104. // We can delete the hosting scene keeping track of all the creation objects
  100105. hostingScene.dispose();
  100106. // Creates the json header for the env texture
  100107. var info = {
  100108. version: 1,
  100109. width: cubeWidth,
  100110. irradiance: _this._CreateEnvTextureIrradiance(texture),
  100111. specular: {
  100112. mipmaps: [],
  100113. lodGenerationScale: texture.lodGenerationScale
  100114. }
  100115. };
  100116. // Sets the specular image data information
  100117. var position = 0;
  100118. for (var i = 0; i <= mipmapsCount; i++) {
  100119. for (var face = 0; face < 6; face++) {
  100120. var byteLength = specularTextures[i * 6 + face].byteLength;
  100121. info.specular.mipmaps.push({
  100122. length: byteLength,
  100123. position: position
  100124. });
  100125. position += byteLength;
  100126. }
  100127. }
  100128. // Encode the JSON as an array buffer
  100129. var infoString = JSON.stringify(info);
  100130. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  100131. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  100132. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  100133. infoView[i] = infoString.charCodeAt(i);
  100134. }
  100135. // Ends up with a null terminator for easier parsing
  100136. infoView[infoString.length] = 0x00;
  100137. // Computes the final required size and creates the storage
  100138. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  100139. var finalBuffer = new ArrayBuffer(totalSize);
  100140. var finalBufferView = new Uint8Array(finalBuffer);
  100141. var dataView = new DataView(finalBuffer);
  100142. // Copy the magic bytes identifying the file in
  100143. var pos = 0;
  100144. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100145. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  100146. }
  100147. // Add the json info
  100148. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  100149. pos += infoBuffer.byteLength;
  100150. // Finally inserts the texture data
  100151. for (var i = 0; i <= mipmapsCount; i++) {
  100152. for (var face = 0; face < 6; face++) {
  100153. var dataBuffer = specularTextures[i * 6 + face];
  100154. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  100155. pos += dataBuffer.byteLength;
  100156. }
  100157. }
  100158. // Voila
  100159. return finalBuffer;
  100160. });
  100161. };
  100162. /**
  100163. * Creates a JSON representation of the spherical data.
  100164. * @param texture defines the texture containing the polynomials
  100165. * @return the JSON representation of the spherical info
  100166. */
  100167. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  100168. var polynmials = texture.sphericalPolynomial;
  100169. if (polynmials == null) {
  100170. return null;
  100171. }
  100172. return {
  100173. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  100174. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  100175. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  100176. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  100177. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  100178. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  100179. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  100180. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  100181. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  100182. };
  100183. };
  100184. /**
  100185. * Uploads the texture info contained in the env file to the GPU.
  100186. * @param texture defines the internal texture to upload to
  100187. * @param arrayBuffer defines the buffer cotaining the data to load
  100188. * @param info defines the texture info retrieved through the GetEnvInfo method
  100189. * @returns a promise
  100190. */
  100191. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  100192. if (info.version !== 1) {
  100193. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  100194. }
  100195. var specularInfo = info.specular;
  100196. if (!specularInfo) {
  100197. // Nothing else parsed so far
  100198. return Promise.resolve();
  100199. }
  100200. // Double checks the enclosed info
  100201. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  100202. mipmapsCount = Math.round(mipmapsCount) + 1;
  100203. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  100204. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  100205. }
  100206. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  100207. var imageData = new Array(mipmapsCount);
  100208. for (var i = 0; i < mipmapsCount; i++) {
  100209. imageData[i] = new Array(6);
  100210. for (var face = 0; face < 6; face++) {
  100211. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  100212. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  100213. }
  100214. }
  100215. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  100216. };
  100217. /**
  100218. * Uploads the levels of image data to the GPU.
  100219. * @param texture defines the internal texture to upload to
  100220. * @param imageData defines the array buffer views of image data [mipmap][face]
  100221. * @returns a promise
  100222. */
  100223. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  100224. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  100225. throw new Error("Texture size must be a power of two");
  100226. }
  100227. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  100228. // Gets everything ready.
  100229. var engine = texture.getEngine();
  100230. var expandTexture = false;
  100231. var generateNonLODTextures = false;
  100232. var rgbdPostProcess = null;
  100233. var cubeRtt = null;
  100234. var lodTextures = null;
  100235. var caps = engine.getCaps();
  100236. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  100237. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100238. texture.generateMipMaps = true;
  100239. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  100240. // Add extra process if texture lod is not supported
  100241. if (!caps.textureLOD) {
  100242. expandTexture = false;
  100243. generateNonLODTextures = true;
  100244. lodTextures = {};
  100245. }
  100246. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  100247. else if (engine.webGLVersion < 2) {
  100248. expandTexture = false;
  100249. }
  100250. // If half float available we can uncompress the texture
  100251. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  100252. expandTexture = true;
  100253. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100254. }
  100255. // If full float available we can uncompress the texture
  100256. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  100257. expandTexture = true;
  100258. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100259. }
  100260. // Expand the texture if possible
  100261. if (expandTexture) {
  100262. // Simply run through the decode PP
  100263. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  100264. texture._isRGBD = false;
  100265. texture.invertY = false;
  100266. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  100267. generateDepthBuffer: false,
  100268. generateMipMaps: true,
  100269. generateStencilBuffer: false,
  100270. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  100271. type: texture.type,
  100272. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  100273. });
  100274. }
  100275. else {
  100276. texture._isRGBD = true;
  100277. texture.invertY = true;
  100278. // In case of missing support, applies the same patch than DDS files.
  100279. if (generateNonLODTextures) {
  100280. var mipSlices = 3;
  100281. var scale = texture._lodGenerationScale;
  100282. var offset = texture._lodGenerationOffset;
  100283. for (var i = 0; i < mipSlices; i++) {
  100284. //compute LOD from even spacing in smoothness (matching shader calculation)
  100285. var smoothness = i / (mipSlices - 1);
  100286. var roughness = 1 - smoothness;
  100287. var minLODIndex = offset; // roughness = 0
  100288. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  100289. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  100290. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  100291. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  100292. glTextureFromLod.isCube = true;
  100293. glTextureFromLod.invertY = true;
  100294. glTextureFromLod.generateMipMaps = false;
  100295. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  100296. // Wrap in a base texture for easy binding.
  100297. var lodTexture = new BABYLON.BaseTexture(null);
  100298. lodTexture.isCube = true;
  100299. lodTexture._texture = glTextureFromLod;
  100300. lodTextures[mipmapIndex] = lodTexture;
  100301. switch (i) {
  100302. case 0:
  100303. texture._lodTextureLow = lodTexture;
  100304. break;
  100305. case 1:
  100306. texture._lodTextureMid = lodTexture;
  100307. break;
  100308. case 2:
  100309. texture._lodTextureHigh = lodTexture;
  100310. break;
  100311. }
  100312. }
  100313. }
  100314. }
  100315. var promises = [];
  100316. var _loop_3 = function (i) {
  100317. var _loop_4 = function (face) {
  100318. // Constructs an image element from image data
  100319. var bytes = imageData[i][face];
  100320. var blob = new Blob([bytes], { type: 'image/png' });
  100321. var url = URL.createObjectURL(blob);
  100322. var image = new Image();
  100323. image.src = url;
  100324. // Enqueue promise to upload to the texture.
  100325. var promise = new Promise(function (resolve, reject) {
  100326. image.onload = function () {
  100327. if (expandTexture) {
  100328. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  100329. reject(message);
  100330. }, image);
  100331. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100332. // Uncompress the data to a RTT
  100333. rgbdPostProcess.onApply = function (effect) {
  100334. effect._bindTexture("textureSampler", tempTexture_1);
  100335. effect.setFloat2("scale", 1, 1);
  100336. };
  100337. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  100338. // Cleanup
  100339. engine.restoreDefaultFramebuffer();
  100340. tempTexture_1.dispose();
  100341. window.URL.revokeObjectURL(url);
  100342. resolve();
  100343. });
  100344. }
  100345. else {
  100346. engine._uploadImageToTexture(texture, image, face, i);
  100347. // Upload the face to the non lod texture support
  100348. if (generateNonLODTextures) {
  100349. var lodTexture = lodTextures[i];
  100350. if (lodTexture) {
  100351. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  100352. }
  100353. }
  100354. resolve();
  100355. }
  100356. };
  100357. image.onerror = function (error) {
  100358. reject(error);
  100359. };
  100360. });
  100361. promises.push(promise);
  100362. };
  100363. // All faces
  100364. for (var face = 0; face < 6; face++) {
  100365. _loop_4(face);
  100366. }
  100367. };
  100368. // All mipmaps up to provided number of images
  100369. for (var i = 0; i < imageData.length; i++) {
  100370. _loop_3(i);
  100371. }
  100372. // Fill remaining mipmaps with black textures.
  100373. if (imageData.length < mipmapsCount) {
  100374. var data = void 0;
  100375. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  100376. var dataLength = size * size * 4;
  100377. switch (texture.type) {
  100378. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  100379. data = new Uint8Array(dataLength);
  100380. break;
  100381. }
  100382. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  100383. data = new Uint16Array(dataLength);
  100384. break;
  100385. }
  100386. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  100387. data = new Float32Array(dataLength);
  100388. break;
  100389. }
  100390. }
  100391. for (var i = imageData.length; i < mipmapsCount; i++) {
  100392. for (var face = 0; face < 6; face++) {
  100393. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  100394. }
  100395. }
  100396. }
  100397. // Once all done, finishes the cleanup and return
  100398. return Promise.all(promises).then(function () {
  100399. // Release temp RTT.
  100400. if (cubeRtt) {
  100401. engine._releaseFramebufferObjects(cubeRtt);
  100402. cubeRtt._swapAndDie(texture);
  100403. }
  100404. // Release temp Post Process.
  100405. if (rgbdPostProcess) {
  100406. rgbdPostProcess.dispose();
  100407. }
  100408. // Flag internal texture as ready in case they are in use.
  100409. if (generateNonLODTextures) {
  100410. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  100411. texture._lodTextureHigh._texture.isReady = true;
  100412. }
  100413. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  100414. texture._lodTextureMid._texture.isReady = true;
  100415. }
  100416. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  100417. texture._lodTextureLow._texture.isReady = true;
  100418. }
  100419. }
  100420. });
  100421. };
  100422. /**
  100423. * Uploads spherical polynomials information to the texture.
  100424. * @param texture defines the texture we are trying to upload the information to
  100425. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  100426. */
  100427. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  100428. if (info.version !== 1) {
  100429. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  100430. }
  100431. var irradianceInfo = info.irradiance;
  100432. if (!irradianceInfo) {
  100433. return;
  100434. }
  100435. var sp = new BABYLON.SphericalPolynomial();
  100436. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  100437. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  100438. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  100439. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  100440. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  100441. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  100442. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  100443. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  100444. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  100445. texture._sphericalPolynomial = sp;
  100446. };
  100447. /**
  100448. * Magic number identifying the env file.
  100449. */
  100450. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  100451. return EnvironmentTextureTools;
  100452. }());
  100453. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  100454. })(BABYLON || (BABYLON = {}));
  100455. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  100456. var BABYLON;
  100457. (function (BABYLON) {
  100458. /**
  100459. * Implementation of the ENV Texture Loader.
  100460. */
  100461. var ENVTextureLoader = /** @class */ (function () {
  100462. function ENVTextureLoader() {
  100463. /**
  100464. * Defines wether the loader supports cascade loading the different faces.
  100465. */
  100466. this.supportCascades = false;
  100467. }
  100468. /**
  100469. * This returns if the loader support the current file information.
  100470. * @param extension defines the file extension of the file being loaded
  100471. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100472. * @param fallback defines the fallback internal texture if any
  100473. * @param isBase64 defines whether the texture is encoded as a base64
  100474. * @param isBuffer defines whether the texture data are stored as a buffer
  100475. * @returns true if the loader can load the specified file
  100476. */
  100477. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100478. return extension.indexOf(".env") === 0;
  100479. };
  100480. /**
  100481. * Transform the url before loading if required.
  100482. * @param rootUrl the url of the texture
  100483. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100484. * @returns the transformed texture
  100485. */
  100486. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100487. return rootUrl;
  100488. };
  100489. /**
  100490. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100491. * @param rootUrl the url of the texture
  100492. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100493. * @returns the fallback texture
  100494. */
  100495. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100496. return null;
  100497. };
  100498. /**
  100499. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100500. * @param data contains the texture data
  100501. * @param texture defines the BabylonJS internal texture
  100502. * @param createPolynomials will be true if polynomials have been requested
  100503. * @param onLoad defines the callback to trigger once the texture is ready
  100504. * @param onError defines the callback to trigger in case of error
  100505. */
  100506. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100507. if (Array.isArray(data)) {
  100508. return;
  100509. }
  100510. data = data;
  100511. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  100512. if (info) {
  100513. texture.width = info.width;
  100514. texture.height = info.width;
  100515. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  100516. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  100517. texture.isReady = true;
  100518. if (onLoad) {
  100519. onLoad();
  100520. }
  100521. });
  100522. }
  100523. else if (onError) {
  100524. onError("Can not parse the environment file", null);
  100525. }
  100526. };
  100527. /**
  100528. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100529. * @param data contains the texture data
  100530. * @param texture defines the BabylonJS internal texture
  100531. * @param callback defines the method to call once ready to upload
  100532. */
  100533. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  100534. throw ".env not supported in 2d.";
  100535. };
  100536. return ENVTextureLoader;
  100537. }());
  100538. // Register the loader.
  100539. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  100540. })(BABYLON || (BABYLON = {}));
  100541. //# sourceMappingURL=babylon.envTextureLoader.js.map
  100542. var BABYLON;
  100543. (function (BABYLON) {
  100544. /**
  100545. * Renders a layer on top of an existing scene
  100546. */
  100547. var UtilityLayerRenderer = /** @class */ (function () {
  100548. /**
  100549. * Instantiates a UtilityLayerRenderer
  100550. * @param originalScene the original scene that will be rendered on top of
  100551. */
  100552. function UtilityLayerRenderer(
  100553. /** the original scene that will be rendered on top of */
  100554. originalScene) {
  100555. var _this = this;
  100556. this.originalScene = originalScene;
  100557. this._pointerCaptures = {};
  100558. this._lastPointerEvents = {};
  100559. /**
  100560. * If the utility layer should automatically be rendered on top of existing scene
  100561. */
  100562. this.shouldRender = true;
  100563. /**
  100564. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  100565. */
  100566. this.onlyCheckPointerDownEvents = true;
  100567. /**
  100568. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  100569. */
  100570. this.processAllEvents = false;
  100571. /**
  100572. * Observable raised when the pointer move from the utility layer scene to the main scene
  100573. */
  100574. this.onPointerOutObservable = new BABYLON.Observable();
  100575. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  100576. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  100577. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  100578. this.utilityLayerScene._allowPostProcessClearColor = false;
  100579. originalScene.getEngine().scenes.pop();
  100580. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  100581. this.utilityLayerScene.detachControl();
  100582. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  100583. if (!_this.processAllEvents) {
  100584. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  100585. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  100586. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  100587. return;
  100588. }
  100589. }
  100590. var pointerEvent = (prePointerInfo.event);
  100591. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  100592. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100593. return;
  100594. }
  100595. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  100596. if (!prePointerInfo.ray && utilityScenePick) {
  100597. prePointerInfo.ray = utilityScenePick.ray;
  100598. }
  100599. // always fire the prepointer oversvable
  100600. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  100601. // allow every non pointer down event to flow to the utility layer
  100602. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  100603. if (!prePointerInfo.skipOnPointerObservable) {
  100604. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100605. }
  100606. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  100607. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100608. }
  100609. return;
  100610. }
  100611. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  100612. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  100613. if (utilityScenePick && utilityScenePick.hit) {
  100614. if (!prePointerInfo.skipOnPointerObservable) {
  100615. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100616. }
  100617. prePointerInfo.skipOnPointerObservable = true;
  100618. }
  100619. }
  100620. else {
  100621. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  100622. var pointerEvent_1 = (prePointerInfo.event);
  100623. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  100624. if (originalScenePick && utilityScenePick) {
  100625. // No pick in utility scene
  100626. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  100627. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100628. // We touched an utility mesh present in the main scene
  100629. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100630. prePointerInfo.skipOnPointerObservable = true;
  100631. }
  100632. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100633. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  100634. }
  100635. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100636. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100637. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100638. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100639. }
  100640. }
  100641. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  100642. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  100643. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  100644. // If a previous utility layer set this, do not unset this
  100645. if (!prePointerInfo.skipOnPointerObservable) {
  100646. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  100647. }
  100648. }
  100649. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  100650. // We have a pick in both scenes but main is closer than utility
  100651. // We touched an utility mesh present in the main scene
  100652. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100653. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100654. prePointerInfo.skipOnPointerObservable = true;
  100655. }
  100656. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100657. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100658. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100659. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100660. }
  100661. }
  100662. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  100663. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  100664. }
  100665. }
  100666. }
  100667. });
  100668. // Render directly on top of existing scene without clearing
  100669. this.utilityLayerScene.autoClear = false;
  100670. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  100671. if (_this.shouldRender) {
  100672. _this.render();
  100673. }
  100674. });
  100675. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  100676. _this.dispose();
  100677. });
  100678. this._updateCamera();
  100679. }
  100680. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  100681. /**
  100682. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  100683. */
  100684. get: function () {
  100685. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  100686. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100687. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100688. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100689. });
  100690. }
  100691. return UtilityLayerRenderer._DefaultUtilityLayer;
  100692. },
  100693. enumerable: true,
  100694. configurable: true
  100695. });
  100696. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  100697. /**
  100698. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  100699. */
  100700. get: function () {
  100701. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  100702. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100703. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  100704. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100705. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100706. });
  100707. }
  100708. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  100709. },
  100710. enumerable: true,
  100711. configurable: true
  100712. });
  100713. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  100714. if (!prePointerInfo.skipOnPointerObservable) {
  100715. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  100716. this._lastPointerEvents[pointerEvent.pointerId] = true;
  100717. }
  100718. };
  100719. /**
  100720. * Renders the utility layers scene on top of the original scene
  100721. */
  100722. UtilityLayerRenderer.prototype.render = function () {
  100723. this._updateCamera();
  100724. if (this.utilityLayerScene.activeCamera) {
  100725. // Set the camera's scene to utility layers scene
  100726. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  100727. var camera = this.utilityLayerScene.activeCamera;
  100728. camera._scene = this.utilityLayerScene;
  100729. if (camera.leftCamera) {
  100730. camera.leftCamera._scene = this.utilityLayerScene;
  100731. }
  100732. if (camera.rightCamera) {
  100733. camera.rightCamera._scene = this.utilityLayerScene;
  100734. }
  100735. this.utilityLayerScene.render(false);
  100736. // Reset camera's scene back to original
  100737. camera._scene = oldScene;
  100738. if (camera.leftCamera) {
  100739. camera.leftCamera._scene = oldScene;
  100740. }
  100741. if (camera.rightCamera) {
  100742. camera.rightCamera._scene = oldScene;
  100743. }
  100744. }
  100745. };
  100746. /**
  100747. * Disposes of the renderer
  100748. */
  100749. UtilityLayerRenderer.prototype.dispose = function () {
  100750. this.onPointerOutObservable.clear();
  100751. if (this._afterRenderObserver) {
  100752. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  100753. }
  100754. if (this._sceneDisposeObserver) {
  100755. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100756. }
  100757. if (this._originalPointerObserver) {
  100758. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  100759. }
  100760. this.utilityLayerScene.dispose();
  100761. };
  100762. UtilityLayerRenderer.prototype._updateCamera = function () {
  100763. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  100764. };
  100765. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100766. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100767. return UtilityLayerRenderer;
  100768. }());
  100769. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  100770. })(BABYLON || (BABYLON = {}));
  100771. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  100772. //# sourceMappingURL=babylon.behavior.js.map
  100773. var BABYLON;
  100774. (function (BABYLON) {
  100775. /**
  100776. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  100777. */
  100778. var PointerDragBehavior = /** @class */ (function () {
  100779. /**
  100780. * Creates a pointer drag behavior that can be attached to a mesh
  100781. * @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)
  100782. */
  100783. function PointerDragBehavior(options) {
  100784. /**
  100785. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  100786. */
  100787. this.maxDragAngle = 0;
  100788. /**
  100789. * @hidden
  100790. */
  100791. this._useAlternatePickedPointAboveMaxDragAngle = false;
  100792. /**
  100793. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  100794. */
  100795. this.currentDraggingPointerID = -1;
  100796. /**
  100797. * If the behavior is currently in a dragging state
  100798. */
  100799. this.dragging = false;
  100800. /**
  100801. * 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)
  100802. */
  100803. this.dragDeltaRatio = 0.2;
  100804. /**
  100805. * If the drag plane orientation should be updated during the dragging (Default: true)
  100806. */
  100807. this.updateDragPlane = true;
  100808. // Debug mode will display drag planes to help visualize behavior
  100809. this._debugMode = false;
  100810. this._moving = false;
  100811. /**
  100812. * Fires each time the attached mesh is dragged with the pointer
  100813. * * delta between last drag position and current drag position in world space
  100814. * * dragDistance along the drag axis
  100815. * * dragPlaneNormal normal of the current drag plane used during the drag
  100816. * * dragPlanePoint in world space where the drag intersects the drag plane
  100817. */
  100818. this.onDragObservable = new BABYLON.Observable();
  100819. /**
  100820. * Fires each time a drag begins (eg. mouse down on mesh)
  100821. */
  100822. this.onDragStartObservable = new BABYLON.Observable();
  100823. /**
  100824. * Fires each time a drag ends (eg. mouse release after drag)
  100825. */
  100826. this.onDragEndObservable = new BABYLON.Observable();
  100827. /**
  100828. * If the attached mesh should be moved when dragged
  100829. */
  100830. this.moveAttached = true;
  100831. /**
  100832. * If the drag behavior will react to drag events (Default: true)
  100833. */
  100834. this.enabled = true;
  100835. /**
  100836. * If camera controls should be detached during the drag
  100837. */
  100838. this.detachCameraControls = true;
  100839. /**
  100840. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  100841. */
  100842. this.useObjectOrienationForDragging = true;
  100843. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  100844. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  100845. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  100846. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  100847. this._attachedElement = null;
  100848. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100849. this._lastPointerRay = {};
  100850. this._dragDelta = new BABYLON.Vector3();
  100851. // Variables to avoid instantiation in the below method
  100852. this._pointA = new BABYLON.Vector3(0, 0, 0);
  100853. this._pointB = new BABYLON.Vector3(0, 0, 0);
  100854. this._pointC = new BABYLON.Vector3(0, 0, 0);
  100855. this._lineA = new BABYLON.Vector3(0, 0, 0);
  100856. this._lineB = new BABYLON.Vector3(0, 0, 0);
  100857. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  100858. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  100859. this._options = options ? options : {};
  100860. var optionCount = 0;
  100861. if (this._options.dragAxis) {
  100862. optionCount++;
  100863. }
  100864. if (this._options.dragPlaneNormal) {
  100865. optionCount++;
  100866. }
  100867. if (optionCount > 1) {
  100868. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  100869. }
  100870. }
  100871. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  100872. /**
  100873. * The name of the behavior
  100874. */
  100875. get: function () {
  100876. return "PointerDrag";
  100877. },
  100878. enumerable: true,
  100879. configurable: true
  100880. });
  100881. /**
  100882. * Initializes the behavior
  100883. */
  100884. PointerDragBehavior.prototype.init = function () { };
  100885. /**
  100886. * Attaches the drag behavior the passed in mesh
  100887. * @param ownerNode The mesh that will be dragged around once attached
  100888. */
  100889. PointerDragBehavior.prototype.attach = function (ownerNode) {
  100890. var _this = this;
  100891. this._scene = ownerNode.getScene();
  100892. this._attachedNode = ownerNode;
  100893. // Initialize drag plane to not interfere with existing scene
  100894. if (!PointerDragBehavior._planeScene) {
  100895. if (this._debugMode) {
  100896. PointerDragBehavior._planeScene = this._scene;
  100897. }
  100898. else {
  100899. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  100900. PointerDragBehavior._planeScene.detachControl();
  100901. this._scene.getEngine().scenes.pop();
  100902. this._scene.onDisposeObservable.addOnce(function () {
  100903. PointerDragBehavior._planeScene.dispose();
  100904. PointerDragBehavior._planeScene = null;
  100905. });
  100906. }
  100907. }
  100908. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  100909. // State of the drag
  100910. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  100911. var pickPredicate = function (m) {
  100912. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  100913. };
  100914. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100915. if (!_this.enabled) {
  100916. return;
  100917. }
  100918. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100919. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100920. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  100921. }
  100922. }
  100923. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100924. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100925. _this.releaseDrag();
  100926. }
  100927. }
  100928. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100929. var pointerId = pointerInfo.event.pointerId;
  100930. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  100931. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  100932. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  100933. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  100934. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  100935. }
  100936. _this.currentDraggingPointerID = pointerId;
  100937. }
  100938. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  100939. if (!_this._lastPointerRay[pointerId]) {
  100940. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100941. }
  100942. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  100943. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  100944. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  100945. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  100946. _this._moveDrag(pointerInfo.pickInfo.ray);
  100947. }
  100948. }
  100949. }
  100950. });
  100951. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100952. if (_this._moving && _this.moveAttached) {
  100953. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  100954. // Slowly move mesh to avoid jitter
  100955. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  100956. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  100957. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  100958. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  100959. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  100960. }
  100961. });
  100962. };
  100963. /**
  100964. * Force relase the drag action by code.
  100965. */
  100966. PointerDragBehavior.prototype.releaseDrag = function () {
  100967. this.dragging = false;
  100968. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  100969. this.currentDraggingPointerID = -1;
  100970. this._moving = false;
  100971. // Reattach camera controls
  100972. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  100973. this._scene.activeCamera.attachControl(this._attachedElement, true);
  100974. }
  100975. };
  100976. /**
  100977. * Simulates the start of a pointer drag event on the behavior
  100978. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  100979. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  100980. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  100981. */
  100982. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  100983. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  100984. this._startDrag(pointerId, fromRay, startPickedPoint);
  100985. var lastRay = this._lastPointerRay[pointerId];
  100986. if (pointerId === PointerDragBehavior._AnyMouseID) {
  100987. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  100988. }
  100989. if (lastRay) {
  100990. // if there was a last pointer ray drag the object there
  100991. this._moveDrag(lastRay);
  100992. }
  100993. };
  100994. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  100995. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  100996. return;
  100997. }
  100998. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  100999. // Create start ray from the camera to the object
  101000. if (fromRay) {
  101001. this._startDragRay.direction.copyFrom(fromRay.direction);
  101002. this._startDragRay.origin.copyFrom(fromRay.origin);
  101003. }
  101004. else {
  101005. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  101006. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  101007. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  101008. }
  101009. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  101010. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  101011. if (pickedPoint) {
  101012. this.dragging = true;
  101013. this.currentDraggingPointerID = pointerId;
  101014. this.lastDragPosition.copyFrom(pickedPoint);
  101015. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  101016. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  101017. // Detatch camera controls
  101018. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  101019. if (this._scene.activeCamera.inputs.attachedElement) {
  101020. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  101021. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  101022. }
  101023. else {
  101024. this._attachedElement = null;
  101025. }
  101026. }
  101027. }
  101028. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  101029. };
  101030. PointerDragBehavior.prototype._moveDrag = function (ray) {
  101031. this._moving = true;
  101032. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  101033. if (pickedPoint) {
  101034. if (this.updateDragPlane) {
  101035. this._updateDragPlanePosition(ray, pickedPoint);
  101036. }
  101037. var dragLength = 0;
  101038. // depending on the drag mode option drag accordingly
  101039. if (this._options.dragAxis) {
  101040. // Convert local drag axis to world
  101041. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  101042. // Project delta drag from the drag plane onto the drag axis
  101043. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  101044. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  101045. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  101046. }
  101047. else {
  101048. dragLength = this._dragDelta.length();
  101049. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  101050. }
  101051. this._targetPosition.addInPlace(this._dragDelta);
  101052. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  101053. this.lastDragPosition.copyFrom(pickedPoint);
  101054. }
  101055. };
  101056. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  101057. var _this = this;
  101058. if (!ray) {
  101059. return null;
  101060. }
  101061. // Calculate angle between plane normal and ray
  101062. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  101063. // Correct if ray is casted from oposite side
  101064. if (angle > Math.PI / 2) {
  101065. angle = Math.PI - angle;
  101066. }
  101067. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  101068. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  101069. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  101070. // Invert ray direction along the towards object axis
  101071. this._tmpVector.copyFrom(ray.direction);
  101072. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  101073. this._alternatePickedPoint.normalize();
  101074. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  101075. this._tmpVector.addInPlace(this._alternatePickedPoint);
  101076. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  101077. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  101078. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  101079. this._alternatePickedPoint.addInPlace(this._tmpVector);
  101080. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  101081. return this._alternatePickedPoint;
  101082. }
  101083. else {
  101084. return null;
  101085. }
  101086. }
  101087. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  101088. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  101089. return pickResult.pickedPoint;
  101090. }
  101091. else {
  101092. return null;
  101093. }
  101094. };
  101095. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  101096. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  101097. this._pointA.copyFrom(dragPlanePosition);
  101098. if (this._options.dragAxis) {
  101099. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  101100. // Calculate plane normal in direction of camera but perpendicular to drag axis
  101101. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  101102. ray.origin.subtractToRef(this._pointA, this._pointC);
  101103. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  101104. // Get perpendicular line from direction to camera and drag axis
  101105. this._pointB.subtractToRef(this._pointA, this._lineA);
  101106. this._pointC.subtractToRef(this._pointA, this._lineB);
  101107. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  101108. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  101109. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  101110. this._lookAt.normalize();
  101111. this._dragPlane.position.copyFrom(this._pointA);
  101112. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  101113. this._dragPlane.lookAt(this._lookAt);
  101114. }
  101115. else if (this._options.dragPlaneNormal) {
  101116. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  101117. this._dragPlane.position.copyFrom(this._pointA);
  101118. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  101119. this._dragPlane.lookAt(this._lookAt);
  101120. }
  101121. else {
  101122. this._dragPlane.position.copyFrom(this._pointA);
  101123. this._dragPlane.lookAt(ray.origin);
  101124. }
  101125. this._dragPlane.computeWorldMatrix(true);
  101126. };
  101127. /**
  101128. * Detaches the behavior from the mesh
  101129. */
  101130. PointerDragBehavior.prototype.detach = function () {
  101131. if (this._pointerObserver) {
  101132. this._scene.onPointerObservable.remove(this._pointerObserver);
  101133. }
  101134. if (this._beforeRenderObserver) {
  101135. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101136. }
  101137. };
  101138. PointerDragBehavior._AnyMouseID = -2;
  101139. return PointerDragBehavior;
  101140. }());
  101141. BABYLON.PointerDragBehavior = PointerDragBehavior;
  101142. })(BABYLON || (BABYLON = {}));
  101143. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  101144. var BABYLON;
  101145. (function (BABYLON) {
  101146. /**
  101147. * A behavior that when attached to a mesh will allow the mesh to be scaled
  101148. */
  101149. var MultiPointerScaleBehavior = /** @class */ (function () {
  101150. /**
  101151. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  101152. */
  101153. function MultiPointerScaleBehavior() {
  101154. this._startDistance = 0;
  101155. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  101156. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  101157. this._sceneRenderObserver = null;
  101158. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  101159. this._dragBehaviorA.moveAttached = false;
  101160. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  101161. this._dragBehaviorB.moveAttached = false;
  101162. }
  101163. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  101164. /**
  101165. * The name of the behavior
  101166. */
  101167. get: function () {
  101168. return "MultiPointerScale";
  101169. },
  101170. enumerable: true,
  101171. configurable: true
  101172. });
  101173. /**
  101174. * Initializes the behavior
  101175. */
  101176. MultiPointerScaleBehavior.prototype.init = function () { };
  101177. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  101178. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  101179. };
  101180. /**
  101181. * Attaches the scale behavior the passed in mesh
  101182. * @param ownerNode The mesh that will be scaled around once attached
  101183. */
  101184. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  101185. var _this = this;
  101186. this._ownerNode = ownerNode;
  101187. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  101188. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  101189. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101190. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101191. _this._dragBehaviorA.releaseDrag();
  101192. }
  101193. else {
  101194. _this._initialScale.copyFrom(ownerNode.scaling);
  101195. _this._startDistance = _this._getCurrentDistance();
  101196. }
  101197. }
  101198. });
  101199. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  101200. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101201. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101202. _this._dragBehaviorB.releaseDrag();
  101203. }
  101204. else {
  101205. _this._initialScale.copyFrom(ownerNode.scaling);
  101206. _this._startDistance = _this._getCurrentDistance();
  101207. }
  101208. }
  101209. });
  101210. // Once both drag behaviors are active scale based on the distance between the two pointers
  101211. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101212. behavior.onDragObservable.add(function () {
  101213. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101214. var ratio = _this._getCurrentDistance() / _this._startDistance;
  101215. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  101216. }
  101217. });
  101218. });
  101219. ownerNode.addBehavior(this._dragBehaviorA);
  101220. ownerNode.addBehavior(this._dragBehaviorB);
  101221. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101222. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101223. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101224. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  101225. if (change.length() > 0.01) {
  101226. ownerNode.scaling.addInPlace(change);
  101227. }
  101228. }
  101229. });
  101230. };
  101231. /**
  101232. * Detaches the behavior from the mesh
  101233. */
  101234. MultiPointerScaleBehavior.prototype.detach = function () {
  101235. var _this = this;
  101236. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101237. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101238. behavior.onDragStartObservable.clear();
  101239. behavior.onDragObservable.clear();
  101240. _this._ownerNode.removeBehavior(behavior);
  101241. });
  101242. };
  101243. return MultiPointerScaleBehavior;
  101244. }());
  101245. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  101246. })(BABYLON || (BABYLON = {}));
  101247. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  101248. var BABYLON;
  101249. (function (BABYLON) {
  101250. /**
  101251. * 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
  101252. */
  101253. var SixDofDragBehavior = /** @class */ (function () {
  101254. /**
  101255. * Instantiates 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
  101256. */
  101257. function SixDofDragBehavior() {
  101258. this._sceneRenderObserver = null;
  101259. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101260. this._moving = false;
  101261. this._startingOrientation = new BABYLON.Quaternion();
  101262. /**
  101263. * 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: 3)
  101264. */
  101265. this.zDragFactor = 3;
  101266. /**
  101267. * If the behavior is currently in a dragging state
  101268. */
  101269. this.dragging = false;
  101270. /**
  101271. * 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)
  101272. */
  101273. this.dragDeltaRatio = 0.2;
  101274. /**
  101275. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101276. */
  101277. this.currentDraggingPointerID = -1;
  101278. /**
  101279. * If camera controls should be detached during the drag
  101280. */
  101281. this.detachCameraControls = true;
  101282. /**
  101283. * Fires each time a drag starts
  101284. */
  101285. this.onDragStartObservable = new BABYLON.Observable();
  101286. /**
  101287. * Fires each time a drag ends (eg. mouse release after drag)
  101288. */
  101289. this.onDragEndObservable = new BABYLON.Observable();
  101290. }
  101291. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  101292. /**
  101293. * The name of the behavior
  101294. */
  101295. get: function () {
  101296. return "SixDofDrag";
  101297. },
  101298. enumerable: true,
  101299. configurable: true
  101300. });
  101301. /**
  101302. * Initializes the behavior
  101303. */
  101304. SixDofDragBehavior.prototype.init = function () { };
  101305. /**
  101306. * Attaches the scale behavior the passed in mesh
  101307. * @param ownerNode The mesh that will be scaled around once attached
  101308. */
  101309. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  101310. var _this = this;
  101311. this._ownerNode = ownerNode;
  101312. this._scene = this._ownerNode.getScene();
  101313. if (!SixDofDragBehavior._virtualScene) {
  101314. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  101315. SixDofDragBehavior._virtualScene.detachControl();
  101316. this._scene.getEngine().scenes.pop();
  101317. }
  101318. var pickedMesh = null;
  101319. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  101320. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  101321. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101322. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  101323. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101324. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  101325. var pickPredicate = function (m) {
  101326. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  101327. };
  101328. var attachedElement = null;
  101329. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101330. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101331. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101332. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101333. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101334. }
  101335. pickedMesh = _this._ownerNode;
  101336. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101337. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101338. // Set position and orientation of the controller
  101339. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101340. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101341. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  101342. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101343. pickedMesh.computeWorldMatrix();
  101344. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  101345. if (!pickedMesh.rotationQuaternion) {
  101346. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  101347. }
  101348. var oldParent = pickedMesh.parent;
  101349. pickedMesh.setParent(null);
  101350. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  101351. pickedMesh.setParent(oldParent);
  101352. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101353. // Update state
  101354. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101355. _this.dragging = true;
  101356. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  101357. // Detatch camera controls
  101358. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101359. if (_this._scene.activeCamera.inputs.attachedElement) {
  101360. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  101361. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  101362. }
  101363. else {
  101364. attachedElement = null;
  101365. }
  101366. }
  101367. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101368. _this.onDragStartObservable.notifyObservers({});
  101369. }
  101370. }
  101371. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101372. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101373. _this.dragging = false;
  101374. _this._moving = false;
  101375. _this.currentDraggingPointerID = -1;
  101376. pickedMesh = null;
  101377. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101378. // Reattach camera controls
  101379. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101380. _this._scene.activeCamera.attachControl(attachedElement, true);
  101381. }
  101382. _this.onDragEndObservable.notifyObservers({});
  101383. }
  101384. }
  101385. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101386. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  101387. var zDragFactor = _this.zDragFactor;
  101388. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101389. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101390. zDragFactor = 0;
  101391. }
  101392. // Calculate controller drag distance in controller space
  101393. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  101394. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101395. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  101396. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101397. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  101398. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  101399. if (_this._virtualDragMesh.position.z < 0) {
  101400. _this._virtualDragMesh.position.z = 0;
  101401. }
  101402. // Update the controller position
  101403. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101404. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101405. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101406. // Move the virtualObjectsPosition into the picked mesh's space if needed
  101407. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101408. if (pickedMesh.parent) {
  101409. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  101410. }
  101411. if (!_this._moving) {
  101412. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  101413. }
  101414. _this._moving = true;
  101415. }
  101416. }
  101417. });
  101418. var tmpQuaternion = new BABYLON.Quaternion();
  101419. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101420. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101421. if (_this.dragging && _this._moving && pickedMesh) {
  101422. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101423. // Slowly move mesh to avoid jitter
  101424. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  101425. // Get change in rotation
  101426. tmpQuaternion.copyFrom(_this._startingOrientation);
  101427. tmpQuaternion.x = -tmpQuaternion.x;
  101428. tmpQuaternion.y = -tmpQuaternion.y;
  101429. tmpQuaternion.z = -tmpQuaternion.z;
  101430. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  101431. // Convert change in rotation to only y axis rotation
  101432. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  101433. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  101434. // Slowly move mesh to avoid jitter
  101435. var oldParent = pickedMesh.parent;
  101436. pickedMesh.setParent(null);
  101437. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  101438. pickedMesh.setParent(oldParent);
  101439. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101440. }
  101441. });
  101442. };
  101443. /**
  101444. * Detaches the behavior from the mesh
  101445. */
  101446. SixDofDragBehavior.prototype.detach = function () {
  101447. if (this._scene) {
  101448. this._scene.onPointerObservable.remove(this._pointerObserver);
  101449. }
  101450. if (this._ownerNode) {
  101451. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101452. }
  101453. if (this._virtualOriginMesh) {
  101454. this._virtualOriginMesh.dispose();
  101455. }
  101456. if (this._virtualDragMesh) {
  101457. this._virtualDragMesh.dispose();
  101458. }
  101459. this.onDragEndObservable.clear();
  101460. this.onDragStartObservable.clear();
  101461. };
  101462. return SixDofDragBehavior;
  101463. }());
  101464. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  101465. })(BABYLON || (BABYLON = {}));
  101466. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  101467. var BABYLON;
  101468. (function (BABYLON) {
  101469. /**
  101470. * @hidden
  101471. */
  101472. var FaceDirectionInfo = /** @class */ (function () {
  101473. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  101474. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  101475. if (diff === void 0) { diff = 0; }
  101476. if (ignore === void 0) { ignore = false; }
  101477. this.direction = direction;
  101478. this.rotatedDirection = rotatedDirection;
  101479. this.diff = diff;
  101480. this.ignore = ignore;
  101481. }
  101482. return FaceDirectionInfo;
  101483. }());
  101484. /**
  101485. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  101486. */
  101487. var AttachToBoxBehavior = /** @class */ (function () {
  101488. /**
  101489. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  101490. * @param ui The transform node that should be attched to the mesh
  101491. */
  101492. function AttachToBoxBehavior(ui) {
  101493. this.ui = ui;
  101494. /**
  101495. * The name of the behavior
  101496. */
  101497. this.name = "AttachToBoxBehavior";
  101498. /**
  101499. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  101500. */
  101501. this.distanceAwayFromFace = 0.15;
  101502. /**
  101503. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  101504. */
  101505. this.distanceAwayFromBottomOfFace = 0.15;
  101506. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  101507. this._tmpMatrix = new BABYLON.Matrix();
  101508. this._tmpVector = new BABYLON.Vector3();
  101509. this._zeroVector = BABYLON.Vector3.Zero();
  101510. this._lookAtTmpMatrix = new BABYLON.Matrix();
  101511. /* Does nothing */
  101512. }
  101513. /**
  101514. * Initializes the behavior
  101515. */
  101516. AttachToBoxBehavior.prototype.init = function () {
  101517. /* Does nothing */
  101518. };
  101519. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  101520. var _this = this;
  101521. // Go over each face and calculate the angle between the face's normal and targetDirection
  101522. this._faceVectors.forEach(function (v) {
  101523. if (!_this._target.rotationQuaternion) {
  101524. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  101525. }
  101526. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  101527. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  101528. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  101529. });
  101530. // Return the face information of the one with the normal closeset to target direction
  101531. return this._faceVectors.reduce(function (min, p) {
  101532. if (min.ignore) {
  101533. return p;
  101534. }
  101535. else if (p.ignore) {
  101536. return min;
  101537. }
  101538. else {
  101539. return min.diff < p.diff ? min : p;
  101540. }
  101541. }, this._faceVectors[0]);
  101542. };
  101543. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  101544. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  101545. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  101546. this._lookAtTmpMatrix.invert();
  101547. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  101548. };
  101549. /**
  101550. * Attaches the AttachToBoxBehavior to the passed in mesh
  101551. * @param target The mesh that the specified node will be attached to
  101552. */
  101553. AttachToBoxBehavior.prototype.attach = function (target) {
  101554. var _this = this;
  101555. this._target = target;
  101556. this._scene = this._target.getScene();
  101557. // Every frame, update the app bars position
  101558. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101559. if (!_this._scene.activeCamera) {
  101560. return;
  101561. }
  101562. // Find the face closest to the cameras position
  101563. var cameraPos = _this._scene.activeCamera.position;
  101564. if (_this._scene.activeCamera.devicePosition) {
  101565. cameraPos = _this._scene.activeCamera.devicePosition;
  101566. }
  101567. var facing = _this._closestFace(cameraPos.subtract(target.position));
  101568. if (_this._scene.activeCamera.leftCamera) {
  101569. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101570. }
  101571. else {
  101572. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101573. }
  101574. // Get camera up direction
  101575. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  101576. // Ignore faces to not select a parrelel face for the up vector of the UI
  101577. _this._faceVectors.forEach(function (v) {
  101578. if (facing.direction.x && v.direction.x) {
  101579. v.ignore = true;
  101580. }
  101581. if (facing.direction.y && v.direction.y) {
  101582. v.ignore = true;
  101583. }
  101584. if (facing.direction.z && v.direction.z) {
  101585. v.ignore = true;
  101586. }
  101587. });
  101588. var facingUp = _this._closestFace(_this._tmpVector);
  101589. // Unignore faces
  101590. _this._faceVectors.forEach(function (v) {
  101591. v.ignore = false;
  101592. });
  101593. // Position the app bar on that face
  101594. _this.ui.position.copyFrom(target.position);
  101595. if (facing.direction.x) {
  101596. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101597. _this.ui.position.addInPlace(_this._tmpVector);
  101598. }
  101599. if (facing.direction.y) {
  101600. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101601. _this.ui.position.addInPlace(_this._tmpVector);
  101602. }
  101603. if (facing.direction.z) {
  101604. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101605. _this.ui.position.addInPlace(_this._tmpVector);
  101606. }
  101607. // Rotate to be oriented properly to the camera
  101608. if (!_this.ui.rotationQuaternion) {
  101609. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  101610. }
  101611. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  101612. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  101613. // Place ui the correct distance from the bottom of the mesh
  101614. if (facingUp.direction.x) {
  101615. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  101616. }
  101617. if (facingUp.direction.y) {
  101618. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  101619. }
  101620. if (facingUp.direction.z) {
  101621. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  101622. }
  101623. _this.ui.position.addInPlace(_this._tmpVector);
  101624. });
  101625. };
  101626. /**
  101627. * Detaches the behavior from the mesh
  101628. */
  101629. AttachToBoxBehavior.prototype.detach = function () {
  101630. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  101631. };
  101632. return AttachToBoxBehavior;
  101633. }());
  101634. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  101635. })(BABYLON || (BABYLON = {}));
  101636. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  101637. var BABYLON;
  101638. (function (BABYLON) {
  101639. /**
  101640. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  101641. */
  101642. var FadeInOutBehavior = /** @class */ (function () {
  101643. /**
  101644. * Instatiates the FadeInOutBehavior
  101645. */
  101646. function FadeInOutBehavior() {
  101647. var _this = this;
  101648. /**
  101649. * Time in milliseconds to delay before fading in (Default: 0)
  101650. */
  101651. this.delay = 0;
  101652. /**
  101653. * Time in milliseconds for the mesh to fade in (Default: 300)
  101654. */
  101655. this.fadeInTime = 300;
  101656. this._millisecondsPerFrame = 1000 / 60;
  101657. this._hovered = false;
  101658. this._hoverValue = 0;
  101659. this._ownerNode = null;
  101660. this._update = function () {
  101661. if (_this._ownerNode) {
  101662. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  101663. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  101664. if (_this._ownerNode.visibility > 1) {
  101665. _this._setAllVisibility(_this._ownerNode, 1);
  101666. _this._hoverValue = _this.fadeInTime + _this.delay;
  101667. return;
  101668. }
  101669. else if (_this._ownerNode.visibility < 0) {
  101670. _this._setAllVisibility(_this._ownerNode, 0);
  101671. if (_this._hoverValue < 0) {
  101672. _this._hoverValue = 0;
  101673. return;
  101674. }
  101675. }
  101676. setTimeout(_this._update, _this._millisecondsPerFrame);
  101677. }
  101678. };
  101679. }
  101680. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  101681. /**
  101682. * The name of the behavior
  101683. */
  101684. get: function () {
  101685. return "FadeInOut";
  101686. },
  101687. enumerable: true,
  101688. configurable: true
  101689. });
  101690. /**
  101691. * Initializes the behavior
  101692. */
  101693. FadeInOutBehavior.prototype.init = function () {
  101694. };
  101695. /**
  101696. * Attaches the fade behavior on the passed in mesh
  101697. * @param ownerNode The mesh that will be faded in/out once attached
  101698. */
  101699. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  101700. this._ownerNode = ownerNode;
  101701. this._setAllVisibility(this._ownerNode, 0);
  101702. };
  101703. /**
  101704. * Detaches the behavior from the mesh
  101705. */
  101706. FadeInOutBehavior.prototype.detach = function () {
  101707. this._ownerNode = null;
  101708. };
  101709. /**
  101710. * Triggers the mesh to begin fading in or out
  101711. * @param value if the object should fade in or out (true to fade in)
  101712. */
  101713. FadeInOutBehavior.prototype.fadeIn = function (value) {
  101714. this._hovered = value;
  101715. this._update();
  101716. };
  101717. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  101718. var _this = this;
  101719. mesh.visibility = value;
  101720. mesh.getChildMeshes().forEach(function (c) {
  101721. _this._setAllVisibility(c, value);
  101722. });
  101723. };
  101724. return FadeInOutBehavior;
  101725. }());
  101726. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  101727. })(BABYLON || (BABYLON = {}));
  101728. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  101729. var BABYLON;
  101730. (function (BABYLON) {
  101731. /**
  101732. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  101733. */
  101734. var Gizmo = /** @class */ (function () {
  101735. /**
  101736. * Creates a gizmo
  101737. * @param gizmoLayer The utility layer the gizmo will be added to
  101738. */
  101739. function Gizmo(
  101740. /** The utility layer the gizmo will be added to */
  101741. gizmoLayer) {
  101742. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101743. var _this = this;
  101744. this.gizmoLayer = gizmoLayer;
  101745. /**
  101746. * Ratio for the scale of the gizmo (Default: 1)
  101747. */
  101748. this.scaleRatio = 1;
  101749. this._tmpMatrix = new BABYLON.Matrix();
  101750. /**
  101751. * If a custom mesh has been set (Default: false)
  101752. */
  101753. this._customMeshSet = false;
  101754. /**
  101755. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  101756. */
  101757. this.updateGizmoRotationToMatchAttachedMesh = true;
  101758. /**
  101759. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  101760. */
  101761. this.updateGizmoPositionToMatchAttachedMesh = true;
  101762. /**
  101763. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  101764. */
  101765. this._updateScale = true;
  101766. this._interactionsEnabled = true;
  101767. this._tempVector = new BABYLON.Vector3();
  101768. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  101769. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  101770. _this._update();
  101771. });
  101772. this.attachedMesh = null;
  101773. }
  101774. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  101775. /**
  101776. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  101777. * * When set, interactions will be enabled
  101778. */
  101779. get: function () {
  101780. return this._attachedMesh;
  101781. },
  101782. set: function (value) {
  101783. this._attachedMesh = value;
  101784. this._rootMesh.setEnabled(value ? true : false);
  101785. this._attachedMeshChanged(value);
  101786. },
  101787. enumerable: true,
  101788. configurable: true
  101789. });
  101790. /**
  101791. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  101792. * @param mesh The mesh to replace the default mesh of the gizmo
  101793. */
  101794. Gizmo.prototype.setCustomMesh = function (mesh) {
  101795. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  101796. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  101797. }
  101798. this._rootMesh.getChildMeshes().forEach(function (c) {
  101799. c.dispose();
  101800. });
  101801. mesh.parent = this._rootMesh;
  101802. this._customMeshSet = true;
  101803. };
  101804. Gizmo.prototype._attachedMeshChanged = function (value) {
  101805. };
  101806. /**
  101807. * @hidden
  101808. * Updates the gizmo to match the attached mesh's position/rotation
  101809. */
  101810. Gizmo.prototype._update = function () {
  101811. if (this.attachedMesh) {
  101812. if (this.updateGizmoRotationToMatchAttachedMesh) {
  101813. if (!this._rootMesh.rotationQuaternion) {
  101814. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  101815. }
  101816. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  101817. this._tempVector.copyFrom(this.attachedMesh.scaling);
  101818. if (this.attachedMesh.scaling.x < 0) {
  101819. this.attachedMesh.scaling.x *= -1;
  101820. }
  101821. if (this.attachedMesh.scaling.y < 0) {
  101822. this.attachedMesh.scaling.y *= -1;
  101823. }
  101824. if (this.attachedMesh.scaling.z < 0) {
  101825. this.attachedMesh.scaling.z *= -1;
  101826. }
  101827. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  101828. this.attachedMesh.scaling.copyFrom(this._tempVector);
  101829. this.attachedMesh.computeWorldMatrix();
  101830. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  101831. }
  101832. else if (this._rootMesh.rotationQuaternion) {
  101833. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  101834. }
  101835. if (this.updateGizmoPositionToMatchAttachedMesh) {
  101836. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  101837. }
  101838. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  101839. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  101840. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  101841. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  101842. }
  101843. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  101844. var dist = this._tempVector.length() * this.scaleRatio;
  101845. this._rootMesh.scaling.set(dist, dist, dist);
  101846. }
  101847. }
  101848. };
  101849. /**
  101850. * Disposes of the gizmo
  101851. */
  101852. Gizmo.prototype.dispose = function () {
  101853. this._rootMesh.dispose();
  101854. if (this._beforeRenderObserver) {
  101855. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101856. }
  101857. };
  101858. return Gizmo;
  101859. }());
  101860. BABYLON.Gizmo = Gizmo;
  101861. })(BABYLON || (BABYLON = {}));
  101862. //# sourceMappingURL=babylon.gizmo.js.map
  101863. var BABYLON;
  101864. (function (BABYLON) {
  101865. /**
  101866. * Single axis drag gizmo
  101867. */
  101868. var AxisDragGizmo = /** @class */ (function (_super) {
  101869. __extends(AxisDragGizmo, _super);
  101870. /**
  101871. * Creates an AxisDragGizmo
  101872. * @param gizmoLayer The utility layer the gizmo will be added to
  101873. * @param dragAxis The axis which the gizmo will be able to drag on
  101874. * @param color The color of the gizmo
  101875. */
  101876. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  101877. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101878. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101879. var _this = _super.call(this, gizmoLayer) || this;
  101880. _this._pointerObserver = null;
  101881. /**
  101882. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101883. */
  101884. _this.snapDistance = 0;
  101885. /**
  101886. * Event that fires each time the gizmo snaps to a new location.
  101887. * * snapDistance is the the change in distance
  101888. */
  101889. _this.onSnapObservable = new BABYLON.Observable();
  101890. // Create Material
  101891. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101892. coloredMaterial.disableLighting = true;
  101893. coloredMaterial.emissiveColor = color;
  101894. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101895. hoverMaterial.disableLighting = true;
  101896. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101897. // Build mesh on root node
  101898. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101899. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  101900. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  101901. arrowTail.color = coloredMaterial.emissiveColor;
  101902. arrow.addChild(arrowMesh);
  101903. arrow.addChild(arrowTail);
  101904. // Position arrow pointing in its drag axis
  101905. arrowMesh.scaling.scaleInPlace(0.05);
  101906. arrowMesh.material = coloredMaterial;
  101907. arrowMesh.rotation.x = Math.PI / 2;
  101908. arrowMesh.position.z += 0.3;
  101909. arrowTail.scaling.scaleInPlace(0.26);
  101910. arrowTail.rotation.x = Math.PI / 2;
  101911. arrowTail.material = coloredMaterial;
  101912. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  101913. arrow.scaling.scaleInPlace(1 / 3);
  101914. _this._rootMesh.addChild(arrow);
  101915. var currentSnapDragDistance = 0;
  101916. var tmpVector = new BABYLON.Vector3();
  101917. var tmpSnapEvent = { snapDistance: 0 };
  101918. // Add drag behavior to handle events when the gizmo is dragged
  101919. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101920. _this.dragBehavior.moveAttached = false;
  101921. _this._rootMesh.addBehavior(_this.dragBehavior);
  101922. var localDelta = new BABYLON.Vector3();
  101923. var tmpMatrix = new BABYLON.Matrix();
  101924. _this.dragBehavior.onDragObservable.add(function (event) {
  101925. if (_this.attachedMesh) {
  101926. // Convert delta to local translation if it has a parent
  101927. if (_this.attachedMesh.parent) {
  101928. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  101929. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  101930. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  101931. }
  101932. else {
  101933. localDelta.copyFrom(event.delta);
  101934. }
  101935. // Snapping logic
  101936. if (_this.snapDistance == 0) {
  101937. _this.attachedMesh.position.addInPlace(localDelta);
  101938. }
  101939. else {
  101940. currentSnapDragDistance += event.dragDistance;
  101941. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  101942. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  101943. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  101944. localDelta.normalizeToRef(tmpVector);
  101945. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  101946. _this.attachedMesh.position.addInPlace(tmpVector);
  101947. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  101948. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  101949. }
  101950. }
  101951. }
  101952. });
  101953. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101954. if (_this._customMeshSet) {
  101955. return;
  101956. }
  101957. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  101958. var material = isHovered ? hoverMaterial : coloredMaterial;
  101959. _this._rootMesh.getChildMeshes().forEach(function (m) {
  101960. m.material = material;
  101961. if (m.color) {
  101962. m.color = material.emissiveColor;
  101963. }
  101964. });
  101965. });
  101966. return _this;
  101967. }
  101968. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  101969. if (this.dragBehavior) {
  101970. this.dragBehavior.enabled = value ? true : false;
  101971. }
  101972. };
  101973. /**
  101974. * Disposes of the gizmo
  101975. */
  101976. AxisDragGizmo.prototype.dispose = function () {
  101977. this.onSnapObservable.clear();
  101978. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101979. this.dragBehavior.detach();
  101980. _super.prototype.dispose.call(this);
  101981. };
  101982. return AxisDragGizmo;
  101983. }(BABYLON.Gizmo));
  101984. BABYLON.AxisDragGizmo = AxisDragGizmo;
  101985. })(BABYLON || (BABYLON = {}));
  101986. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  101987. var BABYLON;
  101988. (function (BABYLON) {
  101989. /**
  101990. * Single axis scale gizmo
  101991. */
  101992. var AxisScaleGizmo = /** @class */ (function (_super) {
  101993. __extends(AxisScaleGizmo, _super);
  101994. /**
  101995. * Creates an AxisScaleGizmo
  101996. * @param gizmoLayer The utility layer the gizmo will be added to
  101997. * @param dragAxis The axis which the gizmo will be able to scale on
  101998. * @param color The color of the gizmo
  101999. */
  102000. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  102001. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102002. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102003. var _this = _super.call(this, gizmoLayer) || this;
  102004. _this._pointerObserver = null;
  102005. /**
  102006. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102007. */
  102008. _this.snapDistance = 0;
  102009. /**
  102010. * Event that fires each time the gizmo snaps to a new location.
  102011. * * snapDistance is the the change in distance
  102012. */
  102013. _this.onSnapObservable = new BABYLON.Observable();
  102014. /**
  102015. * If the scaling operation should be done on all axis (default: false)
  102016. */
  102017. _this.uniformScaling = false;
  102018. // Create Material
  102019. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102020. _this._coloredMaterial.disableLighting = true;
  102021. _this._coloredMaterial.emissiveColor = color;
  102022. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102023. hoverMaterial.disableLighting = true;
  102024. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102025. // Build mesh on root node
  102026. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102027. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  102028. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  102029. arrowTail.color = _this._coloredMaterial.emissiveColor;
  102030. arrow.addChild(arrowMesh);
  102031. arrow.addChild(arrowTail);
  102032. // Position arrow pointing in its drag axis
  102033. arrowMesh.scaling.scaleInPlace(0.1);
  102034. arrowMesh.material = _this._coloredMaterial;
  102035. arrowMesh.rotation.x = Math.PI / 2;
  102036. arrowMesh.position.z += 0.3;
  102037. arrowTail.scaling.scaleInPlace(0.26);
  102038. arrowTail.rotation.x = Math.PI / 2;
  102039. arrowTail.material = _this._coloredMaterial;
  102040. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  102041. _this._rootMesh.addChild(arrow);
  102042. arrow.scaling.scaleInPlace(1 / 3);
  102043. // Add drag behavior to handle events when the gizmo is dragged
  102044. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102045. _this.dragBehavior.moveAttached = false;
  102046. _this._rootMesh.addBehavior(_this.dragBehavior);
  102047. var currentSnapDragDistance = 0;
  102048. var tmpVector = new BABYLON.Vector3();
  102049. var tmpSnapEvent = { snapDistance: 0 };
  102050. _this.dragBehavior.onDragObservable.add(function (event) {
  102051. if (_this.attachedMesh) {
  102052. // Snapping logic
  102053. var snapped = false;
  102054. var dragSteps = 0;
  102055. if (_this.uniformScaling) {
  102056. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  102057. if (tmpVector.y < 0) {
  102058. tmpVector.scaleInPlace(-1);
  102059. }
  102060. }
  102061. else {
  102062. tmpVector.copyFrom(dragAxis);
  102063. }
  102064. if (_this.snapDistance == 0) {
  102065. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  102066. }
  102067. else {
  102068. currentSnapDragDistance += event.dragDistance;
  102069. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102070. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102071. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102072. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  102073. snapped = true;
  102074. }
  102075. else {
  102076. tmpVector.scaleInPlace(0);
  102077. }
  102078. }
  102079. _this.attachedMesh.scaling.addInPlace(tmpVector);
  102080. if (snapped) {
  102081. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102082. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102083. }
  102084. }
  102085. });
  102086. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102087. if (_this._customMeshSet) {
  102088. return;
  102089. }
  102090. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102091. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  102092. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102093. m.material = material;
  102094. if (m.color) {
  102095. m.color = material.emissiveColor;
  102096. }
  102097. });
  102098. });
  102099. return _this;
  102100. }
  102101. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  102102. if (this.dragBehavior) {
  102103. this.dragBehavior.enabled = value ? true : false;
  102104. }
  102105. };
  102106. /**
  102107. * Disposes of the gizmo
  102108. */
  102109. AxisScaleGizmo.prototype.dispose = function () {
  102110. this.onSnapObservable.clear();
  102111. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102112. this.dragBehavior.detach();
  102113. _super.prototype.dispose.call(this);
  102114. };
  102115. /**
  102116. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102117. * @param mesh The mesh to replace the default mesh of the gizmo
  102118. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  102119. */
  102120. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  102121. var _this = this;
  102122. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  102123. _super.prototype.setCustomMesh.call(this, mesh);
  102124. if (useGizmoMaterial) {
  102125. this._rootMesh.getChildMeshes().forEach(function (m) {
  102126. m.material = _this._coloredMaterial;
  102127. if (m.color) {
  102128. m.color = _this._coloredMaterial.emissiveColor;
  102129. }
  102130. });
  102131. this._customMeshSet = false;
  102132. }
  102133. };
  102134. return AxisScaleGizmo;
  102135. }(BABYLON.Gizmo));
  102136. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  102137. })(BABYLON || (BABYLON = {}));
  102138. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  102139. var BABYLON;
  102140. (function (BABYLON) {
  102141. /**
  102142. * Single plane rotation gizmo
  102143. */
  102144. var PlaneRotationGizmo = /** @class */ (function (_super) {
  102145. __extends(PlaneRotationGizmo, _super);
  102146. /**
  102147. * Creates a PlaneRotationGizmo
  102148. * @param gizmoLayer The utility layer the gizmo will be added to
  102149. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  102150. * @param color The color of the gizmo
  102151. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102152. */
  102153. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  102154. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102155. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102156. if (tessellation === void 0) { tessellation = 32; }
  102157. var _this = _super.call(this, gizmoLayer) || this;
  102158. _this._pointerObserver = null;
  102159. /**
  102160. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  102161. */
  102162. _this.snapDistance = 0;
  102163. /**
  102164. * Event that fires each time the gizmo snaps to a new location.
  102165. * * snapDistance is the the change in distance
  102166. */
  102167. _this.onSnapObservable = new BABYLON.Observable();
  102168. // Create Material
  102169. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102170. coloredMaterial.disableLighting = true;
  102171. coloredMaterial.emissiveColor = color;
  102172. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102173. hoverMaterial.disableLighting = true;
  102174. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102175. // Build mesh on root node
  102176. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102177. // Create circle out of lines
  102178. var radius = 0.8;
  102179. var points = new Array();
  102180. for (var i = 0; i < tessellation; i++) {
  102181. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  102182. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  102183. }
  102184. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  102185. rotationMesh.color = coloredMaterial.emissiveColor;
  102186. // Position arrow pointing in its drag axis
  102187. rotationMesh.scaling.scaleInPlace(0.26);
  102188. rotationMesh.material = coloredMaterial;
  102189. rotationMesh.rotation.x = Math.PI / 2;
  102190. parentMesh.addChild(rotationMesh);
  102191. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  102192. _this._rootMesh.addChild(parentMesh);
  102193. parentMesh.scaling.scaleInPlace(1 / 3);
  102194. // Add drag behavior to handle events when the gizmo is dragged
  102195. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  102196. _this.dragBehavior.moveAttached = false;
  102197. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  102198. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  102199. _this._rootMesh.addBehavior(_this.dragBehavior);
  102200. var lastDragPosition = new BABYLON.Vector3();
  102201. _this.dragBehavior.onDragStartObservable.add(function (e) {
  102202. if (_this.attachedMesh) {
  102203. lastDragPosition.copyFrom(e.dragPlanePoint);
  102204. }
  102205. });
  102206. var rotationMatrix = new BABYLON.Matrix();
  102207. var planeNormalTowardsCamera = new BABYLON.Vector3();
  102208. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  102209. var tmpSnapEvent = { snapDistance: 0 };
  102210. var currentSnapDragDistance = 0;
  102211. var tmpMatrix = new BABYLON.Matrix();
  102212. var tmpVector = new BABYLON.Vector3();
  102213. var amountToRotate = new BABYLON.Quaternion();
  102214. _this.dragBehavior.onDragObservable.add(function (event) {
  102215. if (_this.attachedMesh) {
  102216. if (!_this.attachedMesh.rotationQuaternion) {
  102217. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102218. }
  102219. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  102220. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  102221. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  102222. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  102223. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  102224. var angle = Math.atan2(cross.length(), dot);
  102225. planeNormalTowardsCamera.copyFrom(planeNormal);
  102226. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  102227. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102228. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  102229. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  102230. }
  102231. // Flip up vector depending on which side the camera is on
  102232. if (gizmoLayer.utilityLayerScene.activeCamera) {
  102233. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  102234. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  102235. planeNormalTowardsCamera.scaleInPlace(-1);
  102236. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  102237. }
  102238. }
  102239. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  102240. if (halfCircleSide) {
  102241. angle = -angle;
  102242. }
  102243. // Snapping logic
  102244. var snapped = false;
  102245. if (_this.snapDistance != 0) {
  102246. currentSnapDragDistance += angle;
  102247. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102248. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102249. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102250. angle = _this.snapDistance * dragSteps;
  102251. snapped = true;
  102252. }
  102253. else {
  102254. angle = 0;
  102255. }
  102256. }
  102257. // If the mesh has a parent, convert needed world rotation to local rotation
  102258. tmpMatrix.reset();
  102259. if (_this.attachedMesh.parent) {
  102260. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102261. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  102262. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  102263. }
  102264. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  102265. var quaternionCoefficient = Math.sin(angle / 2);
  102266. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  102267. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  102268. if (tmpMatrix.determinant() > 0) {
  102269. amountToRotate.toEulerAnglesToRef(tmpVector);
  102270. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  102271. }
  102272. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102273. // Rotate selected mesh quaternion over fixed axis
  102274. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  102275. }
  102276. else {
  102277. // Rotate selected mesh quaternion over rotated axis
  102278. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  102279. }
  102280. lastDragPosition.copyFrom(event.dragPlanePoint);
  102281. if (snapped) {
  102282. tmpSnapEvent.snapDistance = angle;
  102283. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102284. }
  102285. }
  102286. });
  102287. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102288. if (_this._customMeshSet) {
  102289. return;
  102290. }
  102291. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102292. var material = isHovered ? hoverMaterial : coloredMaterial;
  102293. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102294. m.material = material;
  102295. if (m.color) {
  102296. m.color = material.emissiveColor;
  102297. }
  102298. });
  102299. });
  102300. return _this;
  102301. }
  102302. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  102303. if (this.dragBehavior) {
  102304. this.dragBehavior.enabled = value ? true : false;
  102305. }
  102306. };
  102307. /**
  102308. * Disposes of the gizmo
  102309. */
  102310. PlaneRotationGizmo.prototype.dispose = function () {
  102311. this.onSnapObservable.clear();
  102312. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102313. this.dragBehavior.detach();
  102314. _super.prototype.dispose.call(this);
  102315. };
  102316. return PlaneRotationGizmo;
  102317. }(BABYLON.Gizmo));
  102318. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  102319. })(BABYLON || (BABYLON = {}));
  102320. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  102321. var BABYLON;
  102322. (function (BABYLON) {
  102323. /**
  102324. * Gizmo that enables dragging a mesh along 3 axis
  102325. */
  102326. var PositionGizmo = /** @class */ (function (_super) {
  102327. __extends(PositionGizmo, _super);
  102328. /**
  102329. * Creates a PositionGizmo
  102330. * @param gizmoLayer The utility layer the gizmo will be added to
  102331. */
  102332. function PositionGizmo(gizmoLayer) {
  102333. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102334. var _this = _super.call(this, gizmoLayer) || this;
  102335. /** Fires an event when any of it's sub gizmos are dragged */
  102336. _this.onDragStartObservable = new BABYLON.Observable();
  102337. /** Fires an event when any of it's sub gizmos are released from dragging */
  102338. _this.onDragEndObservable = new BABYLON.Observable();
  102339. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102340. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102341. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102342. // Relay drag events
  102343. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102344. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102345. _this.onDragStartObservable.notifyObservers({});
  102346. });
  102347. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102348. _this.onDragEndObservable.notifyObservers({});
  102349. });
  102350. });
  102351. _this.attachedMesh = null;
  102352. return _this;
  102353. }
  102354. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  102355. set: function (mesh) {
  102356. if (this.xGizmo) {
  102357. this.xGizmo.attachedMesh = mesh;
  102358. this.yGizmo.attachedMesh = mesh;
  102359. this.zGizmo.attachedMesh = mesh;
  102360. }
  102361. },
  102362. enumerable: true,
  102363. configurable: true
  102364. });
  102365. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102366. get: function () {
  102367. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102368. },
  102369. set: function (value) {
  102370. if (this.xGizmo) {
  102371. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102372. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102373. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102374. }
  102375. },
  102376. enumerable: true,
  102377. configurable: true
  102378. });
  102379. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  102380. get: function () {
  102381. return this.xGizmo.snapDistance;
  102382. },
  102383. /**
  102384. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102385. */
  102386. set: function (value) {
  102387. if (this.xGizmo) {
  102388. this.xGizmo.snapDistance = value;
  102389. this.yGizmo.snapDistance = value;
  102390. this.zGizmo.snapDistance = value;
  102391. }
  102392. },
  102393. enumerable: true,
  102394. configurable: true
  102395. });
  102396. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  102397. get: function () {
  102398. return this.xGizmo.scaleRatio;
  102399. },
  102400. /**
  102401. * Ratio for the scale of the gizmo (Default: 1)
  102402. */
  102403. set: function (value) {
  102404. if (this.xGizmo) {
  102405. this.xGizmo.scaleRatio = value;
  102406. this.yGizmo.scaleRatio = value;
  102407. this.zGizmo.scaleRatio = value;
  102408. }
  102409. },
  102410. enumerable: true,
  102411. configurable: true
  102412. });
  102413. /**
  102414. * Disposes of the gizmo
  102415. */
  102416. PositionGizmo.prototype.dispose = function () {
  102417. this.xGizmo.dispose();
  102418. this.yGizmo.dispose();
  102419. this.zGizmo.dispose();
  102420. this.onDragStartObservable.clear();
  102421. this.onDragEndObservable.clear();
  102422. };
  102423. /**
  102424. * CustomMeshes are not supported by this gizmo
  102425. * @param mesh The mesh to replace the default mesh of the gizmo
  102426. */
  102427. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  102428. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  102429. };
  102430. return PositionGizmo;
  102431. }(BABYLON.Gizmo));
  102432. BABYLON.PositionGizmo = PositionGizmo;
  102433. })(BABYLON || (BABYLON = {}));
  102434. //# sourceMappingURL=babylon.positionGizmo.js.map
  102435. var BABYLON;
  102436. (function (BABYLON) {
  102437. /**
  102438. * Gizmo that enables rotating a mesh along 3 axis
  102439. */
  102440. var RotationGizmo = /** @class */ (function (_super) {
  102441. __extends(RotationGizmo, _super);
  102442. /**
  102443. * Creates a RotationGizmo
  102444. * @param gizmoLayer The utility layer the gizmo will be added to
  102445. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102446. */
  102447. function RotationGizmo(gizmoLayer, tessellation) {
  102448. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102449. if (tessellation === void 0) { tessellation = 32; }
  102450. var _this = _super.call(this, gizmoLayer) || this;
  102451. /** Fires an event when any of it's sub gizmos are dragged */
  102452. _this.onDragStartObservable = new BABYLON.Observable();
  102453. /** Fires an event when any of it's sub gizmos are released from dragging */
  102454. _this.onDragEndObservable = new BABYLON.Observable();
  102455. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  102456. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  102457. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  102458. // Relay drag events
  102459. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102460. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102461. _this.onDragStartObservable.notifyObservers({});
  102462. });
  102463. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102464. _this.onDragEndObservable.notifyObservers({});
  102465. });
  102466. });
  102467. _this.attachedMesh = null;
  102468. return _this;
  102469. }
  102470. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  102471. set: function (mesh) {
  102472. if (this.xGizmo) {
  102473. this.xGizmo.attachedMesh = mesh;
  102474. this.yGizmo.attachedMesh = mesh;
  102475. this.zGizmo.attachedMesh = mesh;
  102476. }
  102477. },
  102478. enumerable: true,
  102479. configurable: true
  102480. });
  102481. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102482. get: function () {
  102483. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102484. },
  102485. set: function (value) {
  102486. if (this.xGizmo) {
  102487. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102488. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102489. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102490. }
  102491. },
  102492. enumerable: true,
  102493. configurable: true
  102494. });
  102495. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  102496. get: function () {
  102497. return this.xGizmo.snapDistance;
  102498. },
  102499. /**
  102500. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102501. */
  102502. set: function (value) {
  102503. if (this.xGizmo) {
  102504. this.xGizmo.snapDistance = value;
  102505. this.yGizmo.snapDistance = value;
  102506. this.zGizmo.snapDistance = value;
  102507. }
  102508. },
  102509. enumerable: true,
  102510. configurable: true
  102511. });
  102512. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  102513. get: function () {
  102514. return this.xGizmo.scaleRatio;
  102515. },
  102516. /**
  102517. * Ratio for the scale of the gizmo (Default: 1)
  102518. */
  102519. set: function (value) {
  102520. if (this.xGizmo) {
  102521. this.xGizmo.scaleRatio = value;
  102522. this.yGizmo.scaleRatio = value;
  102523. this.zGizmo.scaleRatio = value;
  102524. }
  102525. },
  102526. enumerable: true,
  102527. configurable: true
  102528. });
  102529. /**
  102530. * Disposes of the gizmo
  102531. */
  102532. RotationGizmo.prototype.dispose = function () {
  102533. this.xGizmo.dispose();
  102534. this.yGizmo.dispose();
  102535. this.zGizmo.dispose();
  102536. this.onDragStartObservable.clear();
  102537. this.onDragEndObservable.clear();
  102538. };
  102539. /**
  102540. * CustomMeshes are not supported by this gizmo
  102541. * @param mesh The mesh to replace the default mesh of the gizmo
  102542. */
  102543. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  102544. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  102545. };
  102546. return RotationGizmo;
  102547. }(BABYLON.Gizmo));
  102548. BABYLON.RotationGizmo = RotationGizmo;
  102549. })(BABYLON || (BABYLON = {}));
  102550. //# sourceMappingURL=babylon.rotationGizmo.js.map
  102551. var BABYLON;
  102552. (function (BABYLON) {
  102553. /**
  102554. * Gizmo that enables scaling a mesh along 3 axis
  102555. */
  102556. var ScaleGizmo = /** @class */ (function (_super) {
  102557. __extends(ScaleGizmo, _super);
  102558. /**
  102559. * Creates a ScaleGizmo
  102560. * @param gizmoLayer The utility layer the gizmo will be added to
  102561. */
  102562. function ScaleGizmo(gizmoLayer) {
  102563. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102564. var _this = _super.call(this, gizmoLayer) || this;
  102565. /** Fires an event when any of it's sub gizmos are dragged */
  102566. _this.onDragStartObservable = new BABYLON.Observable();
  102567. /** Fires an event when any of it's sub gizmos are released from dragging */
  102568. _this.onDragEndObservable = new BABYLON.Observable();
  102569. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102570. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102571. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102572. // Create uniform scale gizmo
  102573. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  102574. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  102575. _this.uniformScaleGizmo.uniformScaling = true;
  102576. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102577. uniformScalingMesh.scaling.scaleInPlace(0.02);
  102578. uniformScalingMesh.visibility = 0;
  102579. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102580. octahedron.scaling.scaleInPlace(0.007);
  102581. uniformScalingMesh.addChild(octahedron);
  102582. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  102583. // Relay drag events
  102584. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  102585. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102586. _this.onDragStartObservable.notifyObservers({});
  102587. });
  102588. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102589. _this.onDragEndObservable.notifyObservers({});
  102590. });
  102591. });
  102592. _this.attachedMesh = null;
  102593. return _this;
  102594. }
  102595. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  102596. set: function (mesh) {
  102597. if (this.xGizmo) {
  102598. this.xGizmo.attachedMesh = mesh;
  102599. this.yGizmo.attachedMesh = mesh;
  102600. this.zGizmo.attachedMesh = mesh;
  102601. this.uniformScaleGizmo.attachedMesh = mesh;
  102602. }
  102603. },
  102604. enumerable: true,
  102605. configurable: true
  102606. });
  102607. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102608. get: function () {
  102609. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102610. },
  102611. set: function (value) {
  102612. if (!value) {
  102613. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  102614. }
  102615. if (this.xGizmo) {
  102616. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102617. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102618. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102619. }
  102620. },
  102621. enumerable: true,
  102622. configurable: true
  102623. });
  102624. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  102625. get: function () {
  102626. return this.xGizmo.snapDistance;
  102627. },
  102628. /**
  102629. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102630. */
  102631. set: function (value) {
  102632. if (this.xGizmo) {
  102633. this.xGizmo.snapDistance = value;
  102634. this.yGizmo.snapDistance = value;
  102635. this.zGizmo.snapDistance = value;
  102636. this.uniformScaleGizmo.snapDistance = value;
  102637. }
  102638. },
  102639. enumerable: true,
  102640. configurable: true
  102641. });
  102642. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  102643. get: function () {
  102644. return this.xGizmo.scaleRatio;
  102645. },
  102646. /**
  102647. * Ratio for the scale of the gizmo (Default: 1)
  102648. */
  102649. set: function (value) {
  102650. if (this.xGizmo) {
  102651. this.xGizmo.scaleRatio = value;
  102652. this.yGizmo.scaleRatio = value;
  102653. this.zGizmo.scaleRatio = value;
  102654. this.uniformScaleGizmo.scaleRatio = value;
  102655. }
  102656. },
  102657. enumerable: true,
  102658. configurable: true
  102659. });
  102660. /**
  102661. * Disposes of the gizmo
  102662. */
  102663. ScaleGizmo.prototype.dispose = function () {
  102664. this.xGizmo.dispose();
  102665. this.yGizmo.dispose();
  102666. this.zGizmo.dispose();
  102667. this.uniformScaleGizmo.dispose();
  102668. this.onDragStartObservable.clear();
  102669. this.onDragEndObservable.clear();
  102670. };
  102671. return ScaleGizmo;
  102672. }(BABYLON.Gizmo));
  102673. BABYLON.ScaleGizmo = ScaleGizmo;
  102674. })(BABYLON || (BABYLON = {}));
  102675. //# sourceMappingURL=babylon.scaleGizmo.js.map
  102676. var BABYLON;
  102677. (function (BABYLON) {
  102678. /**
  102679. * Bounding box gizmo
  102680. */
  102681. var BoundingBoxGizmo = /** @class */ (function (_super) {
  102682. __extends(BoundingBoxGizmo, _super);
  102683. /**
  102684. * Creates an BoundingBoxGizmo
  102685. * @param gizmoLayer The utility layer the gizmo will be added to
  102686. * @param color The color of the gizmo
  102687. */
  102688. function BoundingBoxGizmo(color, gizmoLayer) {
  102689. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102690. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  102691. var _this = _super.call(this, gizmoLayer) || this;
  102692. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  102693. _this._renderObserver = null;
  102694. _this._pointerObserver = null;
  102695. _this._scaleDragSpeed = 0.2;
  102696. _this._tmpQuaternion = new BABYLON.Quaternion();
  102697. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  102698. _this._tmpRotationMatrix = new BABYLON.Matrix();
  102699. /**
  102700. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  102701. */
  102702. _this.ignoreChildren = false;
  102703. /**
  102704. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  102705. */
  102706. _this.includeChildPredicate = null;
  102707. /**
  102708. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  102709. */
  102710. _this.rotationSphereSize = 0.1;
  102711. /**
  102712. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  102713. */
  102714. _this.scaleBoxSize = 0.1;
  102715. /**
  102716. * 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)
  102717. */
  102718. _this.fixedDragMeshScreenSize = false;
  102719. /**
  102720. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  102721. */
  102722. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  102723. /**
  102724. * Fired when a rotation sphere or scale box is dragged
  102725. */
  102726. _this.onDragStartObservable = new BABYLON.Observable();
  102727. /**
  102728. * Fired when a scale box is dragged
  102729. */
  102730. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  102731. /**
  102732. * Fired when a scale box drag is ended
  102733. */
  102734. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  102735. /**
  102736. * Fired when a rotation sphere is dragged
  102737. */
  102738. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  102739. /**
  102740. * Fired when a rotation sphere drag is ended
  102741. */
  102742. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  102743. /**
  102744. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  102745. */
  102746. _this.scalePivot = null;
  102747. _this._existingMeshScale = new BABYLON.Vector3();
  102748. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  102749. _this._updateScale = false;
  102750. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  102751. // Create Materials
  102752. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102753. coloredMaterial.disableLighting = true;
  102754. coloredMaterial.emissiveColor = color;
  102755. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102756. hoverColoredMaterial.disableLighting = true;
  102757. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102758. // Build bounding box out of lines
  102759. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102760. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  102761. var lines = [];
  102762. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  102763. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  102764. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  102765. 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));
  102766. 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));
  102767. 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));
  102768. 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));
  102769. 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));
  102770. 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));
  102771. 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));
  102772. 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));
  102773. 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));
  102774. lines.forEach(function (l) {
  102775. l.color = color;
  102776. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  102777. l.isPickable = false;
  102778. _this._lineBoundingBox.addChild(l);
  102779. });
  102780. _this._rootMesh.addChild(_this._lineBoundingBox);
  102781. // Create rotation spheres
  102782. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102783. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  102784. var _loop_1 = function (i_1) {
  102785. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  102786. sphere.rotationQuaternion = new BABYLON.Quaternion();
  102787. sphere.material = coloredMaterial;
  102788. // Drag behavior
  102789. _dragBehavior = new BABYLON.PointerDragBehavior({});
  102790. _dragBehavior.moveAttached = false;
  102791. _dragBehavior.updateDragPlane = false;
  102792. sphere.addBehavior(_dragBehavior);
  102793. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  102794. var totalTurnAmountOfDrag = 0;
  102795. _dragBehavior.onDragStartObservable.add(function (event) {
  102796. startingTurnDirection.copyFrom(sphere.forward);
  102797. totalTurnAmountOfDrag = 0;
  102798. });
  102799. _dragBehavior.onDragObservable.add(function (event) {
  102800. _this.onRotationSphereDragObservable.notifyObservers({});
  102801. if (_this.attachedMesh) {
  102802. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102803. var worldDragDirection = startingTurnDirection;
  102804. // Project the world right on to the drag plane
  102805. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  102806. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  102807. // project drag delta on to the resulting drag axis and rotate based on that
  102808. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  102809. // Make rotation relative to size of mesh.
  102810. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102811. // Rotate based on axis
  102812. if (!_this.attachedMesh.rotationQuaternion) {
  102813. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102814. }
  102815. if (!_this._anchorMesh.rotationQuaternion) {
  102816. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  102817. }
  102818. // Do not allow the object to turn more than a full circle
  102819. totalTurnAmountOfDrag += projectDist;
  102820. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  102821. if (i_1 >= 8) {
  102822. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  102823. }
  102824. else if (i_1 >= 4) {
  102825. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  102826. }
  102827. else {
  102828. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  102829. }
  102830. // Rotate around center of bounding box
  102831. _this._anchorMesh.addChild(_this.attachedMesh);
  102832. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  102833. _this._anchorMesh.removeChild(_this.attachedMesh);
  102834. }
  102835. _this.updateBoundingBox();
  102836. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102837. }
  102838. });
  102839. // Selection/deselection
  102840. _dragBehavior.onDragStartObservable.add(function () {
  102841. _this.onDragStartObservable.notifyObservers({});
  102842. _this._selectNode(sphere);
  102843. });
  102844. _dragBehavior.onDragEndObservable.add(function () {
  102845. _this.onRotationSphereDragEndObservable.notifyObservers({});
  102846. _this._selectNode(null);
  102847. });
  102848. this_1._rotateSpheresParent.addChild(sphere);
  102849. };
  102850. var this_1 = this, _dragBehavior;
  102851. for (var i_1 = 0; i_1 < 12; i_1++) {
  102852. _loop_1(i_1);
  102853. }
  102854. _this._rootMesh.addChild(_this._rotateSpheresParent);
  102855. // Create scale cubes
  102856. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102857. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  102858. for (var i = 0; i < 2; i++) {
  102859. for (var j = 0; j < 2; j++) {
  102860. var _loop_2 = function () {
  102861. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  102862. box.material = coloredMaterial;
  102863. // Dragging logic
  102864. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  102865. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102866. _dragBehavior.moveAttached = false;
  102867. box.addBehavior(_dragBehavior);
  102868. _dragBehavior.onDragObservable.add(function (event) {
  102869. _this.onScaleBoxDragObservable.notifyObservers({});
  102870. if (_this.attachedMesh) {
  102871. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102872. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102873. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  102874. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  102875. _this.updateBoundingBox();
  102876. if (_this.scalePivot) {
  102877. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  102878. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  102879. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  102880. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102881. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102882. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  102883. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102884. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  102885. }
  102886. else {
  102887. // Scale from the position of the opposite corner
  102888. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  102889. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102890. }
  102891. _this._anchorMesh.addChild(_this.attachedMesh);
  102892. _this._anchorMesh.scaling.addInPlace(deltaScale);
  102893. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  102894. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  102895. }
  102896. _this._anchorMesh.removeChild(_this.attachedMesh);
  102897. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102898. }
  102899. });
  102900. // Selection/deselection
  102901. _dragBehavior.onDragStartObservable.add(function () {
  102902. _this.onDragStartObservable.notifyObservers({});
  102903. _this._selectNode(box);
  102904. });
  102905. _dragBehavior.onDragEndObservable.add(function () {
  102906. _this.onScaleBoxDragEndObservable.notifyObservers({});
  102907. _this._selectNode(null);
  102908. });
  102909. this_2._scaleBoxesParent.addChild(box);
  102910. };
  102911. var this_2 = this, _dragBehavior;
  102912. for (var k = 0; k < 2; k++) {
  102913. _loop_2();
  102914. }
  102915. }
  102916. }
  102917. _this._rootMesh.addChild(_this._scaleBoxesParent);
  102918. // Hover color change
  102919. var pointerIds = new Array();
  102920. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102921. if (!pointerIds[pointerInfo.event.pointerId]) {
  102922. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  102923. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  102924. pointerIds[pointerInfo.event.pointerId] = mesh;
  102925. mesh.material = hoverColoredMaterial;
  102926. }
  102927. });
  102928. }
  102929. else {
  102930. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  102931. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  102932. delete pointerIds[pointerInfo.event.pointerId];
  102933. }
  102934. }
  102935. });
  102936. // Update bounding box positions
  102937. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  102938. // Only update the bouding box if scaling has changed
  102939. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  102940. _this.updateBoundingBox();
  102941. }
  102942. });
  102943. _this.updateBoundingBox();
  102944. return _this;
  102945. }
  102946. /** @hidden */
  102947. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  102948. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  102949. // Save old pivot and set pivot to 0,0,0
  102950. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  102951. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  102952. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  102953. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  102954. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102955. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102956. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102957. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  102958. }
  102959. }
  102960. BoundingBoxGizmo._PivotCached++;
  102961. };
  102962. /** @hidden */
  102963. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  102964. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  102965. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  102966. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102967. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102968. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102969. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  102970. }
  102971. this._PivotCached--;
  102972. };
  102973. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  102974. if (value) {
  102975. // Reset anchor mesh to match attached mesh's scale
  102976. // This is needed to avoid invalid box/sphere position on first drag
  102977. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  102978. this._anchorMesh.addChild(value);
  102979. this._anchorMesh.removeChild(value);
  102980. BoundingBoxGizmo._RestorePivotPoint(value);
  102981. this.updateBoundingBox();
  102982. }
  102983. };
  102984. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  102985. this._rotateSpheresParent.getChildMeshes()
  102986. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  102987. m.isVisible = (!selectedMesh || m == selectedMesh);
  102988. });
  102989. };
  102990. /**
  102991. * Updates the bounding box information for the Gizmo
  102992. */
  102993. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  102994. if (this.attachedMesh) {
  102995. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  102996. this._update();
  102997. // Rotate based on axis
  102998. if (!this.attachedMesh.rotationQuaternion) {
  102999. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  103000. }
  103001. if (!this._anchorMesh.rotationQuaternion) {
  103002. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  103003. }
  103004. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103005. // Store original position and reset mesh to origin before computing the bounding box
  103006. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103007. this._tmpVector.copyFrom(this.attachedMesh.position);
  103008. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  103009. this.attachedMesh.position.set(0, 0, 0);
  103010. // Update bounding dimensions/positions
  103011. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  103012. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  103013. // Update gizmo to match bounding box scaling and rotation
  103014. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  103015. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103016. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  103017. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  103018. this._lineBoundingBox.computeWorldMatrix();
  103019. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  103020. // restore position/rotation values
  103021. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  103022. this.attachedMesh.position.copyFrom(this._tmpVector);
  103023. }
  103024. // Update rotation sphere locations
  103025. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  103026. for (var i = 0; i < 3; i++) {
  103027. for (var j = 0; j < 2; j++) {
  103028. for (var k = 0; k < 2; k++) {
  103029. var index = ((i * 4) + (j * 2)) + k;
  103030. if (i == 0) {
  103031. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103032. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103033. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103034. }
  103035. if (i == 1) {
  103036. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  103037. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103038. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103039. }
  103040. if (i == 2) {
  103041. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  103042. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103043. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103044. }
  103045. if (this.fixedDragMeshScreenSize) {
  103046. this._rootMesh.computeWorldMatrix();
  103047. this._rotateSpheresParent.computeWorldMatrix();
  103048. rotateSpheres[index].computeWorldMatrix();
  103049. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103050. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103051. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103052. }
  103053. else {
  103054. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  103055. }
  103056. }
  103057. }
  103058. }
  103059. // Update scale box locations
  103060. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  103061. for (var i = 0; i < 2; i++) {
  103062. for (var j = 0; j < 2; j++) {
  103063. for (var k = 0; k < 2; k++) {
  103064. var index = ((i * 4) + (j * 2)) + k;
  103065. if (scaleBoxes[index]) {
  103066. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103067. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103068. if (this.fixedDragMeshScreenSize) {
  103069. this._rootMesh.computeWorldMatrix();
  103070. this._scaleBoxesParent.computeWorldMatrix();
  103071. scaleBoxes[index].computeWorldMatrix();
  103072. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103073. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103074. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103075. }
  103076. else {
  103077. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  103078. }
  103079. }
  103080. }
  103081. }
  103082. }
  103083. if (this.attachedMesh) {
  103084. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  103085. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  103086. }
  103087. };
  103088. /**
  103089. * Enables rotation on the specified axis and disables rotation on the others
  103090. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  103091. */
  103092. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  103093. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  103094. if (i < 4) {
  103095. m.setEnabled(axis.indexOf("x") != -1);
  103096. }
  103097. else if (i < 8) {
  103098. m.setEnabled(axis.indexOf("y") != -1);
  103099. }
  103100. else {
  103101. m.setEnabled(axis.indexOf("z") != -1);
  103102. }
  103103. });
  103104. };
  103105. /**
  103106. * Disposes of the gizmo
  103107. */
  103108. BoundingBoxGizmo.prototype.dispose = function () {
  103109. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103110. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  103111. this._lineBoundingBox.dispose();
  103112. this._rotateSpheresParent.dispose();
  103113. this._scaleBoxesParent.dispose();
  103114. _super.prototype.dispose.call(this);
  103115. };
  103116. /**
  103117. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  103118. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  103119. * @returns the bounding box mesh with the passed in mesh as a child
  103120. */
  103121. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  103122. var makeNotPickable = function (root) {
  103123. root.isPickable = false;
  103124. root.getChildMeshes().forEach(function (c) {
  103125. makeNotPickable(c);
  103126. });
  103127. };
  103128. makeNotPickable(mesh);
  103129. // Reset position to get boudning box from origin with no rotation
  103130. if (!mesh.rotationQuaternion) {
  103131. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  103132. }
  103133. var oldPos = mesh.position.clone();
  103134. var oldRot = mesh.rotationQuaternion.clone();
  103135. mesh.rotationQuaternion.set(0, 0, 0, 1);
  103136. mesh.position.set(0, 0, 0);
  103137. // Update bounding dimensions/positions
  103138. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  103139. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  103140. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  103141. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103142. // Restore original positions
  103143. mesh.addChild(box);
  103144. mesh.rotationQuaternion.copyFrom(oldRot);
  103145. mesh.position.copyFrom(oldPos);
  103146. // Reverse parenting
  103147. mesh.removeChild(box);
  103148. box.addChild(mesh);
  103149. box.visibility = 0;
  103150. return box;
  103151. };
  103152. /**
  103153. * CustomMeshes are not supported by this gizmo
  103154. * @param mesh The mesh to replace the default mesh of the gizmo
  103155. */
  103156. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  103157. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  103158. };
  103159. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  103160. // store/remove pivot point should only be applied during their outermost calls
  103161. BoundingBoxGizmo._PivotCached = 0;
  103162. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  103163. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  103164. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  103165. return BoundingBoxGizmo;
  103166. }(BABYLON.Gizmo));
  103167. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  103168. })(BABYLON || (BABYLON = {}));
  103169. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  103170. var BABYLON;
  103171. (function (BABYLON) {
  103172. /**
  103173. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  103174. */
  103175. var GizmoManager = /** @class */ (function () {
  103176. /**
  103177. * Instatiates a gizmo manager
  103178. * @param scene the scene to overlay the gizmos on top of
  103179. */
  103180. function GizmoManager(scene) {
  103181. var _this = this;
  103182. this.scene = scene;
  103183. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  103184. this._pointerObserver = null;
  103185. this._attachedMesh = null;
  103186. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  103187. /**
  103188. * When bounding box gizmo is enabled, this can be used to track drag/end events
  103189. */
  103190. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  103191. /**
  103192. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  103193. */
  103194. this.attachableMeshes = null;
  103195. /**
  103196. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  103197. */
  103198. this.usePointerToAttachGizmos = true;
  103199. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103200. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  103201. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103202. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  103203. // Instatiate/dispose gizmos based on pointer actions
  103204. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  103205. if (!_this.usePointerToAttachGizmos) {
  103206. return;
  103207. }
  103208. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103209. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  103210. var node = pointerInfo.pickInfo.pickedMesh;
  103211. if (_this.attachableMeshes == null) {
  103212. // Attach to the most parent node
  103213. while (node && node.parent != null) {
  103214. node = node.parent;
  103215. }
  103216. }
  103217. else {
  103218. // Attach to the parent node that is an attachableMesh
  103219. var found = false;
  103220. _this.attachableMeshes.forEach(function (mesh) {
  103221. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  103222. node = mesh;
  103223. found = true;
  103224. }
  103225. });
  103226. if (!found) {
  103227. node = null;
  103228. }
  103229. }
  103230. if (node instanceof BABYLON.AbstractMesh) {
  103231. if (_this._attachedMesh != node) {
  103232. _this.attachToMesh(node);
  103233. }
  103234. }
  103235. else {
  103236. _this.attachToMesh(null);
  103237. }
  103238. }
  103239. else {
  103240. _this.attachToMesh(null);
  103241. }
  103242. }
  103243. });
  103244. }
  103245. /**
  103246. * Attaches a set of gizmos to the specified mesh
  103247. * @param mesh The mesh the gizmo's should be attached to
  103248. */
  103249. GizmoManager.prototype.attachToMesh = function (mesh) {
  103250. if (this._attachedMesh) {
  103251. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103252. }
  103253. this._attachedMesh = mesh;
  103254. for (var key in this.gizmos) {
  103255. var gizmo = (this.gizmos[key]);
  103256. if (gizmo && this._gizmosEnabled[key]) {
  103257. gizmo.attachedMesh = mesh;
  103258. }
  103259. }
  103260. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  103261. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103262. }
  103263. };
  103264. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  103265. get: function () {
  103266. return this._gizmosEnabled.positionGizmo;
  103267. },
  103268. /**
  103269. * If the position gizmo is enabled
  103270. */
  103271. set: function (value) {
  103272. if (value) {
  103273. if (!this.gizmos.positionGizmo) {
  103274. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  103275. }
  103276. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  103277. }
  103278. else if (this.gizmos.positionGizmo) {
  103279. this.gizmos.positionGizmo.attachedMesh = null;
  103280. }
  103281. this._gizmosEnabled.positionGizmo = value;
  103282. },
  103283. enumerable: true,
  103284. configurable: true
  103285. });
  103286. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  103287. get: function () {
  103288. return this._gizmosEnabled.rotationGizmo;
  103289. },
  103290. /**
  103291. * If the rotation gizmo is enabled
  103292. */
  103293. set: function (value) {
  103294. if (value) {
  103295. if (!this.gizmos.rotationGizmo) {
  103296. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  103297. }
  103298. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  103299. }
  103300. else if (this.gizmos.rotationGizmo) {
  103301. this.gizmos.rotationGizmo.attachedMesh = null;
  103302. }
  103303. this._gizmosEnabled.rotationGizmo = value;
  103304. },
  103305. enumerable: true,
  103306. configurable: true
  103307. });
  103308. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  103309. get: function () {
  103310. return this._gizmosEnabled.scaleGizmo;
  103311. },
  103312. /**
  103313. * If the scale gizmo is enabled
  103314. */
  103315. set: function (value) {
  103316. if (value) {
  103317. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  103318. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  103319. }
  103320. else if (this.gizmos.scaleGizmo) {
  103321. this.gizmos.scaleGizmo.attachedMesh = null;
  103322. }
  103323. this._gizmosEnabled.scaleGizmo = value;
  103324. },
  103325. enumerable: true,
  103326. configurable: true
  103327. });
  103328. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  103329. get: function () {
  103330. return this._gizmosEnabled.boundingBoxGizmo;
  103331. },
  103332. /**
  103333. * If the boundingBox gizmo is enabled
  103334. */
  103335. set: function (value) {
  103336. if (value) {
  103337. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  103338. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  103339. if (this._attachedMesh) {
  103340. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103341. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103342. }
  103343. }
  103344. else if (this.gizmos.boundingBoxGizmo) {
  103345. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  103346. }
  103347. this._gizmosEnabled.boundingBoxGizmo = value;
  103348. },
  103349. enumerable: true,
  103350. configurable: true
  103351. });
  103352. /**
  103353. * Disposes of the gizmo manager
  103354. */
  103355. GizmoManager.prototype.dispose = function () {
  103356. this.scene.onPointerObservable.remove(this._pointerObserver);
  103357. for (var key in this.gizmos) {
  103358. var gizmo = (this.gizmos[key]);
  103359. if (gizmo) {
  103360. gizmo.dispose();
  103361. }
  103362. }
  103363. this._defaultKeepDepthUtilityLayer.dispose();
  103364. this._defaultUtilityLayer.dispose();
  103365. this.boundingBoxDragBehavior.detach();
  103366. };
  103367. return GizmoManager;
  103368. }());
  103369. BABYLON.GizmoManager = GizmoManager;
  103370. })(BABYLON || (BABYLON = {}));
  103371. //# sourceMappingURL=babylon.gizmoManager.js.map
  103372. var BABYLON;
  103373. (function (BABYLON) {
  103374. /**
  103375. * Defines a target to use with MorphTargetManager
  103376. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103377. */
  103378. var MorphTarget = /** @class */ (function () {
  103379. /**
  103380. * Creates a new MorphTarget
  103381. * @param name defines the name of the target
  103382. * @param influence defines the influence to use
  103383. */
  103384. function MorphTarget(
  103385. /** defines the name of the target */
  103386. name, influence, scene) {
  103387. if (influence === void 0) { influence = 0; }
  103388. if (scene === void 0) { scene = null; }
  103389. this.name = name;
  103390. /**
  103391. * Gets or sets the list of animations
  103392. */
  103393. this.animations = new Array();
  103394. this._positions = null;
  103395. this._normals = null;
  103396. this._tangents = null;
  103397. /**
  103398. * Observable raised when the influence changes
  103399. */
  103400. this.onInfluenceChanged = new BABYLON.Observable();
  103401. /** @hidden */
  103402. this._onDataLayoutChanged = new BABYLON.Observable();
  103403. this._animationPropertiesOverride = null;
  103404. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103405. this.influence = influence;
  103406. }
  103407. Object.defineProperty(MorphTarget.prototype, "influence", {
  103408. /**
  103409. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  103410. */
  103411. get: function () {
  103412. return this._influence;
  103413. },
  103414. set: function (influence) {
  103415. if (this._influence === influence) {
  103416. return;
  103417. }
  103418. var previous = this._influence;
  103419. this._influence = influence;
  103420. if (this.onInfluenceChanged.hasObservers) {
  103421. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  103422. }
  103423. },
  103424. enumerable: true,
  103425. configurable: true
  103426. });
  103427. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  103428. /**
  103429. * Gets or sets the animation properties override
  103430. */
  103431. get: function () {
  103432. if (!this._animationPropertiesOverride && this._scene) {
  103433. return this._scene.animationPropertiesOverride;
  103434. }
  103435. return this._animationPropertiesOverride;
  103436. },
  103437. set: function (value) {
  103438. this._animationPropertiesOverride = value;
  103439. },
  103440. enumerable: true,
  103441. configurable: true
  103442. });
  103443. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  103444. /**
  103445. * Gets a boolean defining if the target contains position data
  103446. */
  103447. get: function () {
  103448. return !!this._positions;
  103449. },
  103450. enumerable: true,
  103451. configurable: true
  103452. });
  103453. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  103454. /**
  103455. * Gets a boolean defining if the target contains normal data
  103456. */
  103457. get: function () {
  103458. return !!this._normals;
  103459. },
  103460. enumerable: true,
  103461. configurable: true
  103462. });
  103463. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  103464. /**
  103465. * Gets a boolean defining if the target contains tangent data
  103466. */
  103467. get: function () {
  103468. return !!this._tangents;
  103469. },
  103470. enumerable: true,
  103471. configurable: true
  103472. });
  103473. /**
  103474. * Affects position data to this target
  103475. * @param data defines the position data to use
  103476. */
  103477. MorphTarget.prototype.setPositions = function (data) {
  103478. var hadPositions = this.hasPositions;
  103479. this._positions = data;
  103480. if (hadPositions !== this.hasPositions) {
  103481. this._onDataLayoutChanged.notifyObservers(undefined);
  103482. }
  103483. };
  103484. /**
  103485. * Gets the position data stored in this target
  103486. * @returns a FloatArray containing the position data (or null if not present)
  103487. */
  103488. MorphTarget.prototype.getPositions = function () {
  103489. return this._positions;
  103490. };
  103491. /**
  103492. * Affects normal data to this target
  103493. * @param data defines the normal data to use
  103494. */
  103495. MorphTarget.prototype.setNormals = function (data) {
  103496. var hadNormals = this.hasNormals;
  103497. this._normals = data;
  103498. if (hadNormals !== this.hasNormals) {
  103499. this._onDataLayoutChanged.notifyObservers(undefined);
  103500. }
  103501. };
  103502. /**
  103503. * Gets the normal data stored in this target
  103504. * @returns a FloatArray containing the normal data (or null if not present)
  103505. */
  103506. MorphTarget.prototype.getNormals = function () {
  103507. return this._normals;
  103508. };
  103509. /**
  103510. * Affects tangent data to this target
  103511. * @param data defines the tangent data to use
  103512. */
  103513. MorphTarget.prototype.setTangents = function (data) {
  103514. var hadTangents = this.hasTangents;
  103515. this._tangents = data;
  103516. if (hadTangents !== this.hasTangents) {
  103517. this._onDataLayoutChanged.notifyObservers(undefined);
  103518. }
  103519. };
  103520. /**
  103521. * Gets the tangent data stored in this target
  103522. * @returns a FloatArray containing the tangent data (or null if not present)
  103523. */
  103524. MorphTarget.prototype.getTangents = function () {
  103525. return this._tangents;
  103526. };
  103527. /**
  103528. * Serializes the current target into a Serialization object
  103529. * @returns the serialized object
  103530. */
  103531. MorphTarget.prototype.serialize = function () {
  103532. var serializationObject = {};
  103533. serializationObject.name = this.name;
  103534. serializationObject.influence = this.influence;
  103535. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  103536. if (this.hasNormals) {
  103537. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  103538. }
  103539. if (this.hasTangents) {
  103540. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  103541. }
  103542. // Animations
  103543. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  103544. return serializationObject;
  103545. };
  103546. // Statics
  103547. /**
  103548. * Creates a new target from serialized data
  103549. * @param serializationObject defines the serialized data to use
  103550. * @returns a new MorphTarget
  103551. */
  103552. MorphTarget.Parse = function (serializationObject) {
  103553. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  103554. result.setPositions(serializationObject.positions);
  103555. if (serializationObject.normals) {
  103556. result.setNormals(serializationObject.normals);
  103557. }
  103558. if (serializationObject.tangents) {
  103559. result.setTangents(serializationObject.tangents);
  103560. }
  103561. // Animations
  103562. if (serializationObject.animations) {
  103563. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  103564. var parsedAnimation = serializationObject.animations[animationIndex];
  103565. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  103566. }
  103567. }
  103568. return result;
  103569. };
  103570. /**
  103571. * Creates a MorphTarget from mesh data
  103572. * @param mesh defines the source mesh
  103573. * @param name defines the name to use for the new target
  103574. * @param influence defines the influence to attach to the target
  103575. * @returns a new MorphTarget
  103576. */
  103577. MorphTarget.FromMesh = function (mesh, name, influence) {
  103578. if (!name) {
  103579. name = mesh.name;
  103580. }
  103581. var result = new MorphTarget(name, influence, mesh.getScene());
  103582. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  103583. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103584. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  103585. }
  103586. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  103587. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  103588. }
  103589. return result;
  103590. };
  103591. return MorphTarget;
  103592. }());
  103593. BABYLON.MorphTarget = MorphTarget;
  103594. })(BABYLON || (BABYLON = {}));
  103595. //# sourceMappingURL=babylon.morphTarget.js.map
  103596. var BABYLON;
  103597. (function (BABYLON) {
  103598. /**
  103599. * This class is used to deform meshes using morphing between different targets
  103600. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103601. */
  103602. var MorphTargetManager = /** @class */ (function () {
  103603. /**
  103604. * Creates a new MorphTargetManager
  103605. * @param scene defines the current scene
  103606. */
  103607. function MorphTargetManager(scene) {
  103608. if (scene === void 0) { scene = null; }
  103609. this._targets = new Array();
  103610. this._targetInfluenceChangedObservers = new Array();
  103611. this._targetDataLayoutChangedObservers = new Array();
  103612. this._activeTargets = new BABYLON.SmartArray(16);
  103613. this._supportsNormals = false;
  103614. this._supportsTangents = false;
  103615. this._vertexCount = 0;
  103616. this._uniqueId = 0;
  103617. this._tempInfluences = new Array();
  103618. if (!scene) {
  103619. scene = BABYLON.Engine.LastCreatedScene;
  103620. }
  103621. this._scene = scene;
  103622. if (this._scene) {
  103623. this._scene.morphTargetManagers.push(this);
  103624. this._uniqueId = this._scene.getUniqueId();
  103625. }
  103626. }
  103627. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  103628. /**
  103629. * Gets the unique ID of this manager
  103630. */
  103631. get: function () {
  103632. return this._uniqueId;
  103633. },
  103634. enumerable: true,
  103635. configurable: true
  103636. });
  103637. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  103638. /**
  103639. * Gets the number of vertices handled by this manager
  103640. */
  103641. get: function () {
  103642. return this._vertexCount;
  103643. },
  103644. enumerable: true,
  103645. configurable: true
  103646. });
  103647. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  103648. /**
  103649. * Gets a boolean indicating if this manager supports morphing of normals
  103650. */
  103651. get: function () {
  103652. return this._supportsNormals;
  103653. },
  103654. enumerable: true,
  103655. configurable: true
  103656. });
  103657. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  103658. /**
  103659. * Gets a boolean indicating if this manager supports morphing of tangents
  103660. */
  103661. get: function () {
  103662. return this._supportsTangents;
  103663. },
  103664. enumerable: true,
  103665. configurable: true
  103666. });
  103667. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  103668. /**
  103669. * Gets the number of targets stored in this manager
  103670. */
  103671. get: function () {
  103672. return this._targets.length;
  103673. },
  103674. enumerable: true,
  103675. configurable: true
  103676. });
  103677. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  103678. /**
  103679. * Gets the number of influencers (ie. the number of targets with influences > 0)
  103680. */
  103681. get: function () {
  103682. return this._activeTargets.length;
  103683. },
  103684. enumerable: true,
  103685. configurable: true
  103686. });
  103687. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  103688. /**
  103689. * Gets the list of influences (one per target)
  103690. */
  103691. get: function () {
  103692. return this._influences;
  103693. },
  103694. enumerable: true,
  103695. configurable: true
  103696. });
  103697. /**
  103698. * Gets the active target at specified index. An active target is a target with an influence > 0
  103699. * @param index defines the index to check
  103700. * @returns the requested target
  103701. */
  103702. MorphTargetManager.prototype.getActiveTarget = function (index) {
  103703. return this._activeTargets.data[index];
  103704. };
  103705. /**
  103706. * Gets the target at specified index
  103707. * @param index defines the index to check
  103708. * @returns the requested target
  103709. */
  103710. MorphTargetManager.prototype.getTarget = function (index) {
  103711. return this._targets[index];
  103712. };
  103713. /**
  103714. * Add a new target to this manager
  103715. * @param target defines the target to add
  103716. */
  103717. MorphTargetManager.prototype.addTarget = function (target) {
  103718. var _this = this;
  103719. this._targets.push(target);
  103720. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  103721. _this._syncActiveTargets(needUpdate);
  103722. }));
  103723. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  103724. _this._syncActiveTargets(true);
  103725. }));
  103726. this._syncActiveTargets(true);
  103727. };
  103728. /**
  103729. * Removes a target from the manager
  103730. * @param target defines the target to remove
  103731. */
  103732. MorphTargetManager.prototype.removeTarget = function (target) {
  103733. var index = this._targets.indexOf(target);
  103734. if (index >= 0) {
  103735. this._targets.splice(index, 1);
  103736. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  103737. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  103738. this._syncActiveTargets(true);
  103739. }
  103740. };
  103741. /**
  103742. * Serializes the current manager into a Serialization object
  103743. * @returns the serialized object
  103744. */
  103745. MorphTargetManager.prototype.serialize = function () {
  103746. var serializationObject = {};
  103747. serializationObject.id = this.uniqueId;
  103748. serializationObject.targets = [];
  103749. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103750. var target = _a[_i];
  103751. serializationObject.targets.push(target.serialize());
  103752. }
  103753. return serializationObject;
  103754. };
  103755. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  103756. var influenceCount = 0;
  103757. this._activeTargets.reset();
  103758. this._supportsNormals = true;
  103759. this._supportsTangents = true;
  103760. this._vertexCount = 0;
  103761. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103762. var target = _a[_i];
  103763. if (target.influence === 0) {
  103764. continue;
  103765. }
  103766. this._activeTargets.push(target);
  103767. this._tempInfluences[influenceCount++] = target.influence;
  103768. this._supportsNormals = this._supportsNormals && target.hasNormals;
  103769. this._supportsTangents = this._supportsTangents && target.hasTangents;
  103770. var positions = target.getPositions();
  103771. if (positions) {
  103772. var vertexCount = positions.length / 3;
  103773. if (this._vertexCount === 0) {
  103774. this._vertexCount = vertexCount;
  103775. }
  103776. else if (this._vertexCount !== vertexCount) {
  103777. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  103778. return;
  103779. }
  103780. }
  103781. }
  103782. if (!this._influences || this._influences.length !== influenceCount) {
  103783. this._influences = new Float32Array(influenceCount);
  103784. }
  103785. for (var index = 0; index < influenceCount; index++) {
  103786. this._influences[index] = this._tempInfluences[index];
  103787. }
  103788. if (needUpdate) {
  103789. this.synchronize();
  103790. }
  103791. };
  103792. /**
  103793. * Syncrhonize the targets with all the meshes using this morph target manager
  103794. */
  103795. MorphTargetManager.prototype.synchronize = function () {
  103796. if (!this._scene) {
  103797. return;
  103798. }
  103799. // Flag meshes as dirty to resync with the active targets
  103800. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  103801. var mesh = _a[_i];
  103802. if (mesh.morphTargetManager === this) {
  103803. mesh._syncGeometryWithMorphTargetManager();
  103804. }
  103805. }
  103806. };
  103807. // Statics
  103808. /**
  103809. * Creates a new MorphTargetManager from serialized data
  103810. * @param serializationObject defines the serialized data
  103811. * @param scene defines the hosting scene
  103812. * @returns the new MorphTargetManager
  103813. */
  103814. MorphTargetManager.Parse = function (serializationObject, scene) {
  103815. var result = new MorphTargetManager(scene);
  103816. result._uniqueId = serializationObject.id;
  103817. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  103818. var targetData = _a[_i];
  103819. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  103820. }
  103821. return result;
  103822. };
  103823. return MorphTargetManager;
  103824. }());
  103825. BABYLON.MorphTargetManager = MorphTargetManager;
  103826. })(BABYLON || (BABYLON = {}));
  103827. //# sourceMappingURL=babylon.morphTargetManager.js.map
  103828. var BABYLON;
  103829. (function (BABYLON) {
  103830. /**
  103831. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  103832. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103833. */
  103834. var Octree = /** @class */ (function () {
  103835. /**
  103836. * Creates a octree
  103837. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103838. * @param creationFunc function to be used to instatiate the octree
  103839. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  103840. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  103841. */
  103842. function Octree(creationFunc, maxBlockCapacity,
  103843. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  103844. maxDepth) {
  103845. if (maxDepth === void 0) { maxDepth = 2; }
  103846. this.maxDepth = maxDepth;
  103847. /**
  103848. * Content stored in the octree
  103849. */
  103850. this.dynamicContent = new Array();
  103851. this._maxBlockCapacity = maxBlockCapacity || 64;
  103852. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  103853. this._creationFunc = creationFunc;
  103854. }
  103855. // Methods
  103856. /**
  103857. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  103858. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103859. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103860. * @param entries meshes to be added to the octree blocks
  103861. */
  103862. Octree.prototype.update = function (worldMin, worldMax, entries) {
  103863. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  103864. };
  103865. /**
  103866. * Adds a mesh to the octree
  103867. * @param entry Mesh to add to the octree
  103868. */
  103869. Octree.prototype.addMesh = function (entry) {
  103870. for (var index = 0; index < this.blocks.length; index++) {
  103871. var block = this.blocks[index];
  103872. block.addEntry(entry);
  103873. }
  103874. };
  103875. /**
  103876. * Selects an array of meshes within the frustum
  103877. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  103878. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  103879. * @returns array of meshes within the frustum
  103880. */
  103881. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  103882. this._selectionContent.reset();
  103883. for (var index = 0; index < this.blocks.length; index++) {
  103884. var block = this.blocks[index];
  103885. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  103886. }
  103887. if (allowDuplicate) {
  103888. this._selectionContent.concat(this.dynamicContent);
  103889. }
  103890. else {
  103891. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103892. }
  103893. return this._selectionContent;
  103894. };
  103895. /**
  103896. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  103897. * @param sphereCenter defines the bounding sphere center
  103898. * @param sphereRadius defines the bounding sphere radius
  103899. * @param allowDuplicate defines if the selection array can contains duplicated entries
  103900. * @returns an array of objects that intersect the sphere
  103901. */
  103902. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  103903. this._selectionContent.reset();
  103904. for (var index = 0; index < this.blocks.length; index++) {
  103905. var block = this.blocks[index];
  103906. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  103907. }
  103908. if (allowDuplicate) {
  103909. this._selectionContent.concat(this.dynamicContent);
  103910. }
  103911. else {
  103912. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103913. }
  103914. return this._selectionContent;
  103915. };
  103916. /**
  103917. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  103918. * @param ray defines the ray to test with
  103919. * @returns array of intersected objects
  103920. */
  103921. Octree.prototype.intersectsRay = function (ray) {
  103922. this._selectionContent.reset();
  103923. for (var index = 0; index < this.blocks.length; index++) {
  103924. var block = this.blocks[index];
  103925. block.intersectsRay(ray, this._selectionContent);
  103926. }
  103927. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103928. return this._selectionContent;
  103929. };
  103930. /**
  103931. * @hidden
  103932. */
  103933. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  103934. target.blocks = new Array();
  103935. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103936. // Segmenting space
  103937. for (var x = 0; x < 2; x++) {
  103938. for (var y = 0; y < 2; y++) {
  103939. for (var z = 0; z < 2; z++) {
  103940. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  103941. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  103942. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  103943. block.addEntries(entries);
  103944. target.blocks.push(block);
  103945. }
  103946. }
  103947. }
  103948. };
  103949. /**
  103950. * Adds a mesh into the octree block if it intersects the block
  103951. */
  103952. Octree.CreationFuncForMeshes = function (entry, block) {
  103953. var boundingInfo = entry.getBoundingInfo();
  103954. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103955. block.entries.push(entry);
  103956. }
  103957. };
  103958. /**
  103959. * Adds a submesh into the octree block if it intersects the block
  103960. */
  103961. Octree.CreationFuncForSubMeshes = function (entry, block) {
  103962. var boundingInfo = entry.getBoundingInfo();
  103963. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103964. block.entries.push(entry);
  103965. }
  103966. };
  103967. return Octree;
  103968. }());
  103969. BABYLON.Octree = Octree;
  103970. })(BABYLON || (BABYLON = {}));
  103971. //# sourceMappingURL=babylon.octree.js.map
  103972. var BABYLON;
  103973. (function (BABYLON) {
  103974. /**
  103975. * Class used to store a cell in an octree
  103976. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103977. */
  103978. var OctreeBlock = /** @class */ (function () {
  103979. /**
  103980. * Creates a new block
  103981. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  103982. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  103983. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  103984. * @param depth defines the current depth of this block in the octree
  103985. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  103986. * @param creationFunc defines a callback to call when an element is added to the block
  103987. */
  103988. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  103989. /**
  103990. * Gets the content of the current block
  103991. */
  103992. this.entries = new Array();
  103993. this._boundingVectors = new Array();
  103994. this._capacity = capacity;
  103995. this._depth = depth;
  103996. this._maxDepth = maxDepth;
  103997. this._creationFunc = creationFunc;
  103998. this._minPoint = minPoint;
  103999. this._maxPoint = maxPoint;
  104000. this._boundingVectors.push(minPoint.clone());
  104001. this._boundingVectors.push(maxPoint.clone());
  104002. this._boundingVectors.push(minPoint.clone());
  104003. this._boundingVectors[2].x = maxPoint.x;
  104004. this._boundingVectors.push(minPoint.clone());
  104005. this._boundingVectors[3].y = maxPoint.y;
  104006. this._boundingVectors.push(minPoint.clone());
  104007. this._boundingVectors[4].z = maxPoint.z;
  104008. this._boundingVectors.push(maxPoint.clone());
  104009. this._boundingVectors[5].z = minPoint.z;
  104010. this._boundingVectors.push(maxPoint.clone());
  104011. this._boundingVectors[6].x = minPoint.x;
  104012. this._boundingVectors.push(maxPoint.clone());
  104013. this._boundingVectors[7].y = minPoint.y;
  104014. }
  104015. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  104016. // Property
  104017. /**
  104018. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104019. */
  104020. get: function () {
  104021. return this._capacity;
  104022. },
  104023. enumerable: true,
  104024. configurable: true
  104025. });
  104026. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  104027. /**
  104028. * Gets the minimum vector (in world space) of the block's bounding box
  104029. */
  104030. get: function () {
  104031. return this._minPoint;
  104032. },
  104033. enumerable: true,
  104034. configurable: true
  104035. });
  104036. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  104037. /**
  104038. * Gets the maximum vector (in world space) of the block's bounding box
  104039. */
  104040. get: function () {
  104041. return this._maxPoint;
  104042. },
  104043. enumerable: true,
  104044. configurable: true
  104045. });
  104046. // Methods
  104047. /**
  104048. * Add a new element to this block
  104049. * @param entry defines the element to add
  104050. */
  104051. OctreeBlock.prototype.addEntry = function (entry) {
  104052. if (this.blocks) {
  104053. for (var index = 0; index < this.blocks.length; index++) {
  104054. var block = this.blocks[index];
  104055. block.addEntry(entry);
  104056. }
  104057. return;
  104058. }
  104059. this._creationFunc(entry, this);
  104060. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  104061. this.createInnerBlocks();
  104062. }
  104063. };
  104064. /**
  104065. * Add an array of elements to this block
  104066. * @param entries defines the array of elements to add
  104067. */
  104068. OctreeBlock.prototype.addEntries = function (entries) {
  104069. for (var index = 0; index < entries.length; index++) {
  104070. var mesh = entries[index];
  104071. this.addEntry(mesh);
  104072. }
  104073. };
  104074. /**
  104075. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  104076. * @param frustumPlanes defines the frustum planes to test
  104077. * @param selection defines the array to store current content if selection is positive
  104078. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104079. */
  104080. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  104081. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  104082. if (this.blocks) {
  104083. for (var index = 0; index < this.blocks.length; index++) {
  104084. var block = this.blocks[index];
  104085. block.select(frustumPlanes, selection, allowDuplicate);
  104086. }
  104087. return;
  104088. }
  104089. if (allowDuplicate) {
  104090. selection.concat(this.entries);
  104091. }
  104092. else {
  104093. selection.concatWithNoDuplicate(this.entries);
  104094. }
  104095. }
  104096. };
  104097. /**
  104098. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  104099. * @param sphereCenter defines the bounding sphere center
  104100. * @param sphereRadius defines the bounding sphere radius
  104101. * @param selection defines the array to store current content if selection is positive
  104102. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104103. */
  104104. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  104105. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  104106. if (this.blocks) {
  104107. for (var index = 0; index < this.blocks.length; index++) {
  104108. var block = this.blocks[index];
  104109. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  104110. }
  104111. return;
  104112. }
  104113. if (allowDuplicate) {
  104114. selection.concat(this.entries);
  104115. }
  104116. else {
  104117. selection.concatWithNoDuplicate(this.entries);
  104118. }
  104119. }
  104120. };
  104121. /**
  104122. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  104123. * @param ray defines the ray to test with
  104124. * @param selection defines the array to store current content if selection is positive
  104125. */
  104126. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  104127. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  104128. if (this.blocks) {
  104129. for (var index = 0; index < this.blocks.length; index++) {
  104130. var block = this.blocks[index];
  104131. block.intersectsRay(ray, selection);
  104132. }
  104133. return;
  104134. }
  104135. selection.concatWithNoDuplicate(this.entries);
  104136. }
  104137. };
  104138. /**
  104139. * Subdivide the content into child blocks (this block will then be empty)
  104140. */
  104141. OctreeBlock.prototype.createInnerBlocks = function () {
  104142. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  104143. };
  104144. return OctreeBlock;
  104145. }());
  104146. BABYLON.OctreeBlock = OctreeBlock;
  104147. })(BABYLON || (BABYLON = {}));
  104148. //# sourceMappingURL=babylon.octreeBlock.js.map
  104149. var BABYLON;
  104150. (function (BABYLON) {
  104151. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  104152. if (maxCapacity === void 0) { maxCapacity = 64; }
  104153. if (maxDepth === void 0) { maxDepth = 2; }
  104154. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104155. if (!component) {
  104156. component = new OctreeSceneComponent(this);
  104157. this._addComponent(component);
  104158. }
  104159. if (!this._selectionOctree) {
  104160. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  104161. }
  104162. var worldExtends = this.getWorldExtends();
  104163. // Update octree
  104164. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  104165. return this._selectionOctree;
  104166. };
  104167. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  104168. get: function () {
  104169. return this._selectionOctree;
  104170. },
  104171. enumerable: true,
  104172. configurable: true
  104173. });
  104174. /**
  104175. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  104176. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  104177. * @param maxCapacity defines the maximum size of each block (64 by default)
  104178. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  104179. * @returns the new octree
  104180. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  104181. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104182. */
  104183. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  104184. if (maxCapacity === void 0) { maxCapacity = 64; }
  104185. if (maxDepth === void 0) { maxDepth = 2; }
  104186. var scene = this.getScene();
  104187. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104188. if (!component) {
  104189. component = new OctreeSceneComponent(scene);
  104190. scene._addComponent(component);
  104191. }
  104192. if (!this._submeshesOctree) {
  104193. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  104194. }
  104195. this.computeWorldMatrix(true);
  104196. var boundingInfo = this.getBoundingInfo();
  104197. // Update octree
  104198. var bbox = boundingInfo.boundingBox;
  104199. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  104200. return this._submeshesOctree;
  104201. };
  104202. /**
  104203. * Defines the octree scene component responsible to manage any octrees
  104204. * in a given scene.
  104205. */
  104206. var OctreeSceneComponent = /** @class */ (function () {
  104207. /**
  104208. * Creates a new instance of the component for the given scene
  104209. * @param scene Defines the scene to register the component in
  104210. */
  104211. function OctreeSceneComponent(scene) {
  104212. /**
  104213. * The component name helpfull to identify the component in the list of scene components.
  104214. */
  104215. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  104216. /**
  104217. * Indicates if the meshes have been checked to make sure they are isEnabled()
  104218. */
  104219. this.checksIsEnabled = true;
  104220. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  104221. this.scene = scene;
  104222. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  104223. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  104224. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  104225. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  104226. }
  104227. /**
  104228. * Registers the component in a given scene
  104229. */
  104230. OctreeSceneComponent.prototype.register = function () {
  104231. var _this = this;
  104232. this.scene.onMeshRemovedObservable.add(function (mesh) {
  104233. var sceneOctree = _this.scene.selectionOctree;
  104234. if (sceneOctree !== undefined && sceneOctree !== null) {
  104235. var index = sceneOctree.dynamicContent.indexOf(mesh);
  104236. if (index !== -1) {
  104237. sceneOctree.dynamicContent.splice(index, 1);
  104238. }
  104239. }
  104240. });
  104241. this.scene.onMeshImportedObservable.add(function (mesh) {
  104242. var sceneOctree = _this.scene.selectionOctree;
  104243. if (sceneOctree !== undefined && sceneOctree !== null) {
  104244. sceneOctree.addMesh(mesh);
  104245. }
  104246. });
  104247. };
  104248. /**
  104249. * Return the list of active meshes
  104250. * @returns the list of active meshes
  104251. */
  104252. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  104253. if (this.scene._selectionOctree) {
  104254. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  104255. return selection;
  104256. }
  104257. return this.scene._getDefaultMeshCandidates();
  104258. };
  104259. /**
  104260. * Return the list of active sub meshes
  104261. * @param mesh The mesh to get the candidates sub meshes from
  104262. * @returns the list of active sub meshes
  104263. */
  104264. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  104265. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  104266. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  104267. return intersections;
  104268. }
  104269. return this.scene._getDefaultSubMeshCandidates(mesh);
  104270. };
  104271. /**
  104272. * Return the list of sub meshes intersecting with a given local ray
  104273. * @param mesh defines the mesh to find the submesh for
  104274. * @param localRay defines the ray in local space
  104275. * @returns the list of intersecting sub meshes
  104276. */
  104277. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  104278. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  104279. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  104280. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  104281. return intersections;
  104282. }
  104283. return this.scene._getDefaultSubMeshCandidates(mesh);
  104284. };
  104285. /**
  104286. * Return the list of sub meshes colliding with a collider
  104287. * @param mesh defines the mesh to find the submesh for
  104288. * @param collider defines the collider to evaluate the collision against
  104289. * @returns the list of colliding sub meshes
  104290. */
  104291. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  104292. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  104293. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  104294. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  104295. return intersections;
  104296. }
  104297. return this.scene._getDefaultSubMeshCandidates(mesh);
  104298. };
  104299. /**
  104300. * Rebuilds the elements related to this component in case of
  104301. * context lost for instance.
  104302. */
  104303. OctreeSceneComponent.prototype.rebuild = function () {
  104304. // Nothing to do here.
  104305. };
  104306. /**
  104307. * Disposes the component and the associated ressources.
  104308. */
  104309. OctreeSceneComponent.prototype.dispose = function () {
  104310. // Nothing to do here.
  104311. };
  104312. return OctreeSceneComponent;
  104313. }());
  104314. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  104315. })(BABYLON || (BABYLON = {}));
  104316. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  104317. var BABYLON;
  104318. (function (BABYLON) {
  104319. /**
  104320. * Postprocess used to generate anaglyphic rendering
  104321. */
  104322. var AnaglyphPostProcess = /** @class */ (function (_super) {
  104323. __extends(AnaglyphPostProcess, _super);
  104324. /**
  104325. * Creates a new AnaglyphPostProcess
  104326. * @param name defines postprocess name
  104327. * @param options defines creation options or target ratio scale
  104328. * @param rigCameras defines cameras using this postprocess
  104329. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  104330. * @param engine defines hosting engine
  104331. * @param reusable defines if the postprocess will be reused multiple times per frame
  104332. */
  104333. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  104334. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  104335. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104336. _this.onApplyObservable.add(function (effect) {
  104337. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  104338. });
  104339. return _this;
  104340. }
  104341. return AnaglyphPostProcess;
  104342. }(BABYLON.PostProcess));
  104343. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  104344. })(BABYLON || (BABYLON = {}));
  104345. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  104346. var BABYLON;
  104347. (function (BABYLON) {
  104348. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  104349. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104350. });
  104351. /**
  104352. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  104353. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104354. */
  104355. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  104356. __extends(AnaglyphArcRotateCamera, _super);
  104357. /**
  104358. * Creates a new AnaglyphArcRotateCamera
  104359. * @param name defines camera name
  104360. * @param alpha defines alpha angle (in radians)
  104361. * @param beta defines beta angle (in radians)
  104362. * @param radius defines radius
  104363. * @param target defines camera target
  104364. * @param interaxialDistance defines distance between each color axis
  104365. * @param scene defines the hosting scene
  104366. */
  104367. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  104368. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104369. _this.interaxialDistance = interaxialDistance;
  104370. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104371. return _this;
  104372. }
  104373. /**
  104374. * Gets camera class name
  104375. * @returns AnaglyphArcRotateCamera
  104376. */
  104377. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  104378. return "AnaglyphArcRotateCamera";
  104379. };
  104380. return AnaglyphArcRotateCamera;
  104381. }(BABYLON.ArcRotateCamera));
  104382. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  104383. })(BABYLON || (BABYLON = {}));
  104384. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  104385. var BABYLON;
  104386. (function (BABYLON) {
  104387. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  104388. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104389. });
  104390. /**
  104391. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  104392. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104393. */
  104394. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  104395. __extends(AnaglyphFreeCamera, _super);
  104396. /**
  104397. * Creates a new AnaglyphFreeCamera
  104398. * @param name defines camera name
  104399. * @param position defines initial position
  104400. * @param interaxialDistance defines distance between each color axis
  104401. * @param scene defines the hosting scene
  104402. */
  104403. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  104404. var _this = _super.call(this, name, position, scene) || this;
  104405. _this.interaxialDistance = interaxialDistance;
  104406. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104407. return _this;
  104408. }
  104409. /**
  104410. * Gets camera class name
  104411. * @returns AnaglyphFreeCamera
  104412. */
  104413. AnaglyphFreeCamera.prototype.getClassName = function () {
  104414. return "AnaglyphFreeCamera";
  104415. };
  104416. return AnaglyphFreeCamera;
  104417. }(BABYLON.FreeCamera));
  104418. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  104419. })(BABYLON || (BABYLON = {}));
  104420. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  104421. var BABYLON;
  104422. (function (BABYLON) {
  104423. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  104424. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104425. });
  104426. /**
  104427. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  104428. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104429. */
  104430. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  104431. __extends(AnaglyphGamepadCamera, _super);
  104432. /**
  104433. * Creates a new AnaglyphGamepadCamera
  104434. * @param name defines camera name
  104435. * @param position defines initial position
  104436. * @param interaxialDistance defines distance between each color axis
  104437. * @param scene defines the hosting scene
  104438. */
  104439. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  104440. var _this = _super.call(this, name, position, scene) || this;
  104441. _this.interaxialDistance = interaxialDistance;
  104442. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104443. return _this;
  104444. }
  104445. /**
  104446. * Gets camera class name
  104447. * @returns AnaglyphGamepadCamera
  104448. */
  104449. AnaglyphGamepadCamera.prototype.getClassName = function () {
  104450. return "AnaglyphGamepadCamera";
  104451. };
  104452. return AnaglyphGamepadCamera;
  104453. }(BABYLON.GamepadCamera));
  104454. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  104455. })(BABYLON || (BABYLON = {}));
  104456. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  104457. var BABYLON;
  104458. (function (BABYLON) {
  104459. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  104460. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104461. });
  104462. /**
  104463. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  104464. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104465. */
  104466. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  104467. __extends(AnaglyphUniversalCamera, _super);
  104468. /**
  104469. * Creates a new AnaglyphUniversalCamera
  104470. * @param name defines camera name
  104471. * @param position defines initial position
  104472. * @param interaxialDistance defines distance between each color axis
  104473. * @param scene defines the hosting scene
  104474. */
  104475. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  104476. var _this = _super.call(this, name, position, scene) || this;
  104477. _this.interaxialDistance = interaxialDistance;
  104478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104479. return _this;
  104480. }
  104481. /**
  104482. * Gets camera class name
  104483. * @returns AnaglyphUniversalCamera
  104484. */
  104485. AnaglyphUniversalCamera.prototype.getClassName = function () {
  104486. return "AnaglyphUniversalCamera";
  104487. };
  104488. return AnaglyphUniversalCamera;
  104489. }(BABYLON.UniversalCamera));
  104490. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  104491. })(BABYLON || (BABYLON = {}));
  104492. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  104493. var BABYLON;
  104494. (function (BABYLON) {
  104495. /**
  104496. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  104497. */
  104498. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  104499. __extends(StereoscopicInterlacePostProcess, _super);
  104500. /**
  104501. * Initializes a StereoscopicInterlacePostProcess
  104502. * @param name The name of the effect.
  104503. * @param rigCameras The rig cameras to be appled to the post process
  104504. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  104505. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  104506. * @param engine The engine which the post process will be applied. (default: current engine)
  104507. * @param reusable If the post process can be reused on the same frame. (default: false)
  104508. */
  104509. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  104510. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  104511. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104512. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104513. _this.onSizeChangedObservable.add(function () {
  104514. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104515. });
  104516. _this.onApplyObservable.add(function (effect) {
  104517. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  104518. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  104519. });
  104520. return _this;
  104521. }
  104522. return StereoscopicInterlacePostProcess;
  104523. }(BABYLON.PostProcess));
  104524. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  104525. })(BABYLON || (BABYLON = {}));
  104526. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  104527. var BABYLON;
  104528. (function (BABYLON) {
  104529. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  104530. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104531. });
  104532. /**
  104533. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  104534. * @see http://doc.babylonjs.com/features/cameras
  104535. */
  104536. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  104537. __extends(StereoscopicArcRotateCamera, _super);
  104538. /**
  104539. * Creates a new StereoscopicArcRotateCamera
  104540. * @param name defines camera name
  104541. * @param alpha defines alpha angle (in radians)
  104542. * @param beta defines beta angle (in radians)
  104543. * @param radius defines radius
  104544. * @param target defines camera target
  104545. * @param interaxialDistance defines distance between each color axis
  104546. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104547. * @param scene defines the hosting scene
  104548. */
  104549. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  104550. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104551. _this.interaxialDistance = interaxialDistance;
  104552. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104553. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104554. return _this;
  104555. }
  104556. /**
  104557. * Gets camera class name
  104558. * @returns StereoscopicArcRotateCamera
  104559. */
  104560. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  104561. return "StereoscopicArcRotateCamera";
  104562. };
  104563. return StereoscopicArcRotateCamera;
  104564. }(BABYLON.ArcRotateCamera));
  104565. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  104566. })(BABYLON || (BABYLON = {}));
  104567. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  104568. var BABYLON;
  104569. (function (BABYLON) {
  104570. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104571. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104572. });
  104573. /**
  104574. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  104575. * @see http://doc.babylonjs.com/features/cameras
  104576. */
  104577. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  104578. __extends(StereoscopicFreeCamera, _super);
  104579. /**
  104580. * Creates a new StereoscopicFreeCamera
  104581. * @param name defines camera name
  104582. * @param position defines initial position
  104583. * @param interaxialDistance defines distance between each color axis
  104584. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104585. * @param scene defines the hosting scene
  104586. */
  104587. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104588. var _this = _super.call(this, name, position, scene) || this;
  104589. _this.interaxialDistance = interaxialDistance;
  104590. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104591. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104592. return _this;
  104593. }
  104594. /**
  104595. * Gets camera class name
  104596. * @returns StereoscopicFreeCamera
  104597. */
  104598. StereoscopicFreeCamera.prototype.getClassName = function () {
  104599. return "StereoscopicFreeCamera";
  104600. };
  104601. return StereoscopicFreeCamera;
  104602. }(BABYLON.FreeCamera));
  104603. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  104604. })(BABYLON || (BABYLON = {}));
  104605. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  104606. var BABYLON;
  104607. (function (BABYLON) {
  104608. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  104609. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104610. });
  104611. /**
  104612. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  104613. * @see http://doc.babylonjs.com/features/cameras
  104614. */
  104615. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  104616. __extends(StereoscopicGamepadCamera, _super);
  104617. /**
  104618. * Creates a new StereoscopicGamepadCamera
  104619. * @param name defines camera name
  104620. * @param position defines initial position
  104621. * @param interaxialDistance defines distance between each color axis
  104622. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104623. * @param scene defines the hosting scene
  104624. */
  104625. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104626. var _this = _super.call(this, name, position, scene) || this;
  104627. _this.interaxialDistance = interaxialDistance;
  104628. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104629. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104630. return _this;
  104631. }
  104632. /**
  104633. * Gets camera class name
  104634. * @returns StereoscopicGamepadCamera
  104635. */
  104636. StereoscopicGamepadCamera.prototype.getClassName = function () {
  104637. return "StereoscopicGamepadCamera";
  104638. };
  104639. return StereoscopicGamepadCamera;
  104640. }(BABYLON.GamepadCamera));
  104641. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  104642. })(BABYLON || (BABYLON = {}));
  104643. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  104644. var BABYLON;
  104645. (function (BABYLON) {
  104646. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104647. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104648. });
  104649. /**
  104650. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  104651. * @see http://doc.babylonjs.com/features/cameras
  104652. */
  104653. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  104654. __extends(StereoscopicUniversalCamera, _super);
  104655. /**
  104656. * Creates a new StereoscopicUniversalCamera
  104657. * @param name defines camera name
  104658. * @param position defines initial position
  104659. * @param interaxialDistance defines distance between each color axis
  104660. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104661. * @param scene defines the hosting scene
  104662. */
  104663. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104664. var _this = _super.call(this, name, position, scene) || this;
  104665. _this.interaxialDistance = interaxialDistance;
  104666. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104667. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104668. return _this;
  104669. }
  104670. /**
  104671. * Gets camera class name
  104672. * @returns StereoscopicUniversalCamera
  104673. */
  104674. StereoscopicUniversalCamera.prototype.getClassName = function () {
  104675. return "StereoscopicUniversalCamera";
  104676. };
  104677. return StereoscopicUniversalCamera;
  104678. }(BABYLON.UniversalCamera));
  104679. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  104680. })(BABYLON || (BABYLON = {}));
  104681. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  104682. var BABYLON;
  104683. (function (BABYLON) {
  104684. /**
  104685. * VRDistortionCorrectionPostProcess used for mobile VR
  104686. */
  104687. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  104688. __extends(VRDistortionCorrectionPostProcess, _super);
  104689. /**
  104690. * Initializes the VRDistortionCorrectionPostProcess
  104691. * @param name The name of the effect.
  104692. * @param camera The camera to apply the render pass to.
  104693. * @param isRightEye If this is for the right eye distortion
  104694. * @param vrMetrics All the required metrics for the VR camera
  104695. */
  104696. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  104697. var _this = _super.call(this, name, "vrDistortionCorrection", [
  104698. 'LensCenter',
  104699. 'Scale',
  104700. 'ScaleIn',
  104701. 'HmdWarpParam'
  104702. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  104703. _this._isRightEye = isRightEye;
  104704. _this._distortionFactors = vrMetrics.distortionK;
  104705. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  104706. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  104707. _this.adaptScaleToCurrentViewport = true;
  104708. _this.onSizeChangedObservable.add(function () {
  104709. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  104710. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  104711. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  104712. });
  104713. _this.onApplyObservable.add(function (effect) {
  104714. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  104715. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  104716. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  104717. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  104718. });
  104719. return _this;
  104720. }
  104721. return VRDistortionCorrectionPostProcess;
  104722. }(BABYLON.PostProcess));
  104723. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  104724. })(BABYLON || (BABYLON = {}));
  104725. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  104726. var BABYLON;
  104727. (function (BABYLON) {
  104728. /**
  104729. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  104730. * Screen rotation is taken into account.
  104731. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104732. */
  104733. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  104734. /**
  104735. * Instantiates a new input
  104736. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104737. */
  104738. function FreeCameraDeviceOrientationInput() {
  104739. var _this = this;
  104740. this._screenOrientationAngle = 0;
  104741. this._screenQuaternion = new BABYLON.Quaternion();
  104742. this._alpha = 0;
  104743. this._beta = 0;
  104744. this._gamma = 0;
  104745. this._orientationChanged = function () {
  104746. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0));
  104747. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  104748. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  104749. };
  104750. this._deviceOrientation = function (evt) {
  104751. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  104752. _this._beta = evt.beta !== null ? evt.beta : 0;
  104753. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  104754. };
  104755. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  104756. this._orientationChanged();
  104757. }
  104758. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  104759. /**
  104760. * Define the camera controlled by the input.
  104761. */
  104762. get: function () {
  104763. return this._camera;
  104764. },
  104765. set: function (camera) {
  104766. this._camera = camera;
  104767. if (this._camera != null && !this._camera.rotationQuaternion) {
  104768. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  104769. }
  104770. },
  104771. enumerable: true,
  104772. configurable: true
  104773. });
  104774. /**
  104775. * Attach the input controls to a specific dom element to get the input from.
  104776. * @param element Defines the element the controls should be listened from
  104777. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104778. */
  104779. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104780. window.addEventListener("orientationchange", this._orientationChanged);
  104781. window.addEventListener("deviceorientation", this._deviceOrientation);
  104782. //In certain cases, the attach control is called AFTER orientation was changed,
  104783. //So this is needed.
  104784. this._orientationChanged();
  104785. };
  104786. /**
  104787. * Detach the current controls from the specified dom element.
  104788. * @param element Defines the element to stop listening the inputs from
  104789. */
  104790. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  104791. window.removeEventListener("orientationchange", this._orientationChanged);
  104792. window.removeEventListener("deviceorientation", this._deviceOrientation);
  104793. };
  104794. /**
  104795. * Update the current camera state depending on the inputs that have been used this frame.
  104796. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104797. */
  104798. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  104799. //if no device orientation provided, don't update the rotation.
  104800. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  104801. if (!this._alpha) {
  104802. return;
  104803. }
  104804. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  104805. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  104806. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  104807. //Mirror on XY Plane
  104808. this._camera.rotationQuaternion.z *= -1;
  104809. this._camera.rotationQuaternion.w *= -1;
  104810. };
  104811. /**
  104812. * Gets the class name of the current intput.
  104813. * @returns the class name
  104814. */
  104815. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  104816. return "FreeCameraDeviceOrientationInput";
  104817. };
  104818. /**
  104819. * Get the friendly name associated with the input class.
  104820. * @returns the input friendly name
  104821. */
  104822. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  104823. return "deviceOrientation";
  104824. };
  104825. return FreeCameraDeviceOrientationInput;
  104826. }());
  104827. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  104828. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  104829. })(BABYLON || (BABYLON = {}));
  104830. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  104831. var BABYLON;
  104832. (function (BABYLON) {
  104833. /**
  104834. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  104835. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104836. */
  104837. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  104838. /**
  104839. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  104840. */
  104841. function ArcRotateCameraVRDeviceOrientationInput() {
  104842. /**
  104843. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  104844. */
  104845. this.alphaCorrection = 1;
  104846. /**
  104847. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  104848. */
  104849. this.gammaCorrection = 1;
  104850. this._alpha = 0;
  104851. this._gamma = 0;
  104852. this._dirty = false;
  104853. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  104854. }
  104855. /**
  104856. * Attach the input controls to a specific dom element to get the input from.
  104857. * @param element Defines the element the controls should be listened from
  104858. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104859. */
  104860. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104861. this.camera.attachControl(element, noPreventDefault);
  104862. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  104863. };
  104864. /** @hidden */
  104865. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  104866. if (evt.alpha !== null) {
  104867. this._alpha = (+evt.alpha | 0) * this.alphaCorrection;
  104868. }
  104869. if (evt.gamma !== null) {
  104870. this._gamma = (+evt.gamma | 0) * this.gammaCorrection;
  104871. }
  104872. this._dirty = true;
  104873. };
  104874. /**
  104875. * Update the current camera state depending on the inputs that have been used this frame.
  104876. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104877. */
  104878. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  104879. if (this._dirty) {
  104880. this._dirty = false;
  104881. if (this._gamma < 0) {
  104882. this._gamma = 180 + this._gamma;
  104883. }
  104884. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  104885. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  104886. }
  104887. };
  104888. /**
  104889. * Detach the current controls from the specified dom element.
  104890. * @param element Defines the element to stop listening the inputs from
  104891. */
  104892. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  104893. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  104894. };
  104895. /**
  104896. * Gets the class name of the current intput.
  104897. * @returns the class name
  104898. */
  104899. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  104900. return "ArcRotateCameraVRDeviceOrientationInput";
  104901. };
  104902. /**
  104903. * Get the friendly name associated with the input class.
  104904. * @returns the input friendly name
  104905. */
  104906. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  104907. return "VRDeviceOrientation";
  104908. };
  104909. return ArcRotateCameraVRDeviceOrientationInput;
  104910. }());
  104911. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  104912. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  104913. })(BABYLON || (BABYLON = {}));
  104914. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  104915. var BABYLON;
  104916. (function (BABYLON) {
  104917. /**
  104918. * This represents all the required metrics to create a VR camera.
  104919. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  104920. */
  104921. var VRCameraMetrics = /** @class */ (function () {
  104922. function VRCameraMetrics() {
  104923. /**
  104924. * Define if the current vr camera should compensate the distortion of the lense or not.
  104925. */
  104926. this.compensateDistortion = true;
  104927. }
  104928. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  104929. /**
  104930. * Gets the rendering aspect ratio based on the provided resolutions.
  104931. */
  104932. get: function () {
  104933. return this.hResolution / (2 * this.vResolution);
  104934. },
  104935. enumerable: true,
  104936. configurable: true
  104937. });
  104938. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  104939. /**
  104940. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  104941. */
  104942. get: function () {
  104943. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  104944. },
  104945. enumerable: true,
  104946. configurable: true
  104947. });
  104948. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  104949. /**
  104950. * @hidden
  104951. */
  104952. get: function () {
  104953. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104954. var h = (4 * meters) / this.hScreenSize;
  104955. return BABYLON.Matrix.Translation(h, 0, 0);
  104956. },
  104957. enumerable: true,
  104958. configurable: true
  104959. });
  104960. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  104961. /**
  104962. * @hidden
  104963. */
  104964. get: function () {
  104965. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104966. var h = (4 * meters) / this.hScreenSize;
  104967. return BABYLON.Matrix.Translation(-h, 0, 0);
  104968. },
  104969. enumerable: true,
  104970. configurable: true
  104971. });
  104972. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  104973. /**
  104974. * @hidden
  104975. */
  104976. get: function () {
  104977. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  104978. },
  104979. enumerable: true,
  104980. configurable: true
  104981. });
  104982. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  104983. /**
  104984. * @hidden
  104985. */
  104986. get: function () {
  104987. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  104988. },
  104989. enumerable: true,
  104990. configurable: true
  104991. });
  104992. /**
  104993. * Get the default VRMetrics based on the most generic setup.
  104994. * @returns the default vr metrics
  104995. */
  104996. VRCameraMetrics.GetDefault = function () {
  104997. var result = new VRCameraMetrics();
  104998. result.hResolution = 1280;
  104999. result.vResolution = 800;
  105000. result.hScreenSize = 0.149759993;
  105001. result.vScreenSize = 0.0935999975;
  105002. result.vScreenCenter = 0.0467999987;
  105003. result.eyeToScreenDistance = 0.0410000011;
  105004. result.lensSeparationDistance = 0.0635000020;
  105005. result.interpupillaryDistance = 0.0640000030;
  105006. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  105007. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  105008. result.postProcessScaleFactor = 1.714605507808412;
  105009. result.lensCenterOffset = 0.151976421;
  105010. return result;
  105011. };
  105012. return VRCameraMetrics;
  105013. }());
  105014. BABYLON.VRCameraMetrics = VRCameraMetrics;
  105015. })(BABYLON || (BABYLON = {}));
  105016. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  105017. var BABYLON;
  105018. (function (BABYLON) {
  105019. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  105020. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105021. });
  105022. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  105023. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105024. });
  105025. /**
  105026. * This represents a WebVR camera.
  105027. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  105028. * @example http://doc.babylonjs.com/how_to/webvr_camera
  105029. */
  105030. var WebVRFreeCamera = /** @class */ (function (_super) {
  105031. __extends(WebVRFreeCamera, _super);
  105032. /**
  105033. * Instantiates a WebVRFreeCamera.
  105034. * @param name The name of the WebVRFreeCamera
  105035. * @param position The starting anchor position for the camera
  105036. * @param scene The scene the camera belongs to
  105037. * @param webVROptions a set of customizable options for the webVRCamera
  105038. */
  105039. function WebVRFreeCamera(name, position, scene, webVROptions) {
  105040. if (webVROptions === void 0) { webVROptions = {}; }
  105041. var _this = _super.call(this, name, position, scene) || this;
  105042. _this.webVROptions = webVROptions;
  105043. /**
  105044. * @hidden
  105045. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  105046. */
  105047. _this._vrDevice = null;
  105048. /**
  105049. * The rawPose of the vrDevice.
  105050. */
  105051. _this.rawPose = null;
  105052. _this._specsVersion = "1.1";
  105053. _this._attached = false;
  105054. _this._descendants = [];
  105055. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  105056. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  105057. /** @hidden */
  105058. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  105059. _this._standingMatrix = null;
  105060. /**
  105061. * Represents device position in babylon space.
  105062. */
  105063. _this.devicePosition = BABYLON.Vector3.Zero();
  105064. /**
  105065. * Represents device rotation in babylon space.
  105066. */
  105067. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  105068. /**
  105069. * The scale of the device to be used when translating from device space to babylon space.
  105070. */
  105071. _this.deviceScaleFactor = 1;
  105072. _this._deviceToWorld = BABYLON.Matrix.Identity();
  105073. _this._worldToDevice = BABYLON.Matrix.Identity();
  105074. /**
  105075. * References to the webVR controllers for the vrDevice.
  105076. */
  105077. _this.controllers = [];
  105078. /**
  105079. * Emits an event when a controller is attached.
  105080. */
  105081. _this.onControllersAttachedObservable = new BABYLON.Observable();
  105082. /**
  105083. * Emits an event when a controller's mesh has been loaded;
  105084. */
  105085. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105086. /**
  105087. * Emits an event when the HMD's pose has been updated.
  105088. */
  105089. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  105090. _this._poseSet = false;
  105091. /**
  105092. * If the rig cameras be used as parent instead of this camera.
  105093. */
  105094. _this.rigParenting = true;
  105095. _this._defaultHeight = undefined;
  105096. _this._htmlElementAttached = null;
  105097. _this._detachIfAttached = function () {
  105098. var vrDisplay = _this.getEngine().getVRDevice();
  105099. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  105100. _this.detachControl(_this._htmlElementAttached);
  105101. }
  105102. };
  105103. _this._workingVector = BABYLON.Vector3.Zero();
  105104. _this._oneVector = BABYLON.Vector3.One();
  105105. _this._workingMatrix = BABYLON.Matrix.Identity();
  105106. _this._tmpMatrix = new BABYLON.Matrix();
  105107. _this._cache.position = BABYLON.Vector3.Zero();
  105108. if (webVROptions.defaultHeight) {
  105109. _this._defaultHeight = webVROptions.defaultHeight;
  105110. _this.position.y = _this._defaultHeight;
  105111. }
  105112. _this.minZ = 0.1;
  105113. //legacy support - the compensation boolean was removed.
  105114. if (arguments.length === 5) {
  105115. _this.webVROptions = arguments[4];
  105116. }
  105117. // default webVR options
  105118. if (_this.webVROptions.trackPosition == undefined) {
  105119. _this.webVROptions.trackPosition = true;
  105120. }
  105121. if (_this.webVROptions.controllerMeshes == undefined) {
  105122. _this.webVROptions.controllerMeshes = true;
  105123. }
  105124. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  105125. _this.webVROptions.defaultLightingOnControllers = true;
  105126. }
  105127. _this.rotationQuaternion = new BABYLON.Quaternion();
  105128. if (_this.webVROptions && _this.webVROptions.positionScale) {
  105129. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  105130. }
  105131. //enable VR
  105132. var engine = _this.getEngine();
  105133. _this._onVREnabled = function (success) { if (success) {
  105134. _this.initControllers();
  105135. } };
  105136. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  105137. engine.initWebVR().add(function (event) {
  105138. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  105139. return;
  105140. }
  105141. _this._vrDevice = event.vrDisplay;
  105142. //reset the rig parameters.
  105143. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  105144. if (_this._attached) {
  105145. _this.getEngine().enableVR();
  105146. }
  105147. });
  105148. if (typeof (VRFrameData) !== "undefined") {
  105149. _this._frameData = new VRFrameData();
  105150. }
  105151. /**
  105152. * The idea behind the following lines:
  105153. * objects that have the camera as parent should actually have the rig cameras as a parent.
  105154. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  105155. * the second will not show it correctly.
  105156. *
  105157. * To solve this - each object that has the camera as parent will be added to a protected array.
  105158. * When the rig camera renders, it will take this array and set all of those to be its children.
  105159. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  105160. * Amazing!
  105161. */
  105162. scene.onBeforeCameraRenderObservable.add(function (camera) {
  105163. if (camera.parent === _this && _this.rigParenting) {
  105164. _this._descendants = _this.getDescendants(true, function (n) {
  105165. // don't take the cameras or the controllers!
  105166. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  105167. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  105168. return !isController && !isRigCamera;
  105169. });
  105170. _this._descendants.forEach(function (node) {
  105171. node.parent = camera;
  105172. });
  105173. }
  105174. });
  105175. scene.onAfterCameraRenderObservable.add(function (camera) {
  105176. if (camera.parent === _this && _this.rigParenting) {
  105177. _this._descendants.forEach(function (node) {
  105178. node.parent = _this;
  105179. });
  105180. }
  105181. });
  105182. return _this;
  105183. }
  105184. /**
  105185. * Gets the device distance from the ground in meters.
  105186. * @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.
  105187. */
  105188. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  105189. if (this._standingMatrix) {
  105190. // Add standing matrix offset to get real offset from ground in room
  105191. this._standingMatrix.getTranslationToRef(this._workingVector);
  105192. return this._deviceRoomPosition.y + this._workingVector.y;
  105193. }
  105194. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  105195. return this._defaultHeight || 0;
  105196. };
  105197. /**
  105198. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105199. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  105200. */
  105201. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  105202. var _this = this;
  105203. if (callback === void 0) { callback = function (bool) { }; }
  105204. // Use standing matrix if available
  105205. this.getEngine().initWebVRAsync().then(function (result) {
  105206. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  105207. callback(false);
  105208. }
  105209. else {
  105210. _this._standingMatrix = new BABYLON.Matrix();
  105211. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  105212. if (!_this.getScene().useRightHandedSystem) {
  105213. if (_this._standingMatrix) {
  105214. _this._standingMatrix.toggleModelMatrixHandInPlace();
  105215. }
  105216. }
  105217. callback(true);
  105218. }
  105219. });
  105220. };
  105221. /**
  105222. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105223. * @returns A promise with a boolean set to if the standing matrix is supported.
  105224. */
  105225. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  105226. var _this = this;
  105227. return new Promise(function (res, rej) {
  105228. _this.useStandingMatrix(function (supported) {
  105229. res(supported);
  105230. });
  105231. });
  105232. };
  105233. /**
  105234. * Disposes the camera
  105235. */
  105236. WebVRFreeCamera.prototype.dispose = function () {
  105237. this._detachIfAttached();
  105238. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  105239. if (this._updateCacheWhenTrackingDisabledObserver) {
  105240. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  105241. }
  105242. _super.prototype.dispose.call(this);
  105243. };
  105244. /**
  105245. * Gets a vrController by name.
  105246. * @param name The name of the controller to retreive
  105247. * @returns the controller matching the name specified or null if not found
  105248. */
  105249. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  105250. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  105251. var gp = _a[_i];
  105252. if (gp.hand === name) {
  105253. return gp;
  105254. }
  105255. }
  105256. return null;
  105257. };
  105258. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  105259. /**
  105260. * The controller corrisponding to the users left hand.
  105261. */
  105262. get: function () {
  105263. if (!this._leftController) {
  105264. this._leftController = this.getControllerByName("left");
  105265. }
  105266. return this._leftController;
  105267. },
  105268. enumerable: true,
  105269. configurable: true
  105270. });
  105271. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  105272. /**
  105273. * The controller corrisponding to the users right hand.
  105274. */
  105275. get: function () {
  105276. if (!this._rightController) {
  105277. this._rightController = this.getControllerByName("right");
  105278. }
  105279. return this._rightController;
  105280. },
  105281. enumerable: true,
  105282. configurable: true
  105283. });
  105284. /**
  105285. * Casts a ray forward from the vrCamera's gaze.
  105286. * @param length Length of the ray (default: 100)
  105287. * @returns the ray corrisponding to the gaze
  105288. */
  105289. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  105290. if (length === void 0) { length = 100; }
  105291. if (this.leftCamera) {
  105292. // Use left eye to avoid computation to compute center on every call
  105293. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  105294. }
  105295. else {
  105296. return _super.prototype.getForwardRay.call(this, length);
  105297. }
  105298. };
  105299. /**
  105300. * @hidden
  105301. * Updates the camera based on device's frame data
  105302. */
  105303. WebVRFreeCamera.prototype._checkInputs = function () {
  105304. if (this._vrDevice && this._vrDevice.isPresenting) {
  105305. this._vrDevice.getFrameData(this._frameData);
  105306. this.updateFromDevice(this._frameData.pose);
  105307. }
  105308. _super.prototype._checkInputs.call(this);
  105309. };
  105310. /**
  105311. * Updates the poseControlled values based on the input device pose.
  105312. * @param poseData Pose coming from the device
  105313. */
  105314. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  105315. if (poseData && poseData.orientation) {
  105316. this.rawPose = poseData;
  105317. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  105318. if (this.getScene().useRightHandedSystem) {
  105319. this._deviceRoomRotationQuaternion.z *= -1;
  105320. this._deviceRoomRotationQuaternion.w *= -1;
  105321. }
  105322. if (this.webVROptions.trackPosition && this.rawPose.position) {
  105323. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  105324. if (this.getScene().useRightHandedSystem) {
  105325. this._deviceRoomPosition.z *= -1;
  105326. }
  105327. }
  105328. this._poseSet = true;
  105329. }
  105330. };
  105331. /**
  105332. * WebVR's attach control will start broadcasting frames to the device.
  105333. * Note that in certain browsers (chrome for example) this function must be called
  105334. * within a user-interaction callback. Example:
  105335. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  105336. *
  105337. * @param element html element to attach the vrDevice to
  105338. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  105339. */
  105340. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  105341. _super.prototype.attachControl.call(this, element, noPreventDefault);
  105342. this._attached = true;
  105343. this._htmlElementAttached = element;
  105344. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  105345. if (this._vrDevice) {
  105346. this.getEngine().enableVR();
  105347. }
  105348. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105349. };
  105350. /**
  105351. * Detaches the camera from the html element and disables VR
  105352. *
  105353. * @param element html element to detach from
  105354. */
  105355. WebVRFreeCamera.prototype.detachControl = function (element) {
  105356. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  105357. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  105358. _super.prototype.detachControl.call(this, element);
  105359. this._attached = false;
  105360. this.getEngine().disableVR();
  105361. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105362. };
  105363. /**
  105364. * @returns the name of this class
  105365. */
  105366. WebVRFreeCamera.prototype.getClassName = function () {
  105367. return "WebVRFreeCamera";
  105368. };
  105369. /**
  105370. * Calls resetPose on the vrDisplay
  105371. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  105372. */
  105373. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  105374. //uses the vrDisplay's "resetPose()".
  105375. //pitch and roll won't be affected.
  105376. this._vrDevice.resetPose();
  105377. };
  105378. /**
  105379. * @hidden
  105380. * Updates the rig cameras (left and right eye)
  105381. */
  105382. WebVRFreeCamera.prototype._updateRigCameras = function () {
  105383. var camLeft = this._rigCameras[0];
  105384. var camRight = this._rigCameras[1];
  105385. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105386. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105387. camLeft.position.copyFrom(this._deviceRoomPosition);
  105388. camRight.position.copyFrom(this._deviceRoomPosition);
  105389. };
  105390. // Remove translation from 6dof headset if trackposition is set to false
  105391. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  105392. if (isViewMatrix === void 0) { isViewMatrix = false; }
  105393. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  105394. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  105395. if (!isViewMatrix) {
  105396. this._tmpMatrix.invert();
  105397. }
  105398. this._tmpMatrix.multiplyToRef(matrix, matrix);
  105399. }
  105400. };
  105401. /**
  105402. * @hidden
  105403. * Updates the cached values of the camera
  105404. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  105405. */
  105406. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  105407. var _this = this;
  105408. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  105409. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  105410. if (!this.updateCacheCalled) {
  105411. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  105412. this.updateCacheCalled = true;
  105413. this.update();
  105414. }
  105415. // Set working vector to the device position in room space rotated by the new rotation
  105416. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  105417. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  105418. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  105419. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  105420. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  105421. // Add translation from anchor position
  105422. this._deviceToWorld.getTranslationToRef(this._workingVector);
  105423. this._workingVector.addInPlace(this.position);
  105424. this._workingVector.subtractInPlace(this._cache.position);
  105425. this._deviceToWorld.setTranslation(this._workingVector);
  105426. // Set an inverted matrix to be used when updating the camera
  105427. this._deviceToWorld.invertToRef(this._worldToDevice);
  105428. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  105429. this.controllers.forEach(function (controller) {
  105430. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  105431. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  105432. controller.update();
  105433. });
  105434. }
  105435. if (!ignoreParentClass) {
  105436. _super.prototype._updateCache.call(this);
  105437. }
  105438. this.updateCacheCalled = false;
  105439. };
  105440. /**
  105441. * @hidden
  105442. * Get current device position in babylon world
  105443. */
  105444. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  105445. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  105446. };
  105447. /**
  105448. * Updates the current device position and rotation in the babylon world
  105449. */
  105450. WebVRFreeCamera.prototype.update = function () {
  105451. this._computeDevicePosition();
  105452. // Get current device rotation in babylon world
  105453. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  105454. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  105455. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  105456. if (this._poseSet) {
  105457. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  105458. }
  105459. _super.prototype.update.call(this);
  105460. };
  105461. /**
  105462. * @hidden
  105463. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  105464. * @returns an identity matrix
  105465. */
  105466. WebVRFreeCamera.prototype._getViewMatrix = function () {
  105467. return BABYLON.Matrix.Identity();
  105468. };
  105469. /**
  105470. * This function is called by the two RIG cameras.
  105471. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  105472. */
  105473. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  105474. // Update the parent camera prior to using a child camera to avoid desynchronization
  105475. var parentCamera = this._cameraRigParams["parentCamera"];
  105476. parentCamera._updateCache();
  105477. //WebVR 1.1
  105478. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  105479. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  105480. if (!this.getScene().useRightHandedSystem) {
  105481. this._webvrViewMatrix.toggleModelMatrixHandInPlace();
  105482. }
  105483. // update the camera rotation matrix
  105484. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  105485. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  105486. // Computing target and final matrix
  105487. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  105488. // should the view matrix be updated with scale and position offset?
  105489. if (parentCamera.deviceScaleFactor !== 1) {
  105490. this._webvrViewMatrix.invert();
  105491. // scale the position, if set
  105492. if (parentCamera.deviceScaleFactor) {
  105493. this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);
  105494. this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);
  105495. this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);
  105496. }
  105497. this._webvrViewMatrix.invert();
  105498. }
  105499. // Remove translation from 6dof headset if trackposition is set to false
  105500. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  105501. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  105502. // Compute global position
  105503. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  105504. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  105505. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  105506. this._workingMatrix.getTranslationToRef(this._globalPosition);
  105507. this._markSyncedWithParent();
  105508. return this._webvrViewMatrix;
  105509. };
  105510. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  105511. var parentCamera = this.parent;
  105512. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  105513. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  105514. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  105515. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  105516. //babylon compatible matrix
  105517. if (!this.getScene().useRightHandedSystem) {
  105518. this._projectionMatrix.toggleProjectionMatrixHandInPlace();
  105519. }
  105520. return this._projectionMatrix;
  105521. };
  105522. /**
  105523. * Initializes the controllers and their meshes
  105524. */
  105525. WebVRFreeCamera.prototype.initControllers = function () {
  105526. var _this = this;
  105527. this.controllers = [];
  105528. var manager = this.getScene().gamepadManager;
  105529. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  105530. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105531. var webVrController = gamepad;
  105532. if (webVrController.defaultModel) {
  105533. webVrController.defaultModel.setEnabled(false);
  105534. }
  105535. if (webVrController.hand === "right") {
  105536. _this._rightController = null;
  105537. }
  105538. if (webVrController.hand === "left") {
  105539. _this._leftController = null;
  105540. }
  105541. var controllerIndex = _this.controllers.indexOf(webVrController);
  105542. if (controllerIndex !== -1) {
  105543. _this.controllers.splice(controllerIndex, 1);
  105544. }
  105545. }
  105546. });
  105547. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  105548. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105549. var webVrController_1 = gamepad;
  105550. if (!_this.webVROptions.trackPosition) {
  105551. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  105552. // Cache must be updated before rendering controllers to avoid them being one frame behind
  105553. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  105554. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  105555. _this._updateCache();
  105556. });
  105557. }
  105558. }
  105559. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  105560. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  105561. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  105562. if (_this.webVROptions.controllerMeshes) {
  105563. if (webVrController_1.defaultModel) {
  105564. webVrController_1.defaultModel.setEnabled(true);
  105565. }
  105566. else {
  105567. // Load the meshes
  105568. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  105569. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  105570. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  105571. if (_this.webVROptions.defaultLightingOnControllers) {
  105572. if (!_this._lightOnControllers) {
  105573. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  105574. }
  105575. var activateLightOnSubMeshes_1 = function (mesh, light) {
  105576. var children = mesh.getChildren();
  105577. if (children && children.length !== 0) {
  105578. children.forEach(function (mesh) {
  105579. light.includedOnlyMeshes.push(mesh);
  105580. activateLightOnSubMeshes_1(mesh, light);
  105581. });
  105582. }
  105583. };
  105584. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  105585. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  105586. }
  105587. });
  105588. }
  105589. }
  105590. webVrController_1.attachToPoseControlledCamera(_this);
  105591. // since this is async - sanity check. Is the controller already stored?
  105592. if (_this.controllers.indexOf(webVrController_1) === -1) {
  105593. //add to the controllers array
  105594. _this.controllers.push(webVrController_1);
  105595. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  105596. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  105597. // So we're overriding setting left & right manually to be sure
  105598. var firstViveWandDetected = false;
  105599. for (var i = 0; i < _this.controllers.length; i++) {
  105600. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105601. if (!firstViveWandDetected) {
  105602. firstViveWandDetected = true;
  105603. _this.controllers[i].hand = "left";
  105604. }
  105605. else {
  105606. _this.controllers[i].hand = "right";
  105607. }
  105608. }
  105609. }
  105610. //did we find enough controllers? Great! let the developer know.
  105611. if (_this.controllers.length >= 2) {
  105612. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  105613. }
  105614. }
  105615. }
  105616. });
  105617. };
  105618. return WebVRFreeCamera;
  105619. }(BABYLON.FreeCamera));
  105620. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  105621. })(BABYLON || (BABYLON = {}));
  105622. //# sourceMappingURL=babylon.webVRCamera.js.map
  105623. var BABYLON;
  105624. (function (BABYLON) {
  105625. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  105626. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  105627. });
  105628. // We're mainly based on the logic defined into the FreeCamera code
  105629. /**
  105630. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  105631. * being tilted forward or back and left or right.
  105632. */
  105633. var DeviceOrientationCamera = /** @class */ (function (_super) {
  105634. __extends(DeviceOrientationCamera, _super);
  105635. /**
  105636. * Creates a new device orientation camera
  105637. * @param name The name of the camera
  105638. * @param position The start position camera
  105639. * @param scene The scene the camera belongs to
  105640. */
  105641. function DeviceOrientationCamera(name, position, scene) {
  105642. var _this = _super.call(this, name, position, scene) || this;
  105643. _this._quaternionCache = new BABYLON.Quaternion();
  105644. _this.inputs.addDeviceOrientation();
  105645. return _this;
  105646. }
  105647. /**
  105648. * Gets the current instance class name ("DeviceOrientationCamera").
  105649. * This helps avoiding instanceof at run time.
  105650. * @returns the class name
  105651. */
  105652. DeviceOrientationCamera.prototype.getClassName = function () {
  105653. return "DeviceOrientationCamera";
  105654. };
  105655. /**
  105656. * @hidden
  105657. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  105658. */
  105659. DeviceOrientationCamera.prototype._checkInputs = function () {
  105660. _super.prototype._checkInputs.call(this);
  105661. this._quaternionCache.copyFrom(this.rotationQuaternion);
  105662. if (this._initialQuaternion) {
  105663. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105664. }
  105665. };
  105666. /**
  105667. * Reset the camera to its default orientation on the specified axis only.
  105668. * @param axis The axis to reset
  105669. */
  105670. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  105671. var _this = this;
  105672. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  105673. //can only work if this camera has a rotation quaternion already.
  105674. if (!this.rotationQuaternion) {
  105675. return;
  105676. }
  105677. if (!this._initialQuaternion) {
  105678. this._initialQuaternion = new BABYLON.Quaternion();
  105679. }
  105680. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  105681. ['x', 'y', 'z'].forEach(function (axisName) {
  105682. if (!axis[axisName]) {
  105683. _this._initialQuaternion[axisName] = 0;
  105684. }
  105685. else {
  105686. _this._initialQuaternion[axisName] *= -1;
  105687. }
  105688. });
  105689. this._initialQuaternion.normalize();
  105690. //force rotation update
  105691. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105692. };
  105693. return DeviceOrientationCamera;
  105694. }(BABYLON.FreeCamera));
  105695. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  105696. })(BABYLON || (BABYLON = {}));
  105697. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  105698. var BABYLON;
  105699. (function (BABYLON) {
  105700. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105701. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105702. });
  105703. /**
  105704. * Camera used to simulate VR rendering (based on FreeCamera)
  105705. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105706. */
  105707. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  105708. __extends(VRDeviceOrientationFreeCamera, _super);
  105709. /**
  105710. * Creates a new VRDeviceOrientationFreeCamera
  105711. * @param name defines camera name
  105712. * @param position defines the start position of the camera
  105713. * @param scene defines the scene the camera belongs to
  105714. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105715. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105716. */
  105717. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105718. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105719. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105720. var _this = _super.call(this, name, position, scene) || this;
  105721. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105722. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105723. return _this;
  105724. }
  105725. /**
  105726. * Gets camera class name
  105727. * @returns VRDeviceOrientationFreeCamera
  105728. */
  105729. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  105730. return "VRDeviceOrientationFreeCamera";
  105731. };
  105732. return VRDeviceOrientationFreeCamera;
  105733. }(BABYLON.DeviceOrientationCamera));
  105734. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  105735. })(BABYLON || (BABYLON = {}));
  105736. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  105737. var BABYLON;
  105738. (function (BABYLON) {
  105739. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105740. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  105741. });
  105742. /**
  105743. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  105744. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105745. */
  105746. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  105747. __extends(VRDeviceOrientationArcRotateCamera, _super);
  105748. /**
  105749. * Creates a new VRDeviceOrientationArcRotateCamera
  105750. * @param name defines camera name
  105751. * @param alpha defines the camera rotation along the logitudinal axis
  105752. * @param beta defines the camera rotation along the latitudinal axis
  105753. * @param radius defines the camera distance from its target
  105754. * @param target defines the camera target
  105755. * @param scene defines the scene the camera belongs to
  105756. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105757. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105758. */
  105759. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  105760. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105761. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105762. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  105763. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105764. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105765. _this.inputs.addVRDeviceOrientation();
  105766. return _this;
  105767. }
  105768. /**
  105769. * Gets camera class name
  105770. * @returns VRDeviceOrientationArcRotateCamera
  105771. */
  105772. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  105773. return "VRDeviceOrientationArcRotateCamera";
  105774. };
  105775. return VRDeviceOrientationArcRotateCamera;
  105776. }(BABYLON.ArcRotateCamera));
  105777. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  105778. })(BABYLON || (BABYLON = {}));
  105779. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  105780. var BABYLON;
  105781. (function (BABYLON) {
  105782. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  105783. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  105784. });
  105785. /**
  105786. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  105787. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105788. */
  105789. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  105790. __extends(VRDeviceOrientationGamepadCamera, _super);
  105791. /**
  105792. * Creates a new VRDeviceOrientationGamepadCamera
  105793. * @param name defines camera name
  105794. * @param position defines the start position of the camera
  105795. * @param scene defines the scene the camera belongs to
  105796. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105797. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105798. */
  105799. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105800. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105801. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105802. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  105803. _this.inputs.addGamepad();
  105804. return _this;
  105805. }
  105806. /**
  105807. * Gets camera class name
  105808. * @returns VRDeviceOrientationGamepadCamera
  105809. */
  105810. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  105811. return "VRDeviceOrientationGamepadCamera";
  105812. };
  105813. return VRDeviceOrientationGamepadCamera;
  105814. }(BABYLON.VRDeviceOrientationFreeCamera));
  105815. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  105816. })(BABYLON || (BABYLON = {}));
  105817. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  105818. var BABYLON;
  105819. (function (BABYLON) {
  105820. var VRExperienceHelperGazer = /** @class */ (function () {
  105821. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  105822. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  105823. this.scene = scene;
  105824. /** @hidden */
  105825. this._pointerDownOnMeshAsked = false;
  105826. /** @hidden */
  105827. this._isActionableMesh = false;
  105828. /** @hidden */
  105829. this._teleportationRequestInitiated = false;
  105830. /** @hidden */
  105831. this._teleportationBackRequestInitiated = false;
  105832. /** @hidden */
  105833. this._rotationRightAsked = false;
  105834. /** @hidden */
  105835. this._rotationLeftAsked = false;
  105836. /** @hidden */
  105837. this._dpadPressed = true;
  105838. /** @hidden */
  105839. this._activePointer = false;
  105840. this._id = VRExperienceHelperGazer._idCounter++;
  105841. // Gaze tracker
  105842. if (!gazeTrackerToClone) {
  105843. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  105844. this._gazeTracker.bakeCurrentTransformIntoVertices();
  105845. this._gazeTracker.isPickable = false;
  105846. this._gazeTracker.isVisible = false;
  105847. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  105848. targetMat.specularColor = BABYLON.Color3.Black();
  105849. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105850. targetMat.backFaceCulling = false;
  105851. this._gazeTracker.material = targetMat;
  105852. }
  105853. else {
  105854. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  105855. }
  105856. }
  105857. /** @hidden */
  105858. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  105859. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  105860. };
  105861. /** @hidden */
  105862. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  105863. this._pointerDownOnMeshAsked = true;
  105864. if (this._currentHit) {
  105865. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  105866. }
  105867. };
  105868. /** @hidden */
  105869. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  105870. if (this._currentHit) {
  105871. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  105872. }
  105873. this._pointerDownOnMeshAsked = false;
  105874. };
  105875. /** @hidden */
  105876. VRExperienceHelperGazer.prototype._activatePointer = function () {
  105877. this._activePointer = true;
  105878. };
  105879. /** @hidden */
  105880. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  105881. this._activePointer = false;
  105882. };
  105883. /** @hidden */
  105884. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  105885. if (distance === void 0) { distance = 100; }
  105886. };
  105887. VRExperienceHelperGazer.prototype.dispose = function () {
  105888. this._interactionsEnabled = false;
  105889. this._teleportationEnabled = false;
  105890. if (this._gazeTracker) {
  105891. this._gazeTracker.dispose();
  105892. }
  105893. };
  105894. VRExperienceHelperGazer._idCounter = 0;
  105895. return VRExperienceHelperGazer;
  105896. }());
  105897. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  105898. __extends(VRExperienceHelperControllerGazer, _super);
  105899. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  105900. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  105901. _this.webVRController = webVRController;
  105902. // Laser pointer
  105903. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  105904. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  105905. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105906. laserPointerMaterial.alpha = 0.6;
  105907. _this._laserPointer.material = laserPointerMaterial;
  105908. _this._laserPointer.rotation.x = Math.PI / 2;
  105909. _this._laserPointer.position.z = -0.5;
  105910. _this._laserPointer.isVisible = false;
  105911. _this._laserPointer.isPickable = false;
  105912. if (!webVRController.mesh) {
  105913. // Create an empty mesh that is used prior to loading the high quality model
  105914. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  105915. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  105916. preloadPointerPose.rotation.x = -0.7;
  105917. preloadMesh.addChild(preloadPointerPose);
  105918. webVRController.attachToMesh(preloadMesh);
  105919. }
  105920. _this._setLaserPointerParent(webVRController.mesh);
  105921. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  105922. _this._setLaserPointerParent(mesh);
  105923. });
  105924. return _this;
  105925. }
  105926. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  105927. return this.webVRController.getForwardRay(length);
  105928. };
  105929. /** @hidden */
  105930. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  105931. _super.prototype._activatePointer.call(this);
  105932. this._laserPointer.isVisible = true;
  105933. };
  105934. /** @hidden */
  105935. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  105936. _super.prototype._deactivatePointer.call(this);
  105937. this._laserPointer.isVisible = false;
  105938. };
  105939. /** @hidden */
  105940. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  105941. this._laserPointer.material.emissiveColor = color;
  105942. };
  105943. /** @hidden */
  105944. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  105945. var makeNotPick = function (root) {
  105946. root.isPickable = false;
  105947. root.getChildMeshes().forEach(function (c) {
  105948. makeNotPick(c);
  105949. });
  105950. };
  105951. makeNotPick(mesh);
  105952. var childMeshes = mesh.getChildMeshes();
  105953. this.webVRController._pointingPoseNode = null;
  105954. for (var i = 0; i < childMeshes.length; i++) {
  105955. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  105956. mesh = childMeshes[i];
  105957. this.webVRController._pointingPoseNode = mesh;
  105958. break;
  105959. }
  105960. }
  105961. this._laserPointer.parent = mesh;
  105962. };
  105963. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  105964. if (distance === void 0) { distance = 100; }
  105965. this._laserPointer.scaling.y = distance;
  105966. this._laserPointer.position.z = -distance / 2;
  105967. };
  105968. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  105969. _super.prototype.dispose.call(this);
  105970. this._laserPointer.dispose();
  105971. if (this._meshAttachedObserver) {
  105972. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  105973. }
  105974. };
  105975. return VRExperienceHelperControllerGazer;
  105976. }(VRExperienceHelperGazer));
  105977. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  105978. __extends(VRExperienceHelperCameraGazer, _super);
  105979. function VRExperienceHelperCameraGazer(getCamera, scene) {
  105980. var _this = _super.call(this, scene) || this;
  105981. _this.getCamera = getCamera;
  105982. return _this;
  105983. }
  105984. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  105985. var camera = this.getCamera();
  105986. if (camera) {
  105987. return camera.getForwardRay(length);
  105988. }
  105989. else {
  105990. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  105991. }
  105992. };
  105993. return VRExperienceHelperCameraGazer;
  105994. }(VRExperienceHelperGazer));
  105995. /**
  105996. * Helps to quickly add VR support to an existing scene.
  105997. * See http://doc.babylonjs.com/how_to/webvr_helper
  105998. */
  105999. var VRExperienceHelper = /** @class */ (function () {
  106000. /**
  106001. * Instantiates a VRExperienceHelper.
  106002. * Helps to quickly add VR support to an existing scene.
  106003. * @param scene The scene the VRExperienceHelper belongs to.
  106004. * @param webVROptions Options to modify the vr experience helper's behavior.
  106005. */
  106006. function VRExperienceHelper(scene,
  106007. /** Options to modify the vr experience helper's behavior. */
  106008. webVROptions) {
  106009. if (webVROptions === void 0) { webVROptions = {}; }
  106010. var _this = this;
  106011. this.webVROptions = webVROptions;
  106012. // Can the system support WebVR, even if a headset isn't plugged in?
  106013. this._webVRsupported = false;
  106014. // If WebVR is supported, is a headset plugged in and are we ready to present?
  106015. this._webVRready = false;
  106016. // Are we waiting for the requestPresent callback to complete?
  106017. this._webVRrequesting = false;
  106018. // Are we presenting to the headset right now? (this is the vrDevice state)
  106019. this._webVRpresenting = false;
  106020. // Are we presenting in the fullscreen fallback?
  106021. this._fullscreenVRpresenting = false;
  106022. /**
  106023. * Observable raised when entering VR.
  106024. */
  106025. this.onEnteringVRObservable = new BABYLON.Observable();
  106026. /**
  106027. * Observable raised when exiting VR.
  106028. */
  106029. this.onExitingVRObservable = new BABYLON.Observable();
  106030. /**
  106031. * Observable raised when controller mesh is loaded.
  106032. */
  106033. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  106034. this._useCustomVRButton = false;
  106035. this._teleportationRequested = false;
  106036. this._teleportActive = false;
  106037. this._floorMeshesCollection = [];
  106038. this._rotationAllowed = true;
  106039. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  106040. this._isDefaultTeleportationTarget = true;
  106041. this._teleportationFillColor = "#444444";
  106042. this._teleportationBorderColor = "#FFFFFF";
  106043. this._rotationAngle = 0;
  106044. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  106045. this._padSensibilityUp = 0.65;
  106046. this._padSensibilityDown = 0.35;
  106047. this._leftController = null;
  106048. this._rightController = null;
  106049. /**
  106050. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  106051. */
  106052. this.onNewMeshSelected = new BABYLON.Observable();
  106053. /**
  106054. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  106055. */
  106056. this.onNewMeshPicked = new BABYLON.Observable();
  106057. /**
  106058. * Observable raised before camera teleportation
  106059. */
  106060. this.onBeforeCameraTeleport = new BABYLON.Observable();
  106061. /**
  106062. * Observable raised after camera teleportation
  106063. */
  106064. this.onAfterCameraTeleport = new BABYLON.Observable();
  106065. /**
  106066. * Observable raised when current selected mesh gets unselected
  106067. */
  106068. this.onSelectedMeshUnselected = new BABYLON.Observable();
  106069. /**
  106070. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  106071. */
  106072. this.teleportationEnabled = true;
  106073. this._teleportationInitialized = false;
  106074. this._interactionsEnabled = false;
  106075. this._interactionsRequested = false;
  106076. this._displayGaze = true;
  106077. this._displayLaserPointer = true;
  106078. /**
  106079. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  106080. */
  106081. this.updateGazeTrackerScale = true;
  106082. this._onResize = function () {
  106083. _this.moveButtonToBottomRight();
  106084. if (_this._fullscreenVRpresenting && _this._webVRready) {
  106085. _this.exitVR();
  106086. }
  106087. };
  106088. this._onFullscreenChange = function () {
  106089. if (document.fullscreen !== undefined) {
  106090. _this._fullscreenVRpresenting = document.fullscreen;
  106091. }
  106092. else if (document.mozFullScreen !== undefined) {
  106093. _this._fullscreenVRpresenting = document.mozFullScreen;
  106094. }
  106095. else if (document.webkitIsFullScreen !== undefined) {
  106096. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  106097. }
  106098. else if (document.msIsFullScreen !== undefined) {
  106099. _this._fullscreenVRpresenting = document.msIsFullScreen;
  106100. }
  106101. else if (document.msFullscreenElement !== undefined) {
  106102. _this._fullscreenVRpresenting = document.msFullscreenElement;
  106103. }
  106104. if (!_this._fullscreenVRpresenting && _this._canvas) {
  106105. _this.exitVR();
  106106. if (!_this._useCustomVRButton) {
  106107. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  106108. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  106109. }
  106110. }
  106111. };
  106112. this.beforeRender = function () {
  106113. if (_this._leftController && _this._leftController._activePointer) {
  106114. _this._castRayAndSelectObject(_this._leftController);
  106115. }
  106116. if (_this._rightController && _this._rightController._activePointer) {
  106117. _this._castRayAndSelectObject(_this._rightController);
  106118. }
  106119. if (_this._noControllerIsActive) {
  106120. _this._castRayAndSelectObject(_this._cameraGazer);
  106121. }
  106122. else {
  106123. _this._cameraGazer._gazeTracker.isVisible = false;
  106124. }
  106125. };
  106126. this._onNewGamepadConnected = function (gamepad) {
  106127. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  106128. if (gamepad.leftStick) {
  106129. gamepad.onleftstickchanged(function (stickValues) {
  106130. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  106131. // Listening to classic/xbox gamepad only if no VR controller is active
  106132. if ((!_this._leftController && !_this._rightController) ||
  106133. ((_this._leftController && !_this._leftController._activePointer) &&
  106134. (_this._rightController && !_this._rightController._activePointer))) {
  106135. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  106136. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  106137. }
  106138. }
  106139. });
  106140. }
  106141. if (gamepad.rightStick) {
  106142. gamepad.onrightstickchanged(function (stickValues) {
  106143. if (_this._teleportationInitialized) {
  106144. _this._checkRotate(stickValues, _this._cameraGazer);
  106145. }
  106146. });
  106147. }
  106148. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  106149. gamepad.onbuttondown(function (buttonPressed) {
  106150. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106151. _this._cameraGazer._selectionPointerDown();
  106152. }
  106153. });
  106154. gamepad.onbuttonup(function (buttonPressed) {
  106155. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106156. _this._cameraGazer._selectionPointerUp();
  106157. }
  106158. });
  106159. }
  106160. }
  106161. else {
  106162. var webVRController = gamepad;
  106163. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  106164. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  106165. _this._rightController = controller;
  106166. }
  106167. else {
  106168. _this._leftController = controller;
  106169. }
  106170. _this._tryEnableInteractionOnController(controller);
  106171. }
  106172. };
  106173. // 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
  106174. this._tryEnableInteractionOnController = function (controller) {
  106175. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  106176. _this._enableInteractionOnController(controller);
  106177. }
  106178. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  106179. _this._enableTeleportationOnController(controller);
  106180. }
  106181. };
  106182. this._onNewGamepadDisconnected = function (gamepad) {
  106183. if (gamepad instanceof BABYLON.WebVRController) {
  106184. if (gamepad.hand === "left" && _this._leftController != null) {
  106185. _this._leftController.dispose();
  106186. _this._leftController = null;
  106187. }
  106188. if (gamepad.hand === "right" && _this._rightController != null) {
  106189. _this._rightController.dispose();
  106190. _this._rightController = null;
  106191. }
  106192. }
  106193. };
  106194. this._workingVector = BABYLON.Vector3.Zero();
  106195. this._workingQuaternion = BABYLON.Quaternion.Identity();
  106196. this._workingMatrix = BABYLON.Matrix.Identity();
  106197. this._scene = scene;
  106198. this._canvas = scene.getEngine().getRenderingCanvas();
  106199. // Parse options
  106200. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  106201. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  106202. }
  106203. if (webVROptions.createDeviceOrientationCamera === undefined) {
  106204. webVROptions.createDeviceOrientationCamera = true;
  106205. }
  106206. if (webVROptions.laserToggle === undefined) {
  106207. webVROptions.laserToggle = true;
  106208. }
  106209. if (webVROptions.defaultHeight === undefined) {
  106210. webVROptions.defaultHeight = 1.7;
  106211. }
  106212. if (webVROptions.useCustomVRButton) {
  106213. this._useCustomVRButton = true;
  106214. if (webVROptions.customVRButton) {
  106215. this._btnVR = webVROptions.customVRButton;
  106216. }
  106217. }
  106218. if (webVROptions.rayLength) {
  106219. this._rayLength = webVROptions.rayLength;
  106220. }
  106221. this._defaultHeight = webVROptions.defaultHeight;
  106222. if (webVROptions.positionScale) {
  106223. this._rayLength *= webVROptions.positionScale;
  106224. this._defaultHeight *= webVROptions.positionScale;
  106225. }
  106226. this._hasEnteredVR = false;
  106227. // Set position
  106228. if (this._scene.activeCamera) {
  106229. this._position = this._scene.activeCamera.position.clone();
  106230. }
  106231. else {
  106232. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  106233. }
  106234. // Set non-vr camera
  106235. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  106236. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  106237. // Copy data from existing camera
  106238. if (this._scene.activeCamera) {
  106239. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106240. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  106241. // Set rotation from previous camera
  106242. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  106243. var targetCamera = this._scene.activeCamera;
  106244. if (targetCamera.rotationQuaternion) {
  106245. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  106246. }
  106247. else {
  106248. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  106249. }
  106250. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  106251. }
  106252. }
  106253. this._scene.activeCamera = this._deviceOrientationCamera;
  106254. if (this._canvas) {
  106255. this._scene.activeCamera.attachControl(this._canvas);
  106256. }
  106257. }
  106258. else {
  106259. this._existingCamera = this._scene.activeCamera;
  106260. }
  106261. // Create VR cameras
  106262. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106263. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  106264. }
  106265. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  106266. this._webVRCamera.useStandingMatrix();
  106267. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  106268. // Create default button
  106269. if (!this._useCustomVRButton) {
  106270. this._btnVR = document.createElement("BUTTON");
  106271. this._btnVR.className = "babylonVRicon";
  106272. this._btnVR.id = "babylonVRiconbtn";
  106273. this._btnVR.title = "Click to switch to VR";
  106274. 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) }";
  106275. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  106276. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  106277. // css += ".babylonVRicon.vrdisplaysupported { }";
  106278. // css += ".babylonVRicon.vrdisplayready { }";
  106279. // css += ".babylonVRicon.vrdisplayrequesting { }";
  106280. var style = document.createElement('style');
  106281. style.appendChild(document.createTextNode(css));
  106282. document.getElementsByTagName('head')[0].appendChild(style);
  106283. this.moveButtonToBottomRight();
  106284. }
  106285. // VR button click event
  106286. if (this._btnVR) {
  106287. this._btnVR.addEventListener("click", function () {
  106288. if (!_this.isInVRMode) {
  106289. _this.enterVR();
  106290. }
  106291. else {
  106292. _this.exitVR();
  106293. }
  106294. });
  106295. }
  106296. // Window events
  106297. window.addEventListener("resize", this._onResize);
  106298. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  106299. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  106300. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  106301. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  106302. document.onmsfullscreenchange = this._onFullscreenChange;
  106303. // Display vr button when headset is connected
  106304. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106305. this.displayVRButton();
  106306. }
  106307. else {
  106308. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  106309. if (e.vrDisplay) {
  106310. _this.displayVRButton();
  106311. }
  106312. });
  106313. }
  106314. // Exiting VR mode using 'ESC' key on desktop
  106315. this._onKeyDown = function (event) {
  106316. if (event.keyCode === 27 && _this.isInVRMode) {
  106317. _this.exitVR();
  106318. }
  106319. };
  106320. document.addEventListener("keydown", this._onKeyDown);
  106321. // Exiting VR mode double tapping the touch screen
  106322. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  106323. if (_this.isInVRMode) {
  106324. _this.exitVR();
  106325. if (_this._fullscreenVRpresenting) {
  106326. _this._scene.getEngine().switchFullscreen(true);
  106327. }
  106328. }
  106329. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  106330. // Listen for WebVR display changes
  106331. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  106332. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  106333. this._onVRRequestPresentStart = function () {
  106334. _this._webVRrequesting = true;
  106335. _this.updateButtonVisibility();
  106336. };
  106337. this._onVRRequestPresentComplete = function (success) {
  106338. _this._webVRrequesting = false;
  106339. _this.updateButtonVisibility();
  106340. };
  106341. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  106342. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  106343. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  106344. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106345. scene.onDisposeObservable.add(function () {
  106346. _this.dispose();
  106347. });
  106348. // Gamepad connection events
  106349. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  106350. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  106351. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  106352. this.updateButtonVisibility();
  106353. //create easing functions
  106354. this._circleEase = new BABYLON.CircleEase();
  106355. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  106356. if (this.webVROptions.floorMeshes) {
  106357. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  106358. }
  106359. }
  106360. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  106361. /** Return this.onEnteringVRObservable
  106362. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  106363. */
  106364. get: function () {
  106365. return this.onEnteringVRObservable;
  106366. },
  106367. enumerable: true,
  106368. configurable: true
  106369. });
  106370. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  106371. /** Return this.onExitingVRObservable
  106372. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  106373. */
  106374. get: function () {
  106375. return this.onExitingVRObservable;
  106376. },
  106377. enumerable: true,
  106378. configurable: true
  106379. });
  106380. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  106381. /** Return this.onControllerMeshLoadedObservable
  106382. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  106383. */
  106384. get: function () {
  106385. return this.onControllerMeshLoadedObservable;
  106386. },
  106387. enumerable: true,
  106388. configurable: true
  106389. });
  106390. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  106391. /**
  106392. * The mesh used to display where the user is going to teleport.
  106393. */
  106394. get: function () {
  106395. return this._teleportationTarget;
  106396. },
  106397. /**
  106398. * Sets the mesh to be used to display where the user is going to teleport.
  106399. */
  106400. set: function (value) {
  106401. if (value) {
  106402. value.name = "teleportationTarget";
  106403. this._isDefaultTeleportationTarget = false;
  106404. this._teleportationTarget = value;
  106405. }
  106406. },
  106407. enumerable: true,
  106408. configurable: true
  106409. });
  106410. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  106411. /**
  106412. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  106413. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  106414. * See http://doc.babylonjs.com/resources/baking_transformations
  106415. */
  106416. get: function () {
  106417. return this._cameraGazer._gazeTracker;
  106418. },
  106419. set: function (value) {
  106420. if (value) {
  106421. // Dispose of existing meshes
  106422. if (this._cameraGazer._gazeTracker) {
  106423. this._cameraGazer._gazeTracker.dispose();
  106424. }
  106425. if (this._leftController && this._leftController._gazeTracker) {
  106426. this._leftController._gazeTracker.dispose();
  106427. }
  106428. if (this._rightController && this._rightController._gazeTracker) {
  106429. this._rightController._gazeTracker.dispose();
  106430. }
  106431. // Set and create gaze trackers on head and controllers
  106432. this._cameraGazer._gazeTracker = value;
  106433. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  106434. this._cameraGazer._gazeTracker.isPickable = false;
  106435. this._cameraGazer._gazeTracker.isVisible = false;
  106436. this._cameraGazer._gazeTracker.name = "gazeTracker";
  106437. if (this._leftController) {
  106438. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106439. }
  106440. if (this._rightController) {
  106441. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106442. }
  106443. }
  106444. },
  106445. enumerable: true,
  106446. configurable: true
  106447. });
  106448. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  106449. /**
  106450. * The gaze tracking mesh corresponding to the left controller
  106451. */
  106452. get: function () {
  106453. if (this._leftController) {
  106454. return this._leftController._gazeTracker;
  106455. }
  106456. return null;
  106457. },
  106458. enumerable: true,
  106459. configurable: true
  106460. });
  106461. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  106462. /**
  106463. * The gaze tracking mesh corresponding to the right controller
  106464. */
  106465. get: function () {
  106466. if (this._rightController) {
  106467. return this._rightController._gazeTracker;
  106468. }
  106469. return null;
  106470. },
  106471. enumerable: true,
  106472. configurable: true
  106473. });
  106474. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  106475. /**
  106476. * If the ray of the gaze should be displayed.
  106477. */
  106478. get: function () {
  106479. return this._displayGaze;
  106480. },
  106481. /**
  106482. * Sets if the ray of the gaze should be displayed.
  106483. */
  106484. set: function (value) {
  106485. this._displayGaze = value;
  106486. if (!value) {
  106487. this._cameraGazer._gazeTracker.isVisible = false;
  106488. if (this._leftController) {
  106489. this._leftController._gazeTracker.isVisible = false;
  106490. }
  106491. if (this._rightController) {
  106492. this._rightController._gazeTracker.isVisible = false;
  106493. }
  106494. }
  106495. },
  106496. enumerable: true,
  106497. configurable: true
  106498. });
  106499. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  106500. /**
  106501. * If the ray of the LaserPointer should be displayed.
  106502. */
  106503. get: function () {
  106504. return this._displayLaserPointer;
  106505. },
  106506. /**
  106507. * Sets if the ray of the LaserPointer should be displayed.
  106508. */
  106509. set: function (value) {
  106510. this._displayLaserPointer = value;
  106511. if (!value) {
  106512. if (this._rightController) {
  106513. this._rightController._deactivatePointer();
  106514. this._rightController._gazeTracker.isVisible = false;
  106515. }
  106516. if (this._leftController) {
  106517. this._leftController._deactivatePointer();
  106518. this._leftController._gazeTracker.isVisible = false;
  106519. }
  106520. }
  106521. else {
  106522. if (this._rightController) {
  106523. this._rightController._activatePointer();
  106524. }
  106525. if (this._leftController) {
  106526. this._leftController._activatePointer();
  106527. }
  106528. }
  106529. },
  106530. enumerable: true,
  106531. configurable: true
  106532. });
  106533. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  106534. /**
  106535. * The deviceOrientationCamera used as the camera when not in VR.
  106536. */
  106537. get: function () {
  106538. return this._deviceOrientationCamera;
  106539. },
  106540. enumerable: true,
  106541. configurable: true
  106542. });
  106543. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  106544. /**
  106545. * Based on the current WebVR support, returns the current VR camera used.
  106546. */
  106547. get: function () {
  106548. if (this._webVRready) {
  106549. return this._webVRCamera;
  106550. }
  106551. else {
  106552. return this._scene.activeCamera;
  106553. }
  106554. },
  106555. enumerable: true,
  106556. configurable: true
  106557. });
  106558. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  106559. /**
  106560. * The webVRCamera which is used when in VR.
  106561. */
  106562. get: function () {
  106563. return this._webVRCamera;
  106564. },
  106565. enumerable: true,
  106566. configurable: true
  106567. });
  106568. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  106569. /**
  106570. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  106571. */
  106572. get: function () {
  106573. return this._vrDeviceOrientationCamera;
  106574. },
  106575. enumerable: true,
  106576. configurable: true
  106577. });
  106578. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  106579. get: function () {
  106580. var result = this._cameraGazer._teleportationRequestInitiated
  106581. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  106582. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  106583. return result;
  106584. },
  106585. enumerable: true,
  106586. configurable: true
  106587. });
  106588. // Raised when one of the controller has loaded successfully its associated default mesh
  106589. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  106590. if (this._leftController && this._leftController.webVRController == webVRController) {
  106591. if (webVRController.mesh) {
  106592. this._leftController._setLaserPointerParent(webVRController.mesh);
  106593. }
  106594. }
  106595. if (this._rightController && this._rightController.webVRController == webVRController) {
  106596. if (webVRController.mesh) {
  106597. this._rightController._setLaserPointerParent(webVRController.mesh);
  106598. }
  106599. }
  106600. try {
  106601. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  106602. }
  106603. catch (err) {
  106604. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  106605. }
  106606. };
  106607. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  106608. /**
  106609. * Gets a value indicating if we are currently in VR mode.
  106610. */
  106611. get: function () {
  106612. return this._webVRpresenting || this._fullscreenVRpresenting;
  106613. },
  106614. enumerable: true,
  106615. configurable: true
  106616. });
  106617. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  106618. var vrDisplay = this._scene.getEngine().getVRDevice();
  106619. if (vrDisplay) {
  106620. var wasPresenting = this._webVRpresenting;
  106621. this._webVRpresenting = vrDisplay.isPresenting;
  106622. if (wasPresenting && !this._webVRpresenting) {
  106623. this.exitVR();
  106624. }
  106625. }
  106626. else {
  106627. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  106628. }
  106629. this.updateButtonVisibility();
  106630. };
  106631. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  106632. this._webVRsupported = eventArgs.vrSupported;
  106633. this._webVRready = !!eventArgs.vrDisplay;
  106634. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  106635. this.updateButtonVisibility();
  106636. };
  106637. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  106638. if (this._canvas && !this._useCustomVRButton) {
  106639. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  106640. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  106641. }
  106642. };
  106643. VRExperienceHelper.prototype.displayVRButton = function () {
  106644. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  106645. document.body.appendChild(this._btnVR);
  106646. this._btnVRDisplayed = true;
  106647. }
  106648. };
  106649. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  106650. if (!this._btnVR || this._useCustomVRButton) {
  106651. return;
  106652. }
  106653. this._btnVR.className = "babylonVRicon";
  106654. if (this.isInVRMode) {
  106655. this._btnVR.className += " vrdisplaypresenting";
  106656. }
  106657. else {
  106658. if (this._webVRready) {
  106659. this._btnVR.className += " vrdisplayready";
  106660. }
  106661. if (this._webVRsupported) {
  106662. this._btnVR.className += " vrdisplaysupported";
  106663. }
  106664. if (this._webVRrequesting) {
  106665. this._btnVR.className += " vrdisplayrequesting";
  106666. }
  106667. }
  106668. };
  106669. /**
  106670. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  106671. * Otherwise, will use the fullscreen API.
  106672. */
  106673. VRExperienceHelper.prototype.enterVR = function () {
  106674. if (this.onEnteringVRObservable) {
  106675. try {
  106676. this.onEnteringVRObservable.notifyObservers(this);
  106677. }
  106678. catch (err) {
  106679. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  106680. }
  106681. }
  106682. if (this._scene.activeCamera) {
  106683. this._position = this._scene.activeCamera.position.clone();
  106684. // make sure that we return to the last active camera
  106685. this._existingCamera = this._scene.activeCamera;
  106686. }
  106687. if (this._webVRrequesting) {
  106688. return;
  106689. }
  106690. // If WebVR is supported and a headset is connected
  106691. if (this._webVRready) {
  106692. if (!this._webVRpresenting) {
  106693. this._webVRCamera.position = this._position;
  106694. this._scene.activeCamera = this._webVRCamera;
  106695. }
  106696. }
  106697. else if (this._vrDeviceOrientationCamera) {
  106698. this._vrDeviceOrientationCamera.position = this._position;
  106699. if (this._scene.activeCamera) {
  106700. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106701. }
  106702. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  106703. this._scene.getEngine().switchFullscreen(true);
  106704. this.updateButtonVisibility();
  106705. }
  106706. if (this._scene.activeCamera && this._canvas) {
  106707. this._scene.activeCamera.attachControl(this._canvas);
  106708. }
  106709. if (this._interactionsEnabled) {
  106710. this._scene.registerBeforeRender(this.beforeRender);
  106711. }
  106712. this._hasEnteredVR = true;
  106713. };
  106714. /**
  106715. * Attempt to exit VR, or fullscreen.
  106716. */
  106717. VRExperienceHelper.prototype.exitVR = function () {
  106718. if (this._hasEnteredVR) {
  106719. if (this.onExitingVRObservable) {
  106720. try {
  106721. this.onExitingVRObservable.notifyObservers(this);
  106722. }
  106723. catch (err) {
  106724. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  106725. }
  106726. }
  106727. if (this._webVRpresenting) {
  106728. this._scene.getEngine().disableVR();
  106729. }
  106730. if (this._scene.activeCamera) {
  106731. this._position = this._scene.activeCamera.position.clone();
  106732. }
  106733. if (this._deviceOrientationCamera) {
  106734. this._deviceOrientationCamera.position = this._position;
  106735. this._scene.activeCamera = this._deviceOrientationCamera;
  106736. if (this._canvas) {
  106737. this._scene.activeCamera.attachControl(this._canvas);
  106738. }
  106739. }
  106740. else if (this._existingCamera) {
  106741. this._existingCamera.position = this._position;
  106742. this._scene.activeCamera = this._existingCamera;
  106743. }
  106744. this.updateButtonVisibility();
  106745. if (this._interactionsEnabled) {
  106746. this._scene.unregisterBeforeRender(this.beforeRender);
  106747. this._cameraGazer._gazeTracker.isVisible = false;
  106748. if (this._leftController) {
  106749. this._leftController._gazeTracker.isVisible = false;
  106750. }
  106751. if (this._rightController) {
  106752. this._rightController._gazeTracker.isVisible = false;
  106753. }
  106754. }
  106755. // resize to update width and height when exiting vr exits fullscreen
  106756. this._scene.getEngine().resize();
  106757. this._hasEnteredVR = false;
  106758. }
  106759. };
  106760. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  106761. /**
  106762. * The position of the vr experience helper.
  106763. */
  106764. get: function () {
  106765. return this._position;
  106766. },
  106767. /**
  106768. * Sets the position of the vr experience helper.
  106769. */
  106770. set: function (value) {
  106771. this._position = value;
  106772. if (this._scene.activeCamera) {
  106773. this._scene.activeCamera.position = value;
  106774. }
  106775. },
  106776. enumerable: true,
  106777. configurable: true
  106778. });
  106779. /**
  106780. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  106781. */
  106782. VRExperienceHelper.prototype.enableInteractions = function () {
  106783. var _this = this;
  106784. if (!this._interactionsEnabled) {
  106785. this._interactionsRequested = true;
  106786. if (this._leftController) {
  106787. this._enableInteractionOnController(this._leftController);
  106788. }
  106789. if (this._rightController) {
  106790. this._enableInteractionOnController(this._rightController);
  106791. }
  106792. this.raySelectionPredicate = function (mesh) {
  106793. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  106794. };
  106795. this.meshSelectionPredicate = function (mesh) {
  106796. return true;
  106797. };
  106798. this._raySelectionPredicate = function (mesh) {
  106799. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  106800. && mesh.name.indexOf("teleportationTarget") === -1
  106801. && mesh.name.indexOf("torusTeleportation") === -1)) {
  106802. return _this.raySelectionPredicate(mesh);
  106803. }
  106804. return false;
  106805. };
  106806. this._interactionsEnabled = true;
  106807. }
  106808. };
  106809. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  106810. get: function () {
  106811. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  106812. },
  106813. enumerable: true,
  106814. configurable: true
  106815. });
  106816. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  106817. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  106818. if (this._floorMeshesCollection[i].id === mesh.id) {
  106819. return true;
  106820. }
  106821. }
  106822. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  106823. return true;
  106824. }
  106825. return false;
  106826. };
  106827. /**
  106828. * Adds a floor mesh to be used for teleportation.
  106829. * @param floorMesh the mesh to be used for teleportation.
  106830. */
  106831. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  106832. if (!this._floorMeshesCollection) {
  106833. return;
  106834. }
  106835. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  106836. return;
  106837. }
  106838. this._floorMeshesCollection.push(floorMesh);
  106839. };
  106840. /**
  106841. * Removes a floor mesh from being used for teleportation.
  106842. * @param floorMesh the mesh to be removed.
  106843. */
  106844. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  106845. if (!this._floorMeshesCollection) {
  106846. return;
  106847. }
  106848. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  106849. if (meshIndex !== -1) {
  106850. this._floorMeshesCollection.splice(meshIndex, 1);
  106851. }
  106852. };
  106853. /**
  106854. * Enables interactions and teleportation using the VR controllers and gaze.
  106855. * @param vrTeleportationOptions options to modify teleportation behavior.
  106856. */
  106857. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  106858. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  106859. if (!this._teleportationInitialized) {
  106860. this._teleportationRequested = true;
  106861. this.enableInteractions();
  106862. if (vrTeleportationOptions.floorMeshName) {
  106863. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  106864. }
  106865. if (vrTeleportationOptions.floorMeshes) {
  106866. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  106867. }
  106868. if (this._leftController != null) {
  106869. this._enableTeleportationOnController(this._leftController);
  106870. }
  106871. if (this._rightController != null) {
  106872. this._enableTeleportationOnController(this._rightController);
  106873. }
  106874. // Creates an image processing post process for the vignette not relying
  106875. // on the main scene configuration for image processing to reduce setup and spaces
  106876. // (gamma/linear) conflicts.
  106877. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  106878. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  106879. imageProcessingConfiguration.vignetteEnabled = true;
  106880. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  106881. this._webVRCamera.detachPostProcess(this._postProcessMove);
  106882. this._teleportationInitialized = true;
  106883. if (this._isDefaultTeleportationTarget) {
  106884. this._createTeleportationCircles();
  106885. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  106886. }
  106887. }
  106888. };
  106889. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  106890. var _this = this;
  106891. var controllerMesh = controller.webVRController.mesh;
  106892. if (controllerMesh) {
  106893. controller._interactionsEnabled = true;
  106894. controller._activatePointer();
  106895. if (this.webVROptions.laserToggle) {
  106896. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  106897. // Enabling / disabling laserPointer
  106898. if (_this._displayLaserPointer && stateObject.value === 1) {
  106899. if (controller._activePointer) {
  106900. controller._deactivatePointer();
  106901. }
  106902. else {
  106903. controller._activatePointer();
  106904. }
  106905. if (_this.displayGaze) {
  106906. controller._gazeTracker.isVisible = controller._activePointer;
  106907. }
  106908. }
  106909. });
  106910. }
  106911. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  106912. var gazer = controller;
  106913. if (_this._noControllerIsActive) {
  106914. gazer = _this._cameraGazer;
  106915. }
  106916. if (!gazer._pointerDownOnMeshAsked) {
  106917. if (stateObject.value > _this._padSensibilityUp) {
  106918. gazer._selectionPointerDown();
  106919. }
  106920. }
  106921. else if (stateObject.value < _this._padSensibilityDown) {
  106922. gazer._selectionPointerUp();
  106923. }
  106924. });
  106925. }
  106926. };
  106927. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  106928. // Dont teleport if another gaze already requested teleportation
  106929. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  106930. return;
  106931. }
  106932. if (!gazer._teleportationRequestInitiated) {
  106933. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  106934. gazer._activatePointer();
  106935. gazer._teleportationRequestInitiated = true;
  106936. }
  106937. }
  106938. else {
  106939. // Listening to the proper controller values changes to confirm teleportation
  106940. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  106941. if (this._teleportActive) {
  106942. this.teleportCamera(this._haloCenter);
  106943. }
  106944. gazer._teleportationRequestInitiated = false;
  106945. }
  106946. }
  106947. };
  106948. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  106949. // Only rotate when user is not currently selecting a teleportation location
  106950. if (gazer._teleportationRequestInitiated) {
  106951. return;
  106952. }
  106953. if (!gazer._rotationLeftAsked) {
  106954. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  106955. gazer._rotationLeftAsked = true;
  106956. if (this._rotationAllowed) {
  106957. this._rotateCamera(false);
  106958. }
  106959. }
  106960. }
  106961. else {
  106962. if (stateObject.x > -this._padSensibilityDown) {
  106963. gazer._rotationLeftAsked = false;
  106964. }
  106965. }
  106966. if (!gazer._rotationRightAsked) {
  106967. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  106968. gazer._rotationRightAsked = true;
  106969. if (this._rotationAllowed) {
  106970. this._rotateCamera(true);
  106971. }
  106972. }
  106973. }
  106974. else {
  106975. if (stateObject.x < this._padSensibilityDown) {
  106976. gazer._rotationRightAsked = false;
  106977. }
  106978. }
  106979. };
  106980. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  106981. // Only teleport backwards when user is not currently selecting a teleportation location
  106982. if (gazer._teleportationRequestInitiated) {
  106983. return;
  106984. }
  106985. // Teleport backwards
  106986. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  106987. if (!gazer._teleportationBackRequestInitiated) {
  106988. if (!this.currentVRCamera) {
  106989. return;
  106990. }
  106991. // Get rotation and position of the current camera
  106992. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  106993. var position = this.currentVRCamera.position;
  106994. // If the camera has device position, use that instead
  106995. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  106996. rotation = this.currentVRCamera.deviceRotationQuaternion;
  106997. position = this.currentVRCamera.devicePosition;
  106998. }
  106999. // Get matrix with only the y rotation of the device rotation
  107000. rotation.toEulerAnglesToRef(this._workingVector);
  107001. this._workingVector.z = 0;
  107002. this._workingVector.x = 0;
  107003. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  107004. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  107005. // Rotate backwards ray by device rotation to cast at the ground behind the user
  107006. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  107007. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  107008. var ray = new BABYLON.Ray(position, this._workingVector);
  107009. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107010. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  107011. this.teleportCamera(hit.pickedPoint);
  107012. }
  107013. gazer._teleportationBackRequestInitiated = true;
  107014. }
  107015. }
  107016. else {
  107017. gazer._teleportationBackRequestInitiated = false;
  107018. }
  107019. };
  107020. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  107021. var _this = this;
  107022. var controllerMesh = controller.webVRController.mesh;
  107023. if (controllerMesh) {
  107024. if (!controller._interactionsEnabled) {
  107025. this._enableInteractionOnController(controller);
  107026. }
  107027. controller._interactionsEnabled = true;
  107028. controller._teleportationEnabled = true;
  107029. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  107030. controller._dpadPressed = false;
  107031. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  107032. controller._dpadPressed = stateObject.pressed;
  107033. if (!controller._dpadPressed) {
  107034. controller._rotationLeftAsked = false;
  107035. controller._rotationRightAsked = false;
  107036. controller._teleportationBackRequestInitiated = false;
  107037. }
  107038. });
  107039. }
  107040. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  107041. if (_this.teleportationEnabled) {
  107042. _this._checkTeleportBackwards(stateObject, controller);
  107043. _this._checkTeleportWithRay(stateObject, controller);
  107044. }
  107045. _this._checkRotate(stateObject, controller);
  107046. });
  107047. }
  107048. };
  107049. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  107050. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  107051. this._teleportationTarget.isPickable = false;
  107052. var length = 512;
  107053. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  107054. dynamicTexture.hasAlpha = true;
  107055. var context = dynamicTexture.getContext();
  107056. var centerX = length / 2;
  107057. var centerY = length / 2;
  107058. var radius = 200;
  107059. context.beginPath();
  107060. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  107061. context.fillStyle = this._teleportationFillColor;
  107062. context.fill();
  107063. context.lineWidth = 10;
  107064. context.strokeStyle = this._teleportationBorderColor;
  107065. context.stroke();
  107066. context.closePath();
  107067. dynamicTexture.update();
  107068. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  107069. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  107070. this._teleportationTarget.material = teleportationCircleMaterial;
  107071. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  107072. torus.isPickable = false;
  107073. torus.parent = this._teleportationTarget;
  107074. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107075. var keys = [];
  107076. keys.push({
  107077. frame: 0,
  107078. value: 0
  107079. });
  107080. keys.push({
  107081. frame: 30,
  107082. value: 0.4
  107083. });
  107084. keys.push({
  107085. frame: 60,
  107086. value: 0
  107087. });
  107088. animationInnerCircle.setKeys(keys);
  107089. var easingFunction = new BABYLON.SineEase();
  107090. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  107091. animationInnerCircle.setEasingFunction(easingFunction);
  107092. torus.animations = [];
  107093. torus.animations.push(animationInnerCircle);
  107094. this._scene.beginAnimation(torus, 0, 60, true);
  107095. this._hideTeleportationTarget();
  107096. };
  107097. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  107098. this._teleportActive = true;
  107099. if (this._teleportationInitialized) {
  107100. this._teleportationTarget.isVisible = true;
  107101. if (this._isDefaultTeleportationTarget) {
  107102. this._teleportationTarget.getChildren()[0].isVisible = true;
  107103. }
  107104. }
  107105. };
  107106. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  107107. this._teleportActive = false;
  107108. if (this._teleportationInitialized) {
  107109. this._teleportationTarget.isVisible = false;
  107110. if (this._isDefaultTeleportationTarget) {
  107111. this._teleportationTarget.getChildren()[0].isVisible = false;
  107112. }
  107113. }
  107114. };
  107115. VRExperienceHelper.prototype._rotateCamera = function (right) {
  107116. var _this = this;
  107117. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107118. return;
  107119. }
  107120. if (right) {
  107121. this._rotationAngle++;
  107122. }
  107123. else {
  107124. this._rotationAngle--;
  107125. }
  107126. this.currentVRCamera.animations = [];
  107127. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  107128. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107129. var animationRotationKeys = [];
  107130. animationRotationKeys.push({
  107131. frame: 0,
  107132. value: this.currentVRCamera.rotationQuaternion
  107133. });
  107134. animationRotationKeys.push({
  107135. frame: 6,
  107136. value: target
  107137. });
  107138. animationRotation.setKeys(animationRotationKeys);
  107139. animationRotation.setEasingFunction(this._circleEase);
  107140. this.currentVRCamera.animations.push(animationRotation);
  107141. this._postProcessMove.animations = [];
  107142. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107143. var vignetteWeightKeys = [];
  107144. vignetteWeightKeys.push({
  107145. frame: 0,
  107146. value: 0
  107147. });
  107148. vignetteWeightKeys.push({
  107149. frame: 3,
  107150. value: 4
  107151. });
  107152. vignetteWeightKeys.push({
  107153. frame: 6,
  107154. value: 0
  107155. });
  107156. animationPP.setKeys(vignetteWeightKeys);
  107157. animationPP.setEasingFunction(this._circleEase);
  107158. this._postProcessMove.animations.push(animationPP);
  107159. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107160. var vignetteStretchKeys = [];
  107161. vignetteStretchKeys.push({
  107162. frame: 0,
  107163. value: 0
  107164. });
  107165. vignetteStretchKeys.push({
  107166. frame: 3,
  107167. value: 10
  107168. });
  107169. vignetteStretchKeys.push({
  107170. frame: 6,
  107171. value: 0
  107172. });
  107173. animationPP2.setKeys(vignetteStretchKeys);
  107174. animationPP2.setEasingFunction(this._circleEase);
  107175. this._postProcessMove.animations.push(animationPP2);
  107176. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107177. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107178. this._postProcessMove.samples = 4;
  107179. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107180. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  107181. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107182. });
  107183. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  107184. };
  107185. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  107186. if (hit.pickedPoint) {
  107187. if (gazer._teleportationRequestInitiated) {
  107188. this._displayTeleportationTarget();
  107189. this._haloCenter.copyFrom(hit.pickedPoint);
  107190. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  107191. }
  107192. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  107193. if (pickNormal) {
  107194. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107195. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107196. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  107197. }
  107198. this._teleportationTarget.position.y += 0.1;
  107199. }
  107200. };
  107201. /**
  107202. * Teleports the users feet to the desired location
  107203. * @param location The location where the user's feet should be placed
  107204. */
  107205. VRExperienceHelper.prototype.teleportCamera = function (location) {
  107206. var _this = this;
  107207. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107208. return;
  107209. }
  107210. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  107211. // offset of the headset from the anchor.
  107212. if (this.webVRCamera.leftCamera) {
  107213. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  107214. this._workingVector.subtractInPlace(this.webVRCamera.position);
  107215. location.subtractToRef(this._workingVector, this._workingVector);
  107216. }
  107217. else {
  107218. this._workingVector.copyFrom(location);
  107219. }
  107220. // Add height to account for user's height offset
  107221. if (this.isInVRMode) {
  107222. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  107223. }
  107224. else {
  107225. this._workingVector.y += this._defaultHeight;
  107226. }
  107227. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  107228. // Create animation from the camera's position to the new location
  107229. this.currentVRCamera.animations = [];
  107230. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107231. var animationCameraTeleportationKeys = [{
  107232. frame: 0,
  107233. value: this.currentVRCamera.position
  107234. },
  107235. {
  107236. frame: 11,
  107237. value: this._workingVector
  107238. }
  107239. ];
  107240. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  107241. animationCameraTeleportation.setEasingFunction(this._circleEase);
  107242. this.currentVRCamera.animations.push(animationCameraTeleportation);
  107243. this._postProcessMove.animations = [];
  107244. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107245. var vignetteWeightKeys = [];
  107246. vignetteWeightKeys.push({
  107247. frame: 0,
  107248. value: 0
  107249. });
  107250. vignetteWeightKeys.push({
  107251. frame: 5,
  107252. value: 8
  107253. });
  107254. vignetteWeightKeys.push({
  107255. frame: 11,
  107256. value: 0
  107257. });
  107258. animationPP.setKeys(vignetteWeightKeys);
  107259. this._postProcessMove.animations.push(animationPP);
  107260. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107261. var vignetteStretchKeys = [];
  107262. vignetteStretchKeys.push({
  107263. frame: 0,
  107264. value: 0
  107265. });
  107266. vignetteStretchKeys.push({
  107267. frame: 5,
  107268. value: 10
  107269. });
  107270. vignetteStretchKeys.push({
  107271. frame: 11,
  107272. value: 0
  107273. });
  107274. animationPP2.setKeys(vignetteStretchKeys);
  107275. this._postProcessMove.animations.push(animationPP2);
  107276. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107277. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107278. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107279. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  107280. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107281. });
  107282. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  107283. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  107284. });
  107285. this._hideTeleportationTarget();
  107286. };
  107287. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  107288. if (normal) {
  107289. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  107290. if (angle < Math.PI / 2) {
  107291. normal.scaleInPlace(-1);
  107292. }
  107293. }
  107294. return normal;
  107295. };
  107296. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  107297. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107298. return;
  107299. }
  107300. var ray = gazer._getForwardRay(this._rayLength);
  107301. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107302. if (hit) {
  107303. // Populate the contrllers mesh that can be used for drag/drop
  107304. if (gazer._laserPointer) {
  107305. hit.originMesh = gazer._laserPointer.parent;
  107306. }
  107307. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  107308. }
  107309. gazer._currentHit = hit;
  107310. // Moving the gazeTracker on the mesh face targetted
  107311. if (hit && hit.pickedPoint) {
  107312. if (this._displayGaze) {
  107313. var multiplier = 1;
  107314. gazer._gazeTracker.isVisible = true;
  107315. if (gazer._isActionableMesh) {
  107316. multiplier = 3;
  107317. }
  107318. if (this.updateGazeTrackerScale) {
  107319. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  107320. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  107321. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  107322. }
  107323. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  107324. // To avoid z-fighting
  107325. var deltaFighting = 0.002;
  107326. if (pickNormal) {
  107327. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107328. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107329. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  107330. }
  107331. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  107332. if (gazer._gazeTracker.position.x < 0) {
  107333. gazer._gazeTracker.position.x += deltaFighting;
  107334. }
  107335. else {
  107336. gazer._gazeTracker.position.x -= deltaFighting;
  107337. }
  107338. if (gazer._gazeTracker.position.y < 0) {
  107339. gazer._gazeTracker.position.y += deltaFighting;
  107340. }
  107341. else {
  107342. gazer._gazeTracker.position.y -= deltaFighting;
  107343. }
  107344. if (gazer._gazeTracker.position.z < 0) {
  107345. gazer._gazeTracker.position.z += deltaFighting;
  107346. }
  107347. else {
  107348. gazer._gazeTracker.position.z -= deltaFighting;
  107349. }
  107350. }
  107351. // Changing the size of the laser pointer based on the distance from the targetted point
  107352. gazer._updatePointerDistance(hit.distance);
  107353. }
  107354. else {
  107355. gazer._updatePointerDistance();
  107356. gazer._gazeTracker.isVisible = false;
  107357. }
  107358. if (hit && hit.pickedMesh) {
  107359. // The object selected is the floor, we're in a teleportation scenario
  107360. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  107361. // Moving the teleportation area to this targetted point
  107362. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  107363. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  107364. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107365. }
  107366. gazer._currentMeshSelected = null;
  107367. if (gazer._teleportationRequestInitiated) {
  107368. this._moveTeleportationSelectorTo(hit, gazer, ray);
  107369. }
  107370. return;
  107371. }
  107372. // If not, we're in a selection scenario
  107373. //this._teleportationAllowed = false;
  107374. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  107375. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  107376. this.onNewMeshPicked.notifyObservers(hit);
  107377. gazer._currentMeshSelected = hit.pickedMesh;
  107378. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  107379. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  107380. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  107381. gazer._isActionableMesh = true;
  107382. }
  107383. else {
  107384. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107385. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107386. gazer._isActionableMesh = false;
  107387. }
  107388. try {
  107389. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  107390. }
  107391. catch (err) {
  107392. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  107393. }
  107394. }
  107395. else {
  107396. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107397. gazer._currentMeshSelected = null;
  107398. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107399. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107400. }
  107401. }
  107402. }
  107403. else {
  107404. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107405. gazer._currentMeshSelected = null;
  107406. //this._teleportationAllowed = false;
  107407. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107408. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107409. }
  107410. };
  107411. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  107412. if (mesh) {
  107413. this.onSelectedMeshUnselected.notifyObservers(mesh);
  107414. }
  107415. };
  107416. /**
  107417. * Sets the color of the laser ray from the vr controllers.
  107418. * @param color new color for the ray.
  107419. */
  107420. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  107421. if (this._leftController) {
  107422. this._leftController._setLaserPointerColor(color);
  107423. }
  107424. if (this._rightController) {
  107425. this._rightController._setLaserPointerColor(color);
  107426. }
  107427. };
  107428. /**
  107429. * Sets the color of the ray from the vr headsets gaze.
  107430. * @param color new color for the ray.
  107431. */
  107432. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  107433. if (!this._cameraGazer._gazeTracker.material) {
  107434. return;
  107435. }
  107436. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  107437. if (this._leftController) {
  107438. this._leftController._gazeTracker.material.emissiveColor = color;
  107439. }
  107440. if (this._rightController) {
  107441. this._rightController._gazeTracker.material.emissiveColor = color;
  107442. }
  107443. };
  107444. /**
  107445. * Exits VR and disposes of the vr experience helper
  107446. */
  107447. VRExperienceHelper.prototype.dispose = function () {
  107448. if (this.isInVRMode) {
  107449. this.exitVR();
  107450. }
  107451. if (this._postProcessMove) {
  107452. this._postProcessMove.dispose();
  107453. }
  107454. if (this._webVRCamera) {
  107455. this._webVRCamera.dispose();
  107456. }
  107457. if (this._vrDeviceOrientationCamera) {
  107458. this._vrDeviceOrientationCamera.dispose();
  107459. }
  107460. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  107461. document.body.removeChild(this._btnVR);
  107462. }
  107463. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  107464. this._deviceOrientationCamera.dispose();
  107465. }
  107466. if (this._cameraGazer) {
  107467. this._cameraGazer.dispose();
  107468. }
  107469. if (this._leftController) {
  107470. this._leftController.dispose();
  107471. }
  107472. if (this._rightController) {
  107473. this._rightController.dispose();
  107474. }
  107475. if (this._teleportationTarget) {
  107476. this._teleportationTarget.dispose();
  107477. }
  107478. this._floorMeshesCollection = [];
  107479. document.removeEventListener("keydown", this._onKeyDown);
  107480. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107481. window.removeEventListener("resize", this._onResize);
  107482. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  107483. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  107484. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  107485. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  107486. document.onmsfullscreenchange = null;
  107487. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  107488. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  107489. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  107490. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107491. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  107492. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  107493. this._scene.unregisterBeforeRender(this.beforeRender);
  107494. };
  107495. /**
  107496. * Gets the name of the VRExperienceHelper class
  107497. * @returns "VRExperienceHelper"
  107498. */
  107499. VRExperienceHelper.prototype.getClassName = function () {
  107500. return "VRExperienceHelper";
  107501. };
  107502. return VRExperienceHelper;
  107503. }());
  107504. BABYLON.VRExperienceHelper = VRExperienceHelper;
  107505. })(BABYLON || (BABYLON = {}));
  107506. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  107507. var BABYLON;
  107508. (function (BABYLON) {
  107509. /**
  107510. * WebXR Camera which holds the views for the xrSession
  107511. * @see https://doc.babylonjs.com/how_to/webxr
  107512. */
  107513. var WebXRCamera = /** @class */ (function (_super) {
  107514. __extends(WebXRCamera, _super);
  107515. /**
  107516. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  107517. * @param name the name of the camera
  107518. * @param scene the scene to add the camera to
  107519. */
  107520. function WebXRCamera(name, scene) {
  107521. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  107522. // Initial camera configuration
  107523. _this.minZ = 0;
  107524. _this.rotationQuaternion = new BABYLON.Quaternion();
  107525. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  107526. _this._updateNumberOfRigCameras(1);
  107527. return _this;
  107528. }
  107529. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  107530. if (viewCount === void 0) { viewCount = 1; }
  107531. while (this.rigCameras.length < viewCount) {
  107532. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  107533. newCamera.minZ = 0;
  107534. newCamera.parent = this;
  107535. this.rigCameras.push(newCamera);
  107536. }
  107537. while (this.rigCameras.length > viewCount) {
  107538. var removedCamera = this.rigCameras.pop();
  107539. if (removedCamera) {
  107540. removedCamera.dispose();
  107541. }
  107542. }
  107543. };
  107544. /** @hidden */
  107545. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  107546. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  107547. // Create initial camera rigs
  107548. this._updateNumberOfRigCameras(2);
  107549. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  107550. this.rigCameras[0].position.x = -pupilDistance / 2;
  107551. this.rigCameras[0].outputRenderTarget = null;
  107552. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  107553. this.rigCameras[1].position.x = pupilDistance / 2;
  107554. this.rigCameras[1].outputRenderTarget = null;
  107555. };
  107556. /**
  107557. * Updates the cameras position from the current pose information of the XR session
  107558. * @param xrSessionManager the session containing pose information
  107559. * @returns true if the camera has been updated, false if the session did not contain pose or frame data
  107560. */
  107561. WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) {
  107562. var _this = this;
  107563. // Ensure all frame data is available
  107564. if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) {
  107565. return false;
  107566. }
  107567. var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference);
  107568. if (!pose || !pose.poseModelMatrix) {
  107569. return false;
  107570. }
  107571. // Update the parent cameras matrix
  107572. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix);
  107573. if (!this._scene.useRightHandedSystem) {
  107574. WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace();
  107575. }
  107576. WebXRCamera._TmpMatrix.getTranslationToRef(this.position);
  107577. WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix);
  107578. BABYLON.Quaternion.FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion);
  107579. this.computeWorldMatrix();
  107580. // Update camera rigs
  107581. this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length);
  107582. xrSessionManager._currentXRFrame.views.forEach(function (view, i) {
  107583. // Update view/projection matrix
  107584. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix);
  107585. BABYLON.Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix);
  107586. if (!_this._scene.useRightHandedSystem) {
  107587. _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace();
  107588. _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace();
  107589. }
  107590. // Update viewport
  107591. var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view);
  107592. var width = xrSessionManager._xrSession.baseLayer.framebufferWidth;
  107593. var height = xrSessionManager._xrSession.baseLayer.framebufferHeight;
  107594. _this.rigCameras[i].viewport.width = viewport.width / width;
  107595. _this.rigCameras[i].viewport.height = viewport.height / height;
  107596. _this.rigCameras[i].viewport.x = viewport.x / width;
  107597. _this.rigCameras[i].viewport.y = viewport.y / height;
  107598. // Set cameras to render to the session's render target
  107599. _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture;
  107600. });
  107601. return true;
  107602. };
  107603. WebXRCamera._TmpMatrix = new BABYLON.Matrix();
  107604. return WebXRCamera;
  107605. }(BABYLON.FreeCamera));
  107606. BABYLON.WebXRCamera = WebXRCamera;
  107607. })(BABYLON || (BABYLON = {}));
  107608. //# sourceMappingURL=babylon.webXRCamera.js.map
  107609. var BABYLON;
  107610. (function (BABYLON) {
  107611. /**
  107612. * Manages an XRSession
  107613. * @see https://doc.babylonjs.com/how_to/webxr
  107614. */
  107615. var WebXRSessionManager = /** @class */ (function () {
  107616. /**
  107617. * Constructs a WebXRSessionManager, this must be initialized within a user action before usage
  107618. * @param scene The scene which the session should be created for
  107619. */
  107620. function WebXRSessionManager(scene) {
  107621. this.scene = scene;
  107622. /**
  107623. * Fires every time a new xrFrame arrives which can be used to update the camera
  107624. */
  107625. this.onXRFrameObservable = new BABYLON.Observable();
  107626. /**
  107627. * Fires when the xr session is ended either by the device or manually done
  107628. */
  107629. this.onXRSessionEnded = new BABYLON.Observable();
  107630. /** @hidden */
  107631. this._sessionRenderTargetTexture = null;
  107632. this._tmpMatrix = new BABYLON.Matrix();
  107633. }
  107634. /**
  107635. * Initializes the manager
  107636. * After initialization enterXR can be called to start an XR session
  107637. * @returns Promise which resolves after it is initialized
  107638. */
  107639. WebXRSessionManager.prototype.initializeAsync = function () {
  107640. var _this = this;
  107641. // Check if the browser supports webXR
  107642. this._xrNavigator = navigator;
  107643. if (!this._xrNavigator.xr) {
  107644. return Promise.reject("webXR not supported by this browser");
  107645. }
  107646. // Request the webXR device
  107647. return this._xrNavigator.xr.requestDevice().then(function (device) {
  107648. _this._xrDevice = device;
  107649. return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice);
  107650. });
  107651. };
  107652. /**
  107653. * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event)
  107654. * @param sessionCreationOptions xr options to create the session with
  107655. * @param frameOfReferenceType option to configure how the xr pose is expressed
  107656. * @returns Promise which resolves after it enters XR
  107657. */
  107658. WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) {
  107659. var _this = this;
  107660. // initialize session
  107661. return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) {
  107662. _this._xrSession = session;
  107663. // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)
  107664. _this._xrSession.addEventListener("end", function () {
  107665. // Remove render target texture and notify frame obervers
  107666. _this._sessionRenderTargetTexture = null;
  107667. // Restore frame buffer to avoid clear on xr framebuffer after session end
  107668. _this.scene.getEngine().restoreDefaultFramebuffer();
  107669. // Need to restart render loop as after the session is ended the last request for new frame will never call callback
  107670. _this.scene.getEngine().customAnimationFrameRequester = null;
  107671. _this.onXRSessionEnded.notifyObservers(null);
  107672. _this.scene.getEngine()._renderLoop();
  107673. }, { once: true });
  107674. _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl);
  107675. return _this._xrSession.requestFrameOfReference(frameOfReferenceType);
  107676. }).then(function (frameOfRef) {
  107677. _this._frameOfReference = frameOfRef;
  107678. // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information
  107679. _this.scene.getEngine().customAnimationFrameRequester = {
  107680. requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession),
  107681. renderFunction: function (timestamp, xrFrame) {
  107682. // Store the XR frame in the manager to be consumed by the XR camera to update pose
  107683. _this._currentXRFrame = xrFrame;
  107684. _this.onXRFrameObservable.notifyObservers(null);
  107685. _this.scene.getEngine()._renderLoop();
  107686. }
  107687. };
  107688. // Create render target texture from xr's webgl render target
  107689. _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene);
  107690. // Stop window's animation frame and trigger sessions animation frame
  107691. window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler);
  107692. _this.scene.getEngine()._renderLoop();
  107693. });
  107694. };
  107695. /**
  107696. * Stops the xrSession and restores the renderloop
  107697. * @returns Promise which resolves after it exits XR
  107698. */
  107699. WebXRSessionManager.prototype.exitXRAsync = function () {
  107700. return this._xrSession.end();
  107701. };
  107702. /**
  107703. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  107704. * @param ray ray to cast into the environment
  107705. * @returns Promise which resolves with a collision point in the environment if it exists
  107706. */
  107707. WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) {
  107708. var _this = this;
  107709. return new Promise(function (res, rej) {
  107710. // Compute left handed inputs to request hit test
  107711. var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]);
  107712. var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]);
  107713. if (!_this.scene.useRightHandedSystem) {
  107714. origin[2] *= -1;
  107715. direction[2] *= -1;
  107716. }
  107717. // Fire hittest
  107718. _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference)
  107719. .then(function (hits) {
  107720. if (hits.length > 0) {
  107721. BABYLON.Matrix.FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix);
  107722. var hitPoint = _this._tmpMatrix.getTranslation();
  107723. if (!_this.scene.useRightHandedSystem) {
  107724. hitPoint.z *= -1;
  107725. }
  107726. res(hitPoint);
  107727. }
  107728. else {
  107729. res(null);
  107730. }
  107731. }).catch(function (e) {
  107732. res(null);
  107733. });
  107734. });
  107735. };
  107736. /**
  107737. * Checks if a session would be supported for the creation options specified
  107738. * @param options creation options to check if they are supported
  107739. * @returns true if supported
  107740. */
  107741. WebXRSessionManager.prototype.supportsSessionAsync = function (options) {
  107742. return this._xrDevice.supportsSession(options).then(function () {
  107743. return true;
  107744. }).catch(function (e) {
  107745. return false;
  107746. });
  107747. };
  107748. /**
  107749. * @hidden
  107750. * Converts the render layer of xrSession to a render target
  107751. * @param session session to create render target for
  107752. * @param scene scene the new render target should be created for
  107753. */
  107754. WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) {
  107755. // Create internal texture
  107756. var internalTexture = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_UNKNOWN, true);
  107757. internalTexture.width = session.baseLayer.framebufferWidth;
  107758. internalTexture.height = session.baseLayer.framebufferHeight;
  107759. internalTexture._framebuffer = session.baseLayer.framebuffer;
  107760. // Create render target texture from the internal texture
  107761. var renderTargetTexture = new BABYLON.RenderTargetTexture("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
  107762. renderTargetTexture._texture = internalTexture;
  107763. return renderTargetTexture;
  107764. };
  107765. /**
  107766. * Disposes of the session manager
  107767. */
  107768. WebXRSessionManager.prototype.dispose = function () {
  107769. this.onXRFrameObservable.clear();
  107770. this.onXRSessionEnded.clear();
  107771. };
  107772. return WebXRSessionManager;
  107773. }());
  107774. BABYLON.WebXRSessionManager = WebXRSessionManager;
  107775. })(BABYLON || (BABYLON = {}));
  107776. //# sourceMappingURL=babylon.webXRSessionManager.js.map
  107777. var BABYLON;
  107778. (function (BABYLON) {
  107779. /**
  107780. * States of the webXR experience
  107781. */
  107782. var WebXRState;
  107783. (function (WebXRState) {
  107784. /**
  107785. * Transitioning to being in XR mode
  107786. */
  107787. WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR";
  107788. /**
  107789. * Transitioning to non XR mode
  107790. */
  107791. WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR";
  107792. /**
  107793. * In XR mode and presenting
  107794. */
  107795. WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR";
  107796. /**
  107797. * Not entered XR mode
  107798. */
  107799. WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR";
  107800. })(WebXRState = BABYLON.WebXRState || (BABYLON.WebXRState = {}));
  107801. /**
  107802. * Helper class used to enable XR
  107803. * @see https://doc.babylonjs.com/how_to/webxr
  107804. */
  107805. var WebXRExperienceHelper = /** @class */ (function () {
  107806. /**
  107807. * Creates a WebXRExperienceHelper
  107808. * @param scene The scene the helper should be created in
  107809. */
  107810. function WebXRExperienceHelper(scene) {
  107811. this.scene = scene;
  107812. /**
  107813. * The current state of the XR experience (eg. transitioning, in XR or not in XR)
  107814. */
  107815. this.state = WebXRState.NOT_IN_XR;
  107816. /**
  107817. * Fires when the state of the experience helper has changed
  107818. */
  107819. this.onStateChangedObservable = new BABYLON.Observable();
  107820. this._nonVRCamera = null;
  107821. this._originalSceneAutoClear = true;
  107822. this._supported = false;
  107823. this.camera = new BABYLON.WebXRCamera("", scene);
  107824. this._sessionManager = new BABYLON.WebXRSessionManager(scene);
  107825. this.container = new BABYLON.AbstractMesh("", scene);
  107826. }
  107827. WebXRExperienceHelper.prototype._setState = function (val) {
  107828. this.state = val;
  107829. this.onStateChangedObservable.notifyObservers(this.state);
  107830. };
  107831. /**
  107832. * Creates the experience helper
  107833. * @param scene the scene to attach the experience helper to
  107834. * @returns a promise for the experience helper
  107835. */
  107836. WebXRExperienceHelper.CreateAsync = function (scene) {
  107837. var helper = new WebXRExperienceHelper(scene);
  107838. return helper._sessionManager.initializeAsync().then(function () {
  107839. helper._supported = true;
  107840. return helper;
  107841. }).catch(function () {
  107842. return helper;
  107843. });
  107844. };
  107845. /**
  107846. * Exits XR mode and returns the scene to its original state
  107847. * @returns promise that resolves after xr mode has exited
  107848. */
  107849. WebXRExperienceHelper.prototype.exitXRAsync = function () {
  107850. this._setState(WebXRState.EXITING_XR);
  107851. return this._sessionManager.exitXRAsync();
  107852. };
  107853. /**
  107854. * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)
  107855. * @param sessionCreationOptions options for the XR session
  107856. * @param frameOfReference frame of reference of the XR session
  107857. * @returns promise that resolves after xr mode has entered
  107858. */
  107859. WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) {
  107860. var _this = this;
  107861. this._setState(WebXRState.ENTERING_XR);
  107862. return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () {
  107863. // Cache pre xr scene settings
  107864. _this._originalSceneAutoClear = _this.scene.autoClear;
  107865. _this._nonVRCamera = _this.scene.activeCamera;
  107866. // Overwrite current scene settings
  107867. _this.scene.autoClear = false;
  107868. _this.scene.activeCamera = _this.camera;
  107869. _this._sessionManager.onXRFrameObservable.add(function () {
  107870. _this.camera.updateFromXRSessionManager(_this._sessionManager);
  107871. });
  107872. _this._sessionManager.onXRSessionEnded.addOnce(function () {
  107873. // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends
  107874. _this.camera.rigCameras.forEach(function (c) {
  107875. c.outputRenderTarget = null;
  107876. });
  107877. // Restore scene settings
  107878. _this.scene.autoClear = _this._originalSceneAutoClear;
  107879. _this.scene.activeCamera = _this._nonVRCamera;
  107880. _this._sessionManager.onXRFrameObservable.clear();
  107881. _this._setState(WebXRState.NOT_IN_XR);
  107882. });
  107883. _this._setState(WebXRState.IN_XR);
  107884. });
  107885. };
  107886. /**
  107887. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  107888. * @param ray ray to cast into the environment
  107889. * @returns Promise which resolves with a collision point in the environment if it exists
  107890. */
  107891. WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) {
  107892. return this._sessionManager.environmentPointHitTestAsync(ray);
  107893. };
  107894. /**
  107895. * Checks if the creation options are supported by the xr session
  107896. * @param options creation options
  107897. * @returns true if supported
  107898. */
  107899. WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) {
  107900. if (!this._supported) {
  107901. return Promise.resolve(false);
  107902. }
  107903. return this._sessionManager.supportsSessionAsync(options);
  107904. };
  107905. /**
  107906. * Disposes of the experience helper
  107907. */
  107908. WebXRExperienceHelper.prototype.dispose = function () {
  107909. this.camera.dispose();
  107910. this.container.dispose();
  107911. this.onStateChangedObservable.clear();
  107912. this._sessionManager.dispose();
  107913. };
  107914. return WebXRExperienceHelper;
  107915. }());
  107916. BABYLON.WebXRExperienceHelper = WebXRExperienceHelper;
  107917. })(BABYLON || (BABYLON = {}));
  107918. //# sourceMappingURL=babylon.webXRExperienceHelper.js.map
  107919. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  107920. return new (P || (P = Promise))(function (resolve, reject) {
  107921. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  107922. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  107923. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  107924. step((generator = generator.apply(thisArg, _arguments || [])).next());
  107925. });
  107926. };
  107927. var __generator = (this && this.__generator) || function (thisArg, body) {
  107928. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  107929. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  107930. function verb(n) { return function (v) { return step([n, v]); }; }
  107931. function step(op) {
  107932. if (f) throw new TypeError("Generator is already executing.");
  107933. while (_) try {
  107934. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  107935. if (y = 0, t) op = [op[0] & 2, t.value];
  107936. switch (op[0]) {
  107937. case 0: case 1: t = op; break;
  107938. case 4: _.label++; return { value: op[1], done: false };
  107939. case 5: _.label++; y = op[1]; op = [0]; continue;
  107940. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  107941. default:
  107942. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  107943. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  107944. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  107945. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  107946. if (t[2]) _.ops.pop();
  107947. _.trys.pop(); continue;
  107948. }
  107949. op = body.call(thisArg, _);
  107950. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  107951. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  107952. }
  107953. };
  107954. var BABYLON;
  107955. (function (BABYLON) {
  107956. /**
  107957. * Button which can be used to enter a different mode of XR
  107958. */
  107959. var WebXREnterExitUIButton = /** @class */ (function () {
  107960. /**
  107961. * Creates a WebXREnterExitUIButton
  107962. * @param element button element
  107963. * @param initializationOptions XR initialization options for the button
  107964. */
  107965. function WebXREnterExitUIButton(
  107966. /** button element */
  107967. element,
  107968. /** XR initialization options for the button */
  107969. initializationOptions) {
  107970. this.element = element;
  107971. this.initializationOptions = initializationOptions;
  107972. }
  107973. /**
  107974. * Overwritable function which can be used to update the button's visuals when the state changes
  107975. * @param activeButton the current active button in the UI
  107976. */
  107977. WebXREnterExitUIButton.prototype.update = function (activeButton) {
  107978. };
  107979. return WebXREnterExitUIButton;
  107980. }());
  107981. BABYLON.WebXREnterExitUIButton = WebXREnterExitUIButton;
  107982. /**
  107983. * Options to create the webXR UI
  107984. */
  107985. var WebXREnterExitUIOptions = /** @class */ (function () {
  107986. function WebXREnterExitUIOptions() {
  107987. }
  107988. return WebXREnterExitUIOptions;
  107989. }());
  107990. BABYLON.WebXREnterExitUIOptions = WebXREnterExitUIOptions;
  107991. /**
  107992. * UI to allow the user to enter/exit XR mode
  107993. */
  107994. var WebXREnterExitUI = /** @class */ (function () {
  107995. function WebXREnterExitUI(scene, options) {
  107996. var _this = this;
  107997. this.scene = scene;
  107998. this._buttons = [];
  107999. this._activeButton = null;
  108000. this._overlay = document.createElement("div");
  108001. this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;";
  108002. if (options.customButtons) {
  108003. this._buttons = options.customButtons;
  108004. }
  108005. else {
  108006. var hmdBtn = document.createElement("button");
  108007. hmdBtn.style.cssText = "color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;";
  108008. hmdBtn.innerText = "HMD";
  108009. this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext }));
  108010. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  108011. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  108012. this.element.innerText = activeButton === this ? "EXIT" : "HMD";
  108013. };
  108014. var windowBtn = document.createElement("button");
  108015. windowBtn.style.cssText = hmdBtn.style.cssText;
  108016. windowBtn.innerText = "Window";
  108017. this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext }));
  108018. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  108019. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  108020. this.element.innerText = activeButton === this ? "EXIT" : "Window";
  108021. };
  108022. this._updateButtons(null);
  108023. }
  108024. var renderCanvas = scene.getEngine().getRenderingCanvas();
  108025. if (renderCanvas && renderCanvas.parentNode) {
  108026. renderCanvas.parentNode.appendChild(this._overlay);
  108027. scene.onDisposeObservable.addOnce(function () {
  108028. _this.dispose();
  108029. });
  108030. }
  108031. }
  108032. /**
  108033. * Creates UI to allow the user to enter/exit XR mode
  108034. * @param scene the scene to add the ui to
  108035. * @param helper the xr experience helper to enter/exit xr with
  108036. * @param options options to configure the UI
  108037. * @returns the created ui
  108038. */
  108039. WebXREnterExitUI.CreateAsync = function (scene, helper, options) {
  108040. var _this = this;
  108041. var ui = new WebXREnterExitUI(scene, options);
  108042. var supportedPromises = ui._buttons.map(function (btn) {
  108043. return helper.supportsSessionAsync(btn.initializationOptions);
  108044. });
  108045. helper.onStateChangedObservable.add(function (state) {
  108046. if (state == BABYLON.WebXRState.NOT_IN_XR) {
  108047. ui._updateButtons(null);
  108048. }
  108049. });
  108050. return Promise.all(supportedPromises).then(function (results) {
  108051. results.forEach(function (supported, i) {
  108052. if (supported) {
  108053. ui._overlay.appendChild(ui._buttons[i].element);
  108054. ui._buttons[i].element.onclick = function () { return __awaiter(_this, void 0, void 0, function () {
  108055. return __generator(this, function (_a) {
  108056. switch (_a.label) {
  108057. case 0:
  108058. if (!(helper.state == BABYLON.WebXRState.IN_XR)) return [3 /*break*/, 2];
  108059. ui._updateButtons(null);
  108060. return [4 /*yield*/, helper.exitXRAsync()];
  108061. case 1:
  108062. _a.sent();
  108063. return [2 /*return*/];
  108064. case 2:
  108065. if (!(helper.state == BABYLON.WebXRState.NOT_IN_XR)) return [3 /*break*/, 4];
  108066. ui._updateButtons(ui._buttons[i]);
  108067. return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")];
  108068. case 3:
  108069. _a.sent();
  108070. _a.label = 4;
  108071. case 4: return [2 /*return*/];
  108072. }
  108073. });
  108074. }); };
  108075. }
  108076. });
  108077. });
  108078. };
  108079. WebXREnterExitUI.prototype._updateButtons = function (activeButton) {
  108080. var _this = this;
  108081. this._activeButton = activeButton;
  108082. this._buttons.forEach(function (b) {
  108083. b.update(_this._activeButton);
  108084. });
  108085. };
  108086. /**
  108087. * Disposes of the object
  108088. */
  108089. WebXREnterExitUI.prototype.dispose = function () {
  108090. var renderCanvas = this.scene.getEngine().getRenderingCanvas();
  108091. if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) {
  108092. renderCanvas.parentNode.removeChild(this._overlay);
  108093. }
  108094. };
  108095. return WebXREnterExitUI;
  108096. }());
  108097. BABYLON.WebXREnterExitUI = WebXREnterExitUI;
  108098. })(BABYLON || (BABYLON = {}));
  108099. //# sourceMappingURL=babylon.webXREnterExitUI.js.map
  108100. var BABYLON;
  108101. (function (BABYLON) {
  108102. /**
  108103. * Creates a canvas that is added/removed from the webpage when entering/exiting XR
  108104. */
  108105. var WebXRManagedOutputCanvas = /** @class */ (function () {
  108106. /**
  108107. * Initializes the canvas to be added/removed upon entering/exiting xr
  108108. * @param helper the xr experience helper used to trigger adding/removing of the canvas
  108109. * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created)
  108110. */
  108111. function WebXRManagedOutputCanvas(helper, canvas) {
  108112. var _this = this;
  108113. this._canvas = null;
  108114. /**
  108115. * xrpresent context of the canvas which can be used to display/mirror xr content
  108116. */
  108117. this.canvasContext = null;
  108118. if (!canvas) {
  108119. canvas = document.createElement('canvas');
  108120. canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;";
  108121. }
  108122. this._setManagedOutputCanvas(canvas);
  108123. helper.onStateChangedObservable.add(function (stateInfo) {
  108124. if (stateInfo == BABYLON.WebXRState.ENTERING_XR) {
  108125. // The canvas is added to the screen before entering XR because currently the xr session must be initialized while the canvas is added render properly
  108126. _this._addCanvas();
  108127. }
  108128. else if (helper.state == BABYLON.WebXRState.NOT_IN_XR) {
  108129. _this._removeCanvas();
  108130. }
  108131. });
  108132. }
  108133. /**
  108134. * Disposes of the object
  108135. */
  108136. WebXRManagedOutputCanvas.prototype.dispose = function () {
  108137. this._removeCanvas();
  108138. this._setManagedOutputCanvas(null);
  108139. };
  108140. WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) {
  108141. this._removeCanvas();
  108142. if (!canvas) {
  108143. this._canvas = null;
  108144. this.canvasContext = null;
  108145. }
  108146. else {
  108147. this._canvas = canvas;
  108148. this.canvasContext = this._canvas.getContext('xrpresent');
  108149. }
  108150. };
  108151. WebXRManagedOutputCanvas.prototype._addCanvas = function () {
  108152. if (this._canvas) {
  108153. document.body.appendChild(this._canvas);
  108154. }
  108155. };
  108156. WebXRManagedOutputCanvas.prototype._removeCanvas = function () {
  108157. if (this._canvas && document.body.contains(this._canvas)) {
  108158. document.body.removeChild(this._canvas);
  108159. }
  108160. };
  108161. return WebXRManagedOutputCanvas;
  108162. }());
  108163. BABYLON.WebXRManagedOutputCanvas = WebXRManagedOutputCanvas;
  108164. })(BABYLON || (BABYLON = {}));
  108165. //# sourceMappingURL=babylon.webXRManagedOutputCanvas.js.map
  108166. var BABYLON;
  108167. (function (BABYLON) {
  108168. /**
  108169. * Represents an XR input
  108170. */
  108171. var WebXRController = /** @class */ (function () {
  108172. /**
  108173. * Creates the controller
  108174. * @see https://doc.babylonjs.com/how_to/webxr
  108175. * @param scene the scene which the controller should be associated to
  108176. */
  108177. function WebXRController(scene) {
  108178. this.pointer = new BABYLON.AbstractMesh("controllerPointer", scene);
  108179. }
  108180. /**
  108181. * Disposes of the object
  108182. */
  108183. WebXRController.prototype.dispose = function () {
  108184. if (this.grip) {
  108185. this.grip.dispose();
  108186. }
  108187. this.pointer.dispose();
  108188. };
  108189. return WebXRController;
  108190. }());
  108191. BABYLON.WebXRController = WebXRController;
  108192. /**
  108193. * XR input used to track XR inputs such as controllers/rays
  108194. */
  108195. var WebXRInput = /** @class */ (function () {
  108196. /**
  108197. * Initializes the WebXRInput
  108198. * @param helper experience helper which the input should be created for
  108199. */
  108200. function WebXRInput(helper) {
  108201. var _this = this;
  108202. this.helper = helper;
  108203. /**
  108204. * XR controllers being tracked
  108205. */
  108206. this.controllers = [];
  108207. this._tmpMatrix = new BABYLON.Matrix();
  108208. this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () {
  108209. if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) {
  108210. return;
  108211. }
  108212. var xrFrame = helper._sessionManager._currentXRFrame;
  108213. var inputSources = helper._sessionManager._xrSession.getInputSources();
  108214. inputSources.forEach(function (input, i) {
  108215. var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference);
  108216. if (inputPose) {
  108217. if (_this.controllers.length <= i) {
  108218. _this.controllers.push(new WebXRController(helper.container.getScene()));
  108219. }
  108220. var controller = _this.controllers[i];
  108221. // Manage the grip if it exists
  108222. if (inputPose.gripMatrix) {
  108223. if (!controller.grip) {
  108224. controller.grip = new BABYLON.AbstractMesh("controllerGrip", helper.container.getScene());
  108225. }
  108226. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix);
  108227. if (!controller.grip.getScene().useRightHandedSystem) {
  108228. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108229. }
  108230. if (!controller.grip.rotationQuaternion) {
  108231. controller.grip.rotationQuaternion = new BABYLON.Quaternion();
  108232. }
  108233. _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position);
  108234. }
  108235. // Manager pointer of controller
  108236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix);
  108237. if (!controller.pointer.getScene().useRightHandedSystem) {
  108238. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108239. }
  108240. if (!controller.pointer.rotationQuaternion) {
  108241. controller.pointer.rotationQuaternion = new BABYLON.Quaternion();
  108242. }
  108243. _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position);
  108244. }
  108245. });
  108246. });
  108247. }
  108248. /**
  108249. * Disposes of the object
  108250. */
  108251. WebXRInput.prototype.dispose = function () {
  108252. this.controllers.forEach(function (c) {
  108253. c.dispose();
  108254. });
  108255. this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver);
  108256. };
  108257. return WebXRInput;
  108258. }());
  108259. BABYLON.WebXRInput = WebXRInput;
  108260. })(BABYLON || (BABYLON = {}));
  108261. //# sourceMappingURL=babylon.webXRInput.js.map
  108262. // Mainly based on these 2 articles :
  108263. // 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
  108264. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  108265. var BABYLON;
  108266. (function (BABYLON) {
  108267. /**
  108268. * Defines the potential axis of a Joystick
  108269. */
  108270. var JoystickAxis;
  108271. (function (JoystickAxis) {
  108272. /** X axis */
  108273. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  108274. /** Y axis */
  108275. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  108276. /** Z axis */
  108277. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  108278. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  108279. /**
  108280. * Class used to define virtual joystick (used in touch mode)
  108281. */
  108282. var VirtualJoystick = /** @class */ (function () {
  108283. /**
  108284. * Creates a new virtual joystick
  108285. * @param leftJoystick defines that the joystick is for left hand (false by default)
  108286. */
  108287. function VirtualJoystick(leftJoystick) {
  108288. var _this = this;
  108289. if (leftJoystick) {
  108290. this._leftJoystick = true;
  108291. }
  108292. else {
  108293. this._leftJoystick = false;
  108294. }
  108295. VirtualJoystick._globalJoystickIndex++;
  108296. // By default left & right arrow keys are moving the X
  108297. // and up & down keys are moving the Y
  108298. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108299. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108300. this.reverseLeftRight = false;
  108301. this.reverseUpDown = false;
  108302. // collections of pointers
  108303. this._touches = new BABYLON.StringDictionary();
  108304. this.deltaPosition = BABYLON.Vector3.Zero();
  108305. this._joystickSensibility = 25;
  108306. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108307. this._onResize = function (evt) {
  108308. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108309. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108310. if (VirtualJoystick.vjCanvas) {
  108311. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  108312. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  108313. }
  108314. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  108315. };
  108316. // injecting a canvas element on top of the canvas 3D game
  108317. if (!VirtualJoystick.vjCanvas) {
  108318. window.addEventListener("resize", this._onResize, false);
  108319. VirtualJoystick.vjCanvas = document.createElement("canvas");
  108320. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108321. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108322. VirtualJoystick.vjCanvas.width = window.innerWidth;
  108323. VirtualJoystick.vjCanvas.height = window.innerHeight;
  108324. VirtualJoystick.vjCanvas.style.width = "100%";
  108325. VirtualJoystick.vjCanvas.style.height = "100%";
  108326. VirtualJoystick.vjCanvas.style.position = "absolute";
  108327. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  108328. VirtualJoystick.vjCanvas.style.top = "0px";
  108329. VirtualJoystick.vjCanvas.style.left = "0px";
  108330. VirtualJoystick.vjCanvas.style.zIndex = "5";
  108331. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  108332. // Support for jQuery PEP polyfill
  108333. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  108334. var context = VirtualJoystick.vjCanvas.getContext('2d');
  108335. if (!context) {
  108336. throw new Error("Unable to create canvas for virtual joystick");
  108337. }
  108338. VirtualJoystick.vjCanvasContext = context;
  108339. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  108340. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108341. document.body.appendChild(VirtualJoystick.vjCanvas);
  108342. }
  108343. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  108344. this.pressed = false;
  108345. // default joystick color
  108346. this._joystickColor = "cyan";
  108347. this._joystickPointerID = -1;
  108348. // current joystick position
  108349. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  108350. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  108351. // origin joystick position
  108352. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  108353. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  108354. this._onPointerDownHandlerRef = function (evt) {
  108355. _this._onPointerDown(evt);
  108356. };
  108357. this._onPointerMoveHandlerRef = function (evt) {
  108358. _this._onPointerMove(evt);
  108359. };
  108360. this._onPointerUpHandlerRef = function (evt) {
  108361. _this._onPointerUp(evt);
  108362. };
  108363. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  108364. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  108365. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  108366. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  108367. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  108368. evt.preventDefault(); // Disables system menu
  108369. }, false);
  108370. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108371. }
  108372. /**
  108373. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  108374. * @param newJoystickSensibility defines the new sensibility
  108375. */
  108376. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  108377. this._joystickSensibility = newJoystickSensibility;
  108378. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108379. };
  108380. VirtualJoystick.prototype._onPointerDown = function (e) {
  108381. var positionOnScreenCondition;
  108382. e.preventDefault();
  108383. if (this._leftJoystick === true) {
  108384. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  108385. }
  108386. else {
  108387. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  108388. }
  108389. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  108390. // First contact will be dedicated to the virtual joystick
  108391. this._joystickPointerID = e.pointerId;
  108392. this._joystickPointerStartPos.x = e.clientX;
  108393. this._joystickPointerStartPos.y = e.clientY;
  108394. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  108395. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  108396. this._deltaJoystickVector.x = 0;
  108397. this._deltaJoystickVector.y = 0;
  108398. this.pressed = true;
  108399. this._touches.add(e.pointerId.toString(), e);
  108400. }
  108401. else {
  108402. // You can only trigger the action buttons with a joystick declared
  108403. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  108404. this._action();
  108405. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  108406. }
  108407. }
  108408. };
  108409. VirtualJoystick.prototype._onPointerMove = function (e) {
  108410. // If the current pointer is the one associated to the joystick (first touch contact)
  108411. if (this._joystickPointerID == e.pointerId) {
  108412. this._joystickPointerPos.x = e.clientX;
  108413. this._joystickPointerPos.y = e.clientY;
  108414. this._deltaJoystickVector = this._joystickPointerPos.clone();
  108415. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  108416. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  108417. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  108418. switch (this._axisTargetedByLeftAndRight) {
  108419. case JoystickAxis.X:
  108420. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  108421. break;
  108422. case JoystickAxis.Y:
  108423. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  108424. break;
  108425. case JoystickAxis.Z:
  108426. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  108427. break;
  108428. }
  108429. var directionUpDown = this.reverseUpDown ? 1 : -1;
  108430. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  108431. switch (this._axisTargetedByUpAndDown) {
  108432. case JoystickAxis.X:
  108433. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  108434. break;
  108435. case JoystickAxis.Y:
  108436. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  108437. break;
  108438. case JoystickAxis.Z:
  108439. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  108440. break;
  108441. }
  108442. }
  108443. else {
  108444. var data = this._touches.get(e.pointerId.toString());
  108445. if (data) {
  108446. data.x = e.clientX;
  108447. data.y = e.clientY;
  108448. }
  108449. }
  108450. };
  108451. VirtualJoystick.prototype._onPointerUp = function (e) {
  108452. if (this._joystickPointerID == e.pointerId) {
  108453. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  108454. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  108455. this._joystickPointerID = -1;
  108456. this.pressed = false;
  108457. }
  108458. else {
  108459. var touch = this._touches.get(e.pointerId.toString());
  108460. if (touch) {
  108461. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108462. }
  108463. }
  108464. this._deltaJoystickVector.x = 0;
  108465. this._deltaJoystickVector.y = 0;
  108466. this._touches.remove(e.pointerId.toString());
  108467. };
  108468. /**
  108469. * Change the color of the virtual joystick
  108470. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  108471. */
  108472. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  108473. this._joystickColor = newColor;
  108474. };
  108475. /**
  108476. * Defines a callback to call when the joystick is touched
  108477. * @param action defines the callback
  108478. */
  108479. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  108480. this._action = action;
  108481. };
  108482. /**
  108483. * Defines which axis you'd like to control for left & right
  108484. * @param axis defines the axis to use
  108485. */
  108486. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  108487. switch (axis) {
  108488. case JoystickAxis.X:
  108489. case JoystickAxis.Y:
  108490. case JoystickAxis.Z:
  108491. this._axisTargetedByLeftAndRight = axis;
  108492. break;
  108493. default:
  108494. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108495. break;
  108496. }
  108497. };
  108498. /**
  108499. * Defines which axis you'd like to control for up & down
  108500. * @param axis defines the axis to use
  108501. */
  108502. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  108503. switch (axis) {
  108504. case JoystickAxis.X:
  108505. case JoystickAxis.Y:
  108506. case JoystickAxis.Z:
  108507. this._axisTargetedByUpAndDown = axis;
  108508. break;
  108509. default:
  108510. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108511. break;
  108512. }
  108513. };
  108514. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  108515. var _this = this;
  108516. if (this.pressed) {
  108517. this._touches.forEach(function (key, touch) {
  108518. if (touch.pointerId === _this._joystickPointerID) {
  108519. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  108520. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  108521. VirtualJoystick.vjCanvasContext.beginPath();
  108522. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108523. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108524. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  108525. VirtualJoystick.vjCanvasContext.stroke();
  108526. VirtualJoystick.vjCanvasContext.closePath();
  108527. VirtualJoystick.vjCanvasContext.beginPath();
  108528. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108529. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108530. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  108531. VirtualJoystick.vjCanvasContext.stroke();
  108532. VirtualJoystick.vjCanvasContext.closePath();
  108533. VirtualJoystick.vjCanvasContext.beginPath();
  108534. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108535. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  108536. VirtualJoystick.vjCanvasContext.stroke();
  108537. VirtualJoystick.vjCanvasContext.closePath();
  108538. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  108539. }
  108540. else {
  108541. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108542. VirtualJoystick.vjCanvasContext.beginPath();
  108543. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  108544. VirtualJoystick.vjCanvasContext.beginPath();
  108545. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  108546. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108547. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  108548. VirtualJoystick.vjCanvasContext.stroke();
  108549. VirtualJoystick.vjCanvasContext.closePath();
  108550. touch.prevX = touch.x;
  108551. touch.prevY = touch.y;
  108552. }
  108553. });
  108554. }
  108555. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108556. };
  108557. /**
  108558. * Release internal HTML canvas
  108559. */
  108560. VirtualJoystick.prototype.releaseCanvas = function () {
  108561. if (VirtualJoystick.vjCanvas) {
  108562. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  108563. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  108564. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  108565. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  108566. window.removeEventListener("resize", this._onResize);
  108567. document.body.removeChild(VirtualJoystick.vjCanvas);
  108568. VirtualJoystick.vjCanvas = null;
  108569. }
  108570. };
  108571. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  108572. VirtualJoystick._globalJoystickIndex = 0;
  108573. return VirtualJoystick;
  108574. }());
  108575. BABYLON.VirtualJoystick = VirtualJoystick;
  108576. })(BABYLON || (BABYLON = {}));
  108577. //# sourceMappingURL=babylon.virtualJoystick.js.map
  108578. var BABYLON;
  108579. (function (BABYLON) {
  108580. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  108581. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  108582. });
  108583. /**
  108584. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  108585. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108586. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108587. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108588. */
  108589. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  108590. __extends(VirtualJoysticksCamera, _super);
  108591. /**
  108592. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  108593. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108594. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108595. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108596. * @param name Define the name of the camera in the scene
  108597. * @param position Define the start position of the camera in the scene
  108598. * @param scene Define the scene the camera belongs to
  108599. */
  108600. function VirtualJoysticksCamera(name, position, scene) {
  108601. var _this = _super.call(this, name, position, scene) || this;
  108602. _this.inputs.addVirtualJoystick();
  108603. return _this;
  108604. }
  108605. /**
  108606. * Gets the current object class name.
  108607. * @return the class name
  108608. */
  108609. VirtualJoysticksCamera.prototype.getClassName = function () {
  108610. return "VirtualJoysticksCamera";
  108611. };
  108612. return VirtualJoysticksCamera;
  108613. }(BABYLON.FreeCamera));
  108614. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  108615. })(BABYLON || (BABYLON = {}));
  108616. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  108617. var BABYLON;
  108618. (function (BABYLON) {
  108619. /**
  108620. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  108621. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  108622. */
  108623. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  108624. function FreeCameraVirtualJoystickInput() {
  108625. }
  108626. /**
  108627. * Gets the left stick of the virtual joystick.
  108628. * @returns The virtual Joystick
  108629. */
  108630. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  108631. return this._leftjoystick;
  108632. };
  108633. /**
  108634. * Gets the right stick of the virtual joystick.
  108635. * @returns The virtual Joystick
  108636. */
  108637. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  108638. return this._rightjoystick;
  108639. };
  108640. /**
  108641. * Update the current camera state depending on the inputs that have been used this frame.
  108642. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  108643. */
  108644. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  108645. if (this._leftjoystick) {
  108646. var camera = this.camera;
  108647. var speed = camera._computeLocalCameraSpeed() * 50;
  108648. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  108649. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  108650. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  108651. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  108652. if (!this._leftjoystick.pressed) {
  108653. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  108654. }
  108655. if (!this._rightjoystick.pressed) {
  108656. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  108657. }
  108658. }
  108659. };
  108660. /**
  108661. * Attach the input controls to a specific dom element to get the input from.
  108662. * @param element Defines the element the controls should be listened from
  108663. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  108664. */
  108665. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  108666. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  108667. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  108668. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  108669. this._leftjoystick.setJoystickSensibility(0.15);
  108670. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  108671. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  108672. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  108673. this._rightjoystick.reverseUpDown = true;
  108674. this._rightjoystick.setJoystickSensibility(0.05);
  108675. this._rightjoystick.setJoystickColor("yellow");
  108676. };
  108677. /**
  108678. * Detach the current controls from the specified dom element.
  108679. * @param element Defines the element to stop listening the inputs from
  108680. */
  108681. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  108682. this._leftjoystick.releaseCanvas();
  108683. this._rightjoystick.releaseCanvas();
  108684. };
  108685. /**
  108686. * Gets the class name of the current intput.
  108687. * @returns the class name
  108688. */
  108689. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  108690. return "FreeCameraVirtualJoystickInput";
  108691. };
  108692. /**
  108693. * Get the friendly name associated with the input class.
  108694. * @returns the input friendly name
  108695. */
  108696. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  108697. return "virtualJoystick";
  108698. };
  108699. return FreeCameraVirtualJoystickInput;
  108700. }());
  108701. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  108702. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  108703. })(BABYLON || (BABYLON = {}));
  108704. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  108705. var BABYLON;
  108706. (function (BABYLON) {
  108707. /**
  108708. * Class used to specify simplification options
  108709. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108710. */
  108711. var SimplificationSettings = /** @class */ (function () {
  108712. /**
  108713. * Creates a SimplificationSettings
  108714. * @param quality expected quality
  108715. * @param distance distance when this optimized version should be used
  108716. * @param optimizeMesh already optimized mesh
  108717. */
  108718. function SimplificationSettings(
  108719. /** expected quality */
  108720. quality,
  108721. /** distance when this optimized version should be used */
  108722. distance,
  108723. /** already optimized mesh */
  108724. optimizeMesh) {
  108725. this.quality = quality;
  108726. this.distance = distance;
  108727. this.optimizeMesh = optimizeMesh;
  108728. }
  108729. return SimplificationSettings;
  108730. }());
  108731. BABYLON.SimplificationSettings = SimplificationSettings;
  108732. /**
  108733. * Queue used to order the simplification tasks
  108734. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108735. */
  108736. var SimplificationQueue = /** @class */ (function () {
  108737. /**
  108738. * Creates a new queue
  108739. */
  108740. function SimplificationQueue() {
  108741. this.running = false;
  108742. this._simplificationArray = [];
  108743. }
  108744. /**
  108745. * Adds a new simplification task
  108746. * @param task defines a task to add
  108747. */
  108748. SimplificationQueue.prototype.addTask = function (task) {
  108749. this._simplificationArray.push(task);
  108750. };
  108751. /**
  108752. * Execute next task
  108753. */
  108754. SimplificationQueue.prototype.executeNext = function () {
  108755. var task = this._simplificationArray.pop();
  108756. if (task) {
  108757. this.running = true;
  108758. this.runSimplification(task);
  108759. }
  108760. else {
  108761. this.running = false;
  108762. }
  108763. };
  108764. /**
  108765. * Execute a simplification task
  108766. * @param task defines the task to run
  108767. */
  108768. SimplificationQueue.prototype.runSimplification = function (task) {
  108769. var _this = this;
  108770. if (task.parallelProcessing) {
  108771. //parallel simplifier
  108772. task.settings.forEach(function (setting) {
  108773. var simplifier = _this.getSimplifier(task);
  108774. simplifier.simplify(setting, function (newMesh) {
  108775. task.mesh.addLODLevel(setting.distance, newMesh);
  108776. newMesh.isVisible = true;
  108777. //check if it is the last
  108778. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  108779. //all done, run the success callback.
  108780. task.successCallback();
  108781. }
  108782. _this.executeNext();
  108783. });
  108784. });
  108785. }
  108786. else {
  108787. //single simplifier.
  108788. var simplifier = this.getSimplifier(task);
  108789. var runDecimation = function (setting, callback) {
  108790. simplifier.simplify(setting, function (newMesh) {
  108791. task.mesh.addLODLevel(setting.distance, newMesh);
  108792. newMesh.isVisible = true;
  108793. //run the next quality level
  108794. callback();
  108795. });
  108796. };
  108797. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  108798. runDecimation(task.settings[loop.index], function () {
  108799. loop.executeNext();
  108800. });
  108801. }, function () {
  108802. //execution ended, run the success callback.
  108803. if (task.successCallback) {
  108804. task.successCallback();
  108805. }
  108806. _this.executeNext();
  108807. });
  108808. }
  108809. };
  108810. SimplificationQueue.prototype.getSimplifier = function (task) {
  108811. switch (task.simplificationType) {
  108812. case SimplificationType.QUADRATIC:
  108813. default:
  108814. return new QuadraticErrorSimplification(task.mesh);
  108815. }
  108816. };
  108817. return SimplificationQueue;
  108818. }());
  108819. BABYLON.SimplificationQueue = SimplificationQueue;
  108820. /**
  108821. * The implemented types of simplification
  108822. * At the moment only Quadratic Error Decimation is implemented
  108823. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108824. */
  108825. var SimplificationType;
  108826. (function (SimplificationType) {
  108827. /** Quadratic error decimation */
  108828. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  108829. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  108830. var DecimationTriangle = /** @class */ (function () {
  108831. function DecimationTriangle(vertices) {
  108832. this.vertices = vertices;
  108833. this.error = new Array(4);
  108834. this.deleted = false;
  108835. this.isDirty = false;
  108836. this.deletePending = false;
  108837. this.borderFactor = 0;
  108838. }
  108839. return DecimationTriangle;
  108840. }());
  108841. var DecimationVertex = /** @class */ (function () {
  108842. function DecimationVertex(position, id) {
  108843. this.position = position;
  108844. this.id = id;
  108845. this.isBorder = true;
  108846. this.q = new QuadraticMatrix();
  108847. this.triangleCount = 0;
  108848. this.triangleStart = 0;
  108849. this.originalOffsets = [];
  108850. }
  108851. DecimationVertex.prototype.updatePosition = function (newPosition) {
  108852. this.position.copyFrom(newPosition);
  108853. };
  108854. return DecimationVertex;
  108855. }());
  108856. var QuadraticMatrix = /** @class */ (function () {
  108857. function QuadraticMatrix(data) {
  108858. this.data = new Array(10);
  108859. for (var i = 0; i < 10; ++i) {
  108860. if (data && data[i]) {
  108861. this.data[i] = data[i];
  108862. }
  108863. else {
  108864. this.data[i] = 0;
  108865. }
  108866. }
  108867. }
  108868. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  108869. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  108870. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  108871. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  108872. return det;
  108873. };
  108874. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  108875. for (var i = 0; i < 10; ++i) {
  108876. this.data[i] += matrix.data[i];
  108877. }
  108878. };
  108879. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  108880. for (var i = 0; i < 10; ++i) {
  108881. this.data[i] += data[i];
  108882. }
  108883. };
  108884. QuadraticMatrix.prototype.add = function (matrix) {
  108885. var m = new QuadraticMatrix();
  108886. for (var i = 0; i < 10; ++i) {
  108887. m.data[i] = this.data[i] + matrix.data[i];
  108888. }
  108889. return m;
  108890. };
  108891. QuadraticMatrix.FromData = function (a, b, c, d) {
  108892. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  108893. };
  108894. //returning an array to avoid garbage collection
  108895. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  108896. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  108897. };
  108898. return QuadraticMatrix;
  108899. }());
  108900. var Reference = /** @class */ (function () {
  108901. function Reference(vertexId, triangleId) {
  108902. this.vertexId = vertexId;
  108903. this.triangleId = triangleId;
  108904. }
  108905. return Reference;
  108906. }());
  108907. /**
  108908. * An implementation of the Quadratic Error simplification algorithm.
  108909. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  108910. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  108911. * @author RaananW
  108912. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108913. */
  108914. var QuadraticErrorSimplification = /** @class */ (function () {
  108915. function QuadraticErrorSimplification(_mesh) {
  108916. this._mesh = _mesh;
  108917. this.syncIterations = 5000;
  108918. this.aggressiveness = 7;
  108919. this.decimationIterations = 100;
  108920. this.boundingBoxEpsilon = BABYLON.Epsilon;
  108921. }
  108922. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  108923. var _this = this;
  108924. this.initDecimatedMesh();
  108925. //iterating through the submeshes array, one after the other.
  108926. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  108927. _this.initWithMesh(loop.index, function () {
  108928. _this.runDecimation(settings, loop.index, function () {
  108929. loop.executeNext();
  108930. });
  108931. }, settings.optimizeMesh);
  108932. }, function () {
  108933. setTimeout(function () {
  108934. successCallback(_this._reconstructedMesh);
  108935. }, 0);
  108936. });
  108937. };
  108938. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  108939. var _this = this;
  108940. var targetCount = ~~(this.triangles.length * settings.quality);
  108941. var deletedTriangles = 0;
  108942. var triangleCount = this.triangles.length;
  108943. var iterationFunction = function (iteration, callback) {
  108944. setTimeout(function () {
  108945. if (iteration % 5 === 0) {
  108946. _this.updateMesh(iteration === 0);
  108947. }
  108948. for (var i = 0; i < _this.triangles.length; ++i) {
  108949. _this.triangles[i].isDirty = false;
  108950. }
  108951. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  108952. var trianglesIterator = function (i) {
  108953. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  108954. var t = _this.triangles[tIdx];
  108955. if (!t) {
  108956. return;
  108957. }
  108958. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  108959. return;
  108960. }
  108961. for (var j = 0; j < 3; ++j) {
  108962. if (t.error[j] < threshold) {
  108963. var deleted0 = [];
  108964. var deleted1 = [];
  108965. var v0 = t.vertices[j];
  108966. var v1 = t.vertices[(j + 1) % 3];
  108967. if (v0.isBorder || v1.isBorder) {
  108968. continue;
  108969. }
  108970. var p = BABYLON.Vector3.Zero();
  108971. var n = BABYLON.Vector3.Zero();
  108972. var uv = BABYLON.Vector2.Zero();
  108973. var color = new BABYLON.Color4(0, 0, 0, 1);
  108974. _this.calculateError(v0, v1, p, n, uv, color);
  108975. var delTr = new Array();
  108976. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  108977. continue;
  108978. }
  108979. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  108980. continue;
  108981. }
  108982. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  108983. continue;
  108984. }
  108985. var uniqueArray = new Array();
  108986. delTr.forEach(function (deletedT) {
  108987. if (uniqueArray.indexOf(deletedT) === -1) {
  108988. deletedT.deletePending = true;
  108989. uniqueArray.push(deletedT);
  108990. }
  108991. });
  108992. if (uniqueArray.length % 2 !== 0) {
  108993. continue;
  108994. }
  108995. v0.q = v1.q.add(v0.q);
  108996. v0.updatePosition(p);
  108997. var tStart = _this.references.length;
  108998. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  108999. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  109000. var tCount = _this.references.length - tStart;
  109001. if (tCount <= v0.triangleCount) {
  109002. if (tCount) {
  109003. for (var c = 0; c < tCount; c++) {
  109004. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  109005. }
  109006. }
  109007. }
  109008. else {
  109009. v0.triangleStart = tStart;
  109010. }
  109011. v0.triangleCount = tCount;
  109012. break;
  109013. }
  109014. }
  109015. };
  109016. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  109017. }, 0);
  109018. };
  109019. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  109020. if (triangleCount - deletedTriangles <= targetCount) {
  109021. loop.breakLoop();
  109022. }
  109023. else {
  109024. iterationFunction(loop.index, function () {
  109025. loop.executeNext();
  109026. });
  109027. }
  109028. }, function () {
  109029. setTimeout(function () {
  109030. //reconstruct this part of the mesh
  109031. _this.reconstructMesh(submeshIndex);
  109032. successCallback();
  109033. }, 0);
  109034. });
  109035. };
  109036. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  109037. var _this = this;
  109038. this.vertices = [];
  109039. this.triangles = [];
  109040. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  109041. var indices = this._mesh.getIndices();
  109042. var submesh = this._mesh.subMeshes[submeshIndex];
  109043. var findInVertices = function (positionToSearch) {
  109044. if (optimizeMesh) {
  109045. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  109046. if (_this.vertices[ii].position.equals(positionToSearch)) {
  109047. return _this.vertices[ii];
  109048. }
  109049. }
  109050. }
  109051. return null;
  109052. };
  109053. var vertexReferences = [];
  109054. var vertexInit = function (i) {
  109055. if (!positionData) {
  109056. return;
  109057. }
  109058. var offset = i + submesh.verticesStart;
  109059. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  109060. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  109061. vertex.originalOffsets.push(offset);
  109062. if (vertex.id === _this.vertices.length) {
  109063. _this.vertices.push(vertex);
  109064. }
  109065. vertexReferences.push(vertex.id);
  109066. };
  109067. //var totalVertices = mesh.getTotalVertices();
  109068. var totalVertices = submesh.verticesCount;
  109069. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  109070. var indicesInit = function (i) {
  109071. if (!indices) {
  109072. return;
  109073. }
  109074. var offset = (submesh.indexStart / 3) + i;
  109075. var pos = (offset * 3);
  109076. var i0 = indices[pos + 0];
  109077. var i1 = indices[pos + 1];
  109078. var i2 = indices[pos + 2];
  109079. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  109080. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  109081. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  109082. var triangle = new DecimationTriangle([v0, v1, v2]);
  109083. triangle.originalOffset = pos;
  109084. _this.triangles.push(triangle);
  109085. };
  109086. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  109087. _this.init(callback);
  109088. });
  109089. });
  109090. };
  109091. QuadraticErrorSimplification.prototype.init = function (callback) {
  109092. var _this = this;
  109093. var triangleInit1 = function (i) {
  109094. var t = _this.triangles[i];
  109095. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  109096. for (var j = 0; j < 3; j++) {
  109097. 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))));
  109098. }
  109099. };
  109100. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  109101. var triangleInit2 = function (i) {
  109102. var t = _this.triangles[i];
  109103. for (var j = 0; j < 3; ++j) {
  109104. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  109105. }
  109106. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109107. };
  109108. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  109109. callback();
  109110. });
  109111. });
  109112. };
  109113. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  109114. var newTriangles = [];
  109115. var i;
  109116. for (i = 0; i < this.vertices.length; ++i) {
  109117. this.vertices[i].triangleCount = 0;
  109118. }
  109119. var t;
  109120. var j;
  109121. for (i = 0; i < this.triangles.length; ++i) {
  109122. if (!this.triangles[i].deleted) {
  109123. t = this.triangles[i];
  109124. for (j = 0; j < 3; ++j) {
  109125. t.vertices[j].triangleCount = 1;
  109126. }
  109127. newTriangles.push(t);
  109128. }
  109129. }
  109130. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  109131. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  109132. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  109133. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  109134. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  109135. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  109136. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  109137. var vertexCount = 0;
  109138. for (i = 0; i < this.vertices.length; ++i) {
  109139. var vertex = this.vertices[i];
  109140. vertex.id = vertexCount;
  109141. if (vertex.triangleCount) {
  109142. vertex.originalOffsets.forEach(function (originalOffset) {
  109143. if (!normalData) {
  109144. return;
  109145. }
  109146. newPositionData.push(vertex.position.x);
  109147. newPositionData.push(vertex.position.y);
  109148. newPositionData.push(vertex.position.z);
  109149. newNormalData.push(normalData[originalOffset * 3]);
  109150. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  109151. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  109152. if (uvs && uvs.length) {
  109153. newUVsData.push(uvs[(originalOffset * 2)]);
  109154. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  109155. }
  109156. else if (colorsData && colorsData.length) {
  109157. newColorsData.push(colorsData[(originalOffset * 4)]);
  109158. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  109159. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  109160. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  109161. }
  109162. ++vertexCount;
  109163. });
  109164. }
  109165. }
  109166. var startingIndex = this._reconstructedMesh.getTotalIndices();
  109167. var startingVertex = this._reconstructedMesh.getTotalVertices();
  109168. var submeshesArray = this._reconstructedMesh.subMeshes;
  109169. this._reconstructedMesh.subMeshes = [];
  109170. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  109171. var originalIndices = this._mesh.getIndices();
  109172. for (i = 0; i < newTriangles.length; ++i) {
  109173. t = newTriangles[i]; //now get the new referencing point for each vertex
  109174. [0, 1, 2].forEach(function (idx) {
  109175. var id = originalIndices[t.originalOffset + idx];
  109176. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  109177. if (offset < 0) {
  109178. offset = 0;
  109179. }
  109180. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  109181. });
  109182. }
  109183. //overwriting the old vertex buffers and indices.
  109184. this._reconstructedMesh.setIndices(newIndicesArray);
  109185. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  109186. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  109187. if (newUVsData.length > 0) {
  109188. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  109189. }
  109190. if (newColorsData.length > 0) {
  109191. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  109192. }
  109193. //create submesh
  109194. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  109195. if (submeshIndex > 0) {
  109196. this._reconstructedMesh.subMeshes = [];
  109197. submeshesArray.forEach(function (submesh) {
  109198. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  109199. });
  109200. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  109201. }
  109202. };
  109203. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  109204. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  109205. this._reconstructedMesh.material = this._mesh.material;
  109206. this._reconstructedMesh.parent = this._mesh.parent;
  109207. this._reconstructedMesh.isVisible = false;
  109208. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  109209. };
  109210. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  109211. for (var i = 0; i < vertex1.triangleCount; ++i) {
  109212. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  109213. if (t.deleted) {
  109214. continue;
  109215. }
  109216. var s = this.references[vertex1.triangleStart + i].vertexId;
  109217. var v1 = t.vertices[(s + 1) % 3];
  109218. var v2 = t.vertices[(s + 2) % 3];
  109219. if ((v1 === vertex2 || v2 === vertex2)) {
  109220. deletedArray[i] = true;
  109221. delTr.push(t);
  109222. continue;
  109223. }
  109224. var d1 = v1.position.subtract(point);
  109225. d1 = d1.normalize();
  109226. var d2 = v2.position.subtract(point);
  109227. d2 = d2.normalize();
  109228. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  109229. return true;
  109230. }
  109231. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  109232. deletedArray[i] = false;
  109233. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  109234. return true;
  109235. }
  109236. }
  109237. return false;
  109238. };
  109239. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  109240. var newDeleted = deletedTriangles;
  109241. for (var i = 0; i < vertex.triangleCount; ++i) {
  109242. var ref = this.references[vertex.triangleStart + i];
  109243. var t = this.triangles[ref.triangleId];
  109244. if (t.deleted) {
  109245. continue;
  109246. }
  109247. if (deletedArray[i] && t.deletePending) {
  109248. t.deleted = true;
  109249. newDeleted++;
  109250. continue;
  109251. }
  109252. t.vertices[ref.vertexId] = origVertex;
  109253. t.isDirty = true;
  109254. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  109255. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  109256. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  109257. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109258. this.references.push(ref);
  109259. }
  109260. return newDeleted;
  109261. };
  109262. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  109263. for (var i = 0; i < this.vertices.length; ++i) {
  109264. var vCount = [];
  109265. var vId = [];
  109266. var v = this.vertices[i];
  109267. var j;
  109268. for (j = 0; j < v.triangleCount; ++j) {
  109269. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  109270. for (var ii = 0; ii < 3; ii++) {
  109271. var ofs = 0;
  109272. var vv = triangle.vertices[ii];
  109273. while (ofs < vCount.length) {
  109274. if (vId[ofs] === vv.id) {
  109275. break;
  109276. }
  109277. ++ofs;
  109278. }
  109279. if (ofs === vCount.length) {
  109280. vCount.push(1);
  109281. vId.push(vv.id);
  109282. }
  109283. else {
  109284. vCount[ofs]++;
  109285. }
  109286. }
  109287. }
  109288. for (j = 0; j < vCount.length; ++j) {
  109289. if (vCount[j] === 1) {
  109290. this.vertices[vId[j]].isBorder = true;
  109291. }
  109292. else {
  109293. this.vertices[vId[j]].isBorder = false;
  109294. }
  109295. }
  109296. }
  109297. };
  109298. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  109299. if (identifyBorders === void 0) { identifyBorders = false; }
  109300. var i;
  109301. if (!identifyBorders) {
  109302. var newTrianglesVector = [];
  109303. for (i = 0; i < this.triangles.length; ++i) {
  109304. if (!this.triangles[i].deleted) {
  109305. newTrianglesVector.push(this.triangles[i]);
  109306. }
  109307. }
  109308. this.triangles = newTrianglesVector;
  109309. }
  109310. for (i = 0; i < this.vertices.length; ++i) {
  109311. this.vertices[i].triangleCount = 0;
  109312. this.vertices[i].triangleStart = 0;
  109313. }
  109314. var t;
  109315. var j;
  109316. var v;
  109317. for (i = 0; i < this.triangles.length; ++i) {
  109318. t = this.triangles[i];
  109319. for (j = 0; j < 3; ++j) {
  109320. v = t.vertices[j];
  109321. v.triangleCount++;
  109322. }
  109323. }
  109324. var tStart = 0;
  109325. for (i = 0; i < this.vertices.length; ++i) {
  109326. this.vertices[i].triangleStart = tStart;
  109327. tStart += this.vertices[i].triangleCount;
  109328. this.vertices[i].triangleCount = 0;
  109329. }
  109330. var newReferences = new Array(this.triangles.length * 3);
  109331. for (i = 0; i < this.triangles.length; ++i) {
  109332. t = this.triangles[i];
  109333. for (j = 0; j < 3; ++j) {
  109334. v = t.vertices[j];
  109335. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  109336. v.triangleCount++;
  109337. }
  109338. }
  109339. this.references = newReferences;
  109340. if (identifyBorders) {
  109341. this.identifyBorder();
  109342. }
  109343. };
  109344. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  109345. var x = point.x;
  109346. var y = point.y;
  109347. var z = point.z;
  109348. 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
  109349. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  109350. };
  109351. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  109352. var q = vertex1.q.add(vertex2.q);
  109353. var border = vertex1.isBorder && vertex2.isBorder;
  109354. var error = 0;
  109355. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  109356. if (qDet !== 0 && !border) {
  109357. if (!pointResult) {
  109358. pointResult = BABYLON.Vector3.Zero();
  109359. }
  109360. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  109361. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  109362. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  109363. error = this.vertexError(q, pointResult);
  109364. }
  109365. else {
  109366. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  109367. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  109368. var error1 = this.vertexError(q, vertex1.position);
  109369. var error2 = this.vertexError(q, vertex2.position);
  109370. var error3 = this.vertexError(q, p3);
  109371. error = Math.min(error1, error2, error3);
  109372. if (error === error1) {
  109373. if (pointResult) {
  109374. pointResult.copyFrom(vertex1.position);
  109375. }
  109376. }
  109377. else if (error === error2) {
  109378. if (pointResult) {
  109379. pointResult.copyFrom(vertex2.position);
  109380. }
  109381. }
  109382. else {
  109383. if (pointResult) {
  109384. pointResult.copyFrom(p3);
  109385. }
  109386. }
  109387. }
  109388. return error;
  109389. };
  109390. return QuadraticErrorSimplification;
  109391. }());
  109392. })(BABYLON || (BABYLON = {}));
  109393. //# sourceMappingURL=babylon.meshSimplification.js.map
  109394. var BABYLON;
  109395. (function (BABYLON) {
  109396. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  109397. get: function () {
  109398. if (!this._simplificationQueue) {
  109399. this._simplificationQueue = new BABYLON.SimplificationQueue();
  109400. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  109401. if (!component) {
  109402. component = new SimplicationQueueSceneComponent(this);
  109403. this._addComponent(component);
  109404. }
  109405. }
  109406. return this._simplificationQueue;
  109407. },
  109408. set: function (value) {
  109409. this._simplificationQueue = value;
  109410. },
  109411. enumerable: true,
  109412. configurable: true
  109413. });
  109414. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  109415. if (parallelProcessing === void 0) { parallelProcessing = true; }
  109416. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  109417. this.getScene().simplificationQueue.addTask({
  109418. settings: settings,
  109419. parallelProcessing: parallelProcessing,
  109420. mesh: this,
  109421. simplificationType: simplificationType,
  109422. successCallback: successCallback
  109423. });
  109424. return this;
  109425. };
  109426. /**
  109427. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  109428. * created in a scene
  109429. */
  109430. var SimplicationQueueSceneComponent = /** @class */ (function () {
  109431. /**
  109432. * Creates a new instance of the component for the given scene
  109433. * @param scene Defines the scene to register the component in
  109434. */
  109435. function SimplicationQueueSceneComponent(scene) {
  109436. /**
  109437. * The component name helpfull to identify the component in the list of scene components.
  109438. */
  109439. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  109440. this.scene = scene;
  109441. }
  109442. /**
  109443. * Registers the component in a given scene
  109444. */
  109445. SimplicationQueueSceneComponent.prototype.register = function () {
  109446. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  109447. };
  109448. /**
  109449. * Rebuilds the elements related to this component in case of
  109450. * context lost for instance.
  109451. */
  109452. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  109453. // Nothing to do for this component
  109454. };
  109455. /**
  109456. * Disposes the component and the associated ressources
  109457. */
  109458. SimplicationQueueSceneComponent.prototype.dispose = function () {
  109459. // Nothing to do for this component
  109460. };
  109461. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  109462. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  109463. this.scene._simplificationQueue.executeNext();
  109464. }
  109465. };
  109466. return SimplicationQueueSceneComponent;
  109467. }());
  109468. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  109469. })(BABYLON || (BABYLON = {}));
  109470. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  109471. var BABYLON;
  109472. (function (BABYLON) {
  109473. /**
  109474. * Class used to represent a specific level of detail of a mesh
  109475. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  109476. */
  109477. var MeshLODLevel = /** @class */ (function () {
  109478. /**
  109479. * Creates a new LOD level
  109480. * @param distance defines the distance where this level should star being displayed
  109481. * @param mesh defines the mesh to use to render this level
  109482. */
  109483. function MeshLODLevel(
  109484. /** Defines the distance where this level should star being displayed */
  109485. distance,
  109486. /** Defines the mesh to use to render this level */
  109487. mesh) {
  109488. this.distance = distance;
  109489. this.mesh = mesh;
  109490. }
  109491. return MeshLODLevel;
  109492. }());
  109493. BABYLON.MeshLODLevel = MeshLODLevel;
  109494. })(BABYLON || (BABYLON = {}));
  109495. //# sourceMappingURL=babylon.meshLODLevel.js.map
  109496. var BABYLON;
  109497. (function (BABYLON) {
  109498. /**
  109499. * Defines the root class used to create scene optimization to use with SceneOptimizer
  109500. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109501. */
  109502. var SceneOptimization = /** @class */ (function () {
  109503. /**
  109504. * Creates the SceneOptimization object
  109505. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109506. * @param desc defines the description associated with the optimization
  109507. */
  109508. function SceneOptimization(
  109509. /**
  109510. * Defines the priority of this optimization (0 by default which means first in the list)
  109511. */
  109512. priority) {
  109513. if (priority === void 0) { priority = 0; }
  109514. this.priority = priority;
  109515. }
  109516. /**
  109517. * Gets a string describing the action executed by the current optimization
  109518. * @returns description string
  109519. */
  109520. SceneOptimization.prototype.getDescription = function () {
  109521. return "";
  109522. };
  109523. /**
  109524. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109525. * @param scene defines the current scene where to apply this optimization
  109526. * @param optimizer defines the current optimizer
  109527. * @returns true if everything that can be done was applied
  109528. */
  109529. SceneOptimization.prototype.apply = function (scene, optimizer) {
  109530. return true;
  109531. };
  109532. return SceneOptimization;
  109533. }());
  109534. BABYLON.SceneOptimization = SceneOptimization;
  109535. /**
  109536. * Defines an optimization used to reduce the size of render target textures
  109537. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109538. */
  109539. var TextureOptimization = /** @class */ (function (_super) {
  109540. __extends(TextureOptimization, _super);
  109541. /**
  109542. * Creates the TextureOptimization object
  109543. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109544. * @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
  109545. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109546. */
  109547. function TextureOptimization(
  109548. /**
  109549. * Defines the priority of this optimization (0 by default which means first in the list)
  109550. */
  109551. priority,
  109552. /**
  109553. * 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
  109554. */
  109555. maximumSize,
  109556. /**
  109557. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109558. */
  109559. step) {
  109560. if (priority === void 0) { priority = 0; }
  109561. if (maximumSize === void 0) { maximumSize = 1024; }
  109562. if (step === void 0) { step = 0.5; }
  109563. var _this = _super.call(this, priority) || this;
  109564. _this.priority = priority;
  109565. _this.maximumSize = maximumSize;
  109566. _this.step = step;
  109567. return _this;
  109568. }
  109569. /**
  109570. * Gets a string describing the action executed by the current optimization
  109571. * @returns description string
  109572. */
  109573. TextureOptimization.prototype.getDescription = function () {
  109574. return "Reducing render target texture size to " + this.maximumSize;
  109575. };
  109576. /**
  109577. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109578. * @param scene defines the current scene where to apply this optimization
  109579. * @param optimizer defines the current optimizer
  109580. * @returns true if everything that can be done was applied
  109581. */
  109582. TextureOptimization.prototype.apply = function (scene, optimizer) {
  109583. var allDone = true;
  109584. for (var index = 0; index < scene.textures.length; index++) {
  109585. var texture = scene.textures[index];
  109586. if (!texture.canRescale || texture.getContext) {
  109587. continue;
  109588. }
  109589. var currentSize = texture.getSize();
  109590. var maxDimension = Math.max(currentSize.width, currentSize.height);
  109591. if (maxDimension > this.maximumSize) {
  109592. texture.scale(this.step);
  109593. allDone = false;
  109594. }
  109595. }
  109596. return allDone;
  109597. };
  109598. return TextureOptimization;
  109599. }(SceneOptimization));
  109600. BABYLON.TextureOptimization = TextureOptimization;
  109601. /**
  109602. * Defines an optimization used to increase or decrease the rendering resolution
  109603. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109604. */
  109605. var HardwareScalingOptimization = /** @class */ (function (_super) {
  109606. __extends(HardwareScalingOptimization, _super);
  109607. /**
  109608. * Creates the HardwareScalingOptimization object
  109609. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109610. * @param maximumScale defines the maximum scale to use (2 by default)
  109611. * @param step defines the step to use between two passes (0.5 by default)
  109612. */
  109613. function HardwareScalingOptimization(
  109614. /**
  109615. * Defines the priority of this optimization (0 by default which means first in the list)
  109616. */
  109617. priority,
  109618. /**
  109619. * Defines the maximum scale to use (2 by default)
  109620. */
  109621. maximumScale,
  109622. /**
  109623. * Defines the step to use between two passes (0.5 by default)
  109624. */
  109625. step) {
  109626. if (priority === void 0) { priority = 0; }
  109627. if (maximumScale === void 0) { maximumScale = 2; }
  109628. if (step === void 0) { step = 0.25; }
  109629. var _this = _super.call(this, priority) || this;
  109630. _this.priority = priority;
  109631. _this.maximumScale = maximumScale;
  109632. _this.step = step;
  109633. _this._currentScale = -1;
  109634. _this._directionOffset = 1;
  109635. return _this;
  109636. }
  109637. /**
  109638. * Gets a string describing the action executed by the current optimization
  109639. * @return description string
  109640. */
  109641. HardwareScalingOptimization.prototype.getDescription = function () {
  109642. return "Setting hardware scaling level to " + this._currentScale;
  109643. };
  109644. /**
  109645. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109646. * @param scene defines the current scene where to apply this optimization
  109647. * @param optimizer defines the current optimizer
  109648. * @returns true if everything that can be done was applied
  109649. */
  109650. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  109651. if (this._currentScale === -1) {
  109652. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  109653. if (this._currentScale > this.maximumScale) {
  109654. this._directionOffset = -1;
  109655. }
  109656. }
  109657. this._currentScale += this._directionOffset * this.step;
  109658. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  109659. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  109660. };
  109661. return HardwareScalingOptimization;
  109662. }(SceneOptimization));
  109663. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  109664. /**
  109665. * Defines an optimization used to remove shadows
  109666. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109667. */
  109668. var ShadowsOptimization = /** @class */ (function (_super) {
  109669. __extends(ShadowsOptimization, _super);
  109670. function ShadowsOptimization() {
  109671. return _super !== null && _super.apply(this, arguments) || this;
  109672. }
  109673. /**
  109674. * Gets a string describing the action executed by the current optimization
  109675. * @return description string
  109676. */
  109677. ShadowsOptimization.prototype.getDescription = function () {
  109678. return "Turning shadows on/off";
  109679. };
  109680. /**
  109681. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109682. * @param scene defines the current scene where to apply this optimization
  109683. * @param optimizer defines the current optimizer
  109684. * @returns true if everything that can be done was applied
  109685. */
  109686. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  109687. scene.shadowsEnabled = optimizer.isInImprovementMode;
  109688. return true;
  109689. };
  109690. return ShadowsOptimization;
  109691. }(SceneOptimization));
  109692. BABYLON.ShadowsOptimization = ShadowsOptimization;
  109693. /**
  109694. * Defines an optimization used to turn post-processes off
  109695. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109696. */
  109697. var PostProcessesOptimization = /** @class */ (function (_super) {
  109698. __extends(PostProcessesOptimization, _super);
  109699. function PostProcessesOptimization() {
  109700. return _super !== null && _super.apply(this, arguments) || this;
  109701. }
  109702. /**
  109703. * Gets a string describing the action executed by the current optimization
  109704. * @return description string
  109705. */
  109706. PostProcessesOptimization.prototype.getDescription = function () {
  109707. return "Turning post-processes on/off";
  109708. };
  109709. /**
  109710. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109711. * @param scene defines the current scene where to apply this optimization
  109712. * @param optimizer defines the current optimizer
  109713. * @returns true if everything that can be done was applied
  109714. */
  109715. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  109716. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  109717. return true;
  109718. };
  109719. return PostProcessesOptimization;
  109720. }(SceneOptimization));
  109721. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  109722. /**
  109723. * Defines an optimization used to turn lens flares off
  109724. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109725. */
  109726. var LensFlaresOptimization = /** @class */ (function (_super) {
  109727. __extends(LensFlaresOptimization, _super);
  109728. function LensFlaresOptimization() {
  109729. return _super !== null && _super.apply(this, arguments) || this;
  109730. }
  109731. /**
  109732. * Gets a string describing the action executed by the current optimization
  109733. * @return description string
  109734. */
  109735. LensFlaresOptimization.prototype.getDescription = function () {
  109736. return "Turning lens flares on/off";
  109737. };
  109738. /**
  109739. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109740. * @param scene defines the current scene where to apply this optimization
  109741. * @param optimizer defines the current optimizer
  109742. * @returns true if everything that can be done was applied
  109743. */
  109744. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  109745. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  109746. return true;
  109747. };
  109748. return LensFlaresOptimization;
  109749. }(SceneOptimization));
  109750. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  109751. /**
  109752. * Defines an optimization based on user defined callback.
  109753. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109754. */
  109755. var CustomOptimization = /** @class */ (function (_super) {
  109756. __extends(CustomOptimization, _super);
  109757. function CustomOptimization() {
  109758. return _super !== null && _super.apply(this, arguments) || this;
  109759. }
  109760. /**
  109761. * Gets a string describing the action executed by the current optimization
  109762. * @returns description string
  109763. */
  109764. CustomOptimization.prototype.getDescription = function () {
  109765. if (this.onGetDescription) {
  109766. return this.onGetDescription();
  109767. }
  109768. return "Running user defined callback";
  109769. };
  109770. /**
  109771. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109772. * @param scene defines the current scene where to apply this optimization
  109773. * @param optimizer defines the current optimizer
  109774. * @returns true if everything that can be done was applied
  109775. */
  109776. CustomOptimization.prototype.apply = function (scene, optimizer) {
  109777. if (this.onApply) {
  109778. return this.onApply(scene, optimizer);
  109779. }
  109780. return true;
  109781. };
  109782. return CustomOptimization;
  109783. }(SceneOptimization));
  109784. BABYLON.CustomOptimization = CustomOptimization;
  109785. /**
  109786. * Defines an optimization used to turn particles off
  109787. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109788. */
  109789. var ParticlesOptimization = /** @class */ (function (_super) {
  109790. __extends(ParticlesOptimization, _super);
  109791. function ParticlesOptimization() {
  109792. return _super !== null && _super.apply(this, arguments) || this;
  109793. }
  109794. /**
  109795. * Gets a string describing the action executed by the current optimization
  109796. * @return description string
  109797. */
  109798. ParticlesOptimization.prototype.getDescription = function () {
  109799. return "Turning particles on/off";
  109800. };
  109801. /**
  109802. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109803. * @param scene defines the current scene where to apply this optimization
  109804. * @param optimizer defines the current optimizer
  109805. * @returns true if everything that can be done was applied
  109806. */
  109807. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  109808. scene.particlesEnabled = optimizer.isInImprovementMode;
  109809. return true;
  109810. };
  109811. return ParticlesOptimization;
  109812. }(SceneOptimization));
  109813. BABYLON.ParticlesOptimization = ParticlesOptimization;
  109814. /**
  109815. * Defines an optimization used to turn render targets off
  109816. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109817. */
  109818. var RenderTargetsOptimization = /** @class */ (function (_super) {
  109819. __extends(RenderTargetsOptimization, _super);
  109820. function RenderTargetsOptimization() {
  109821. return _super !== null && _super.apply(this, arguments) || this;
  109822. }
  109823. /**
  109824. * Gets a string describing the action executed by the current optimization
  109825. * @return description string
  109826. */
  109827. RenderTargetsOptimization.prototype.getDescription = function () {
  109828. return "Turning render targets off";
  109829. };
  109830. /**
  109831. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109832. * @param scene defines the current scene where to apply this optimization
  109833. * @param optimizer defines the current optimizer
  109834. * @returns true if everything that can be done was applied
  109835. */
  109836. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  109837. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  109838. return true;
  109839. };
  109840. return RenderTargetsOptimization;
  109841. }(SceneOptimization));
  109842. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  109843. /**
  109844. * Defines an optimization used to merge meshes with compatible materials
  109845. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109846. */
  109847. var MergeMeshesOptimization = /** @class */ (function (_super) {
  109848. __extends(MergeMeshesOptimization, _super);
  109849. function MergeMeshesOptimization() {
  109850. var _this = _super !== null && _super.apply(this, arguments) || this;
  109851. _this._canBeMerged = function (abstractMesh) {
  109852. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  109853. return false;
  109854. }
  109855. var mesh = abstractMesh;
  109856. if (mesh.isDisposed()) {
  109857. return false;
  109858. }
  109859. if (!mesh.isVisible || !mesh.isEnabled()) {
  109860. return false;
  109861. }
  109862. if (mesh.instances.length > 0) {
  109863. return false;
  109864. }
  109865. if (mesh.skeleton || mesh.hasLODLevels) {
  109866. return false;
  109867. }
  109868. return true;
  109869. };
  109870. return _this;
  109871. }
  109872. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  109873. /**
  109874. * Gets or sets a boolean which defines if optimization octree has to be updated
  109875. */
  109876. get: function () {
  109877. return MergeMeshesOptimization._UpdateSelectionTree;
  109878. },
  109879. /**
  109880. * Gets or sets a boolean which defines if optimization octree has to be updated
  109881. */
  109882. set: function (value) {
  109883. MergeMeshesOptimization._UpdateSelectionTree = value;
  109884. },
  109885. enumerable: true,
  109886. configurable: true
  109887. });
  109888. /**
  109889. * Gets a string describing the action executed by the current optimization
  109890. * @return description string
  109891. */
  109892. MergeMeshesOptimization.prototype.getDescription = function () {
  109893. return "Merging similar meshes together";
  109894. };
  109895. /**
  109896. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109897. * @param scene defines the current scene where to apply this optimization
  109898. * @param optimizer defines the current optimizer
  109899. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  109900. * @returns true if everything that can be done was applied
  109901. */
  109902. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  109903. var globalPool = scene.meshes.slice(0);
  109904. var globalLength = globalPool.length;
  109905. for (var index = 0; index < globalLength; index++) {
  109906. var currentPool = new Array();
  109907. var current = globalPool[index];
  109908. // Checks
  109909. if (!this._canBeMerged(current)) {
  109910. continue;
  109911. }
  109912. currentPool.push(current);
  109913. // Find compatible meshes
  109914. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  109915. var otherMesh = globalPool[subIndex];
  109916. if (!this._canBeMerged(otherMesh)) {
  109917. continue;
  109918. }
  109919. if (otherMesh.material !== current.material) {
  109920. continue;
  109921. }
  109922. if (otherMesh.checkCollisions !== current.checkCollisions) {
  109923. continue;
  109924. }
  109925. currentPool.push(otherMesh);
  109926. globalLength--;
  109927. globalPool.splice(subIndex, 1);
  109928. subIndex--;
  109929. }
  109930. if (currentPool.length < 2) {
  109931. continue;
  109932. }
  109933. // Merge meshes
  109934. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  109935. }
  109936. // Call the octree system optimization if it is defined.
  109937. var sceneAsAny = scene;
  109938. if (sceneAsAny.createOrUpdateSelectionOctree) {
  109939. if (updateSelectionTree != undefined) {
  109940. if (updateSelectionTree) {
  109941. sceneAsAny.createOrUpdateSelectionOctree();
  109942. }
  109943. }
  109944. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  109945. sceneAsAny.createOrUpdateSelectionOctree();
  109946. }
  109947. }
  109948. return true;
  109949. };
  109950. MergeMeshesOptimization._UpdateSelectionTree = false;
  109951. return MergeMeshesOptimization;
  109952. }(SceneOptimization));
  109953. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  109954. /**
  109955. * Defines a list of options used by SceneOptimizer
  109956. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109957. */
  109958. var SceneOptimizerOptions = /** @class */ (function () {
  109959. /**
  109960. * Creates a new list of options used by SceneOptimizer
  109961. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  109962. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  109963. */
  109964. function SceneOptimizerOptions(
  109965. /**
  109966. * Defines the target frame rate to reach (60 by default)
  109967. */
  109968. targetFrameRate,
  109969. /**
  109970. * Defines the interval between two checkes (2000ms by default)
  109971. */
  109972. trackerDuration) {
  109973. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  109974. if (trackerDuration === void 0) { trackerDuration = 2000; }
  109975. this.targetFrameRate = targetFrameRate;
  109976. this.trackerDuration = trackerDuration;
  109977. /**
  109978. * Gets the list of optimizations to apply
  109979. */
  109980. this.optimizations = new Array();
  109981. }
  109982. /**
  109983. * Add a new optimization
  109984. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  109985. * @returns the current SceneOptimizerOptions
  109986. */
  109987. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  109988. this.optimizations.push(optimization);
  109989. return this;
  109990. };
  109991. /**
  109992. * Add a new custom optimization
  109993. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  109994. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  109995. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109996. * @returns the current SceneOptimizerOptions
  109997. */
  109998. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  109999. if (priority === void 0) { priority = 0; }
  110000. var optimization = new CustomOptimization(priority);
  110001. optimization.onApply = onApply;
  110002. optimization.onGetDescription = onGetDescription;
  110003. this.optimizations.push(optimization);
  110004. return this;
  110005. };
  110006. /**
  110007. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  110008. * @param targetFrameRate defines the target frame rate (60 by default)
  110009. * @returns a SceneOptimizerOptions object
  110010. */
  110011. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  110012. var result = new SceneOptimizerOptions(targetFrameRate);
  110013. var priority = 0;
  110014. result.addOptimization(new MergeMeshesOptimization(priority));
  110015. result.addOptimization(new ShadowsOptimization(priority));
  110016. result.addOptimization(new LensFlaresOptimization(priority));
  110017. // Next priority
  110018. priority++;
  110019. result.addOptimization(new PostProcessesOptimization(priority));
  110020. result.addOptimization(new ParticlesOptimization(priority));
  110021. // Next priority
  110022. priority++;
  110023. result.addOptimization(new TextureOptimization(priority, 1024));
  110024. return result;
  110025. };
  110026. /**
  110027. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  110028. * @param targetFrameRate defines the target frame rate (60 by default)
  110029. * @returns a SceneOptimizerOptions object
  110030. */
  110031. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  110032. var result = new SceneOptimizerOptions(targetFrameRate);
  110033. var priority = 0;
  110034. result.addOptimization(new MergeMeshesOptimization(priority));
  110035. result.addOptimization(new ShadowsOptimization(priority));
  110036. result.addOptimization(new LensFlaresOptimization(priority));
  110037. // Next priority
  110038. priority++;
  110039. result.addOptimization(new PostProcessesOptimization(priority));
  110040. result.addOptimization(new ParticlesOptimization(priority));
  110041. // Next priority
  110042. priority++;
  110043. result.addOptimization(new TextureOptimization(priority, 512));
  110044. // Next priority
  110045. priority++;
  110046. result.addOptimization(new RenderTargetsOptimization(priority));
  110047. // Next priority
  110048. priority++;
  110049. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  110050. return result;
  110051. };
  110052. /**
  110053. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  110054. * @param targetFrameRate defines the target frame rate (60 by default)
  110055. * @returns a SceneOptimizerOptions object
  110056. */
  110057. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  110058. var result = new SceneOptimizerOptions(targetFrameRate);
  110059. var priority = 0;
  110060. result.addOptimization(new MergeMeshesOptimization(priority));
  110061. result.addOptimization(new ShadowsOptimization(priority));
  110062. result.addOptimization(new LensFlaresOptimization(priority));
  110063. // Next priority
  110064. priority++;
  110065. result.addOptimization(new PostProcessesOptimization(priority));
  110066. result.addOptimization(new ParticlesOptimization(priority));
  110067. // Next priority
  110068. priority++;
  110069. result.addOptimization(new TextureOptimization(priority, 256));
  110070. // Next priority
  110071. priority++;
  110072. result.addOptimization(new RenderTargetsOptimization(priority));
  110073. // Next priority
  110074. priority++;
  110075. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  110076. return result;
  110077. };
  110078. return SceneOptimizerOptions;
  110079. }());
  110080. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  110081. /**
  110082. * Class used to run optimizations in order to reach a target frame rate
  110083. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110084. */
  110085. var SceneOptimizer = /** @class */ (function () {
  110086. /**
  110087. * Creates a new SceneOptimizer
  110088. * @param scene defines the scene to work on
  110089. * @param options defines the options to use with the SceneOptimizer
  110090. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  110091. * @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)
  110092. */
  110093. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  110094. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  110095. if (improvementMode === void 0) { improvementMode = false; }
  110096. var _this = this;
  110097. this._isRunning = false;
  110098. this._currentPriorityLevel = 0;
  110099. this._targetFrameRate = 60;
  110100. this._trackerDuration = 2000;
  110101. this._currentFrameRate = 0;
  110102. this._improvementMode = false;
  110103. /**
  110104. * Defines an observable called when the optimizer reaches the target frame rate
  110105. */
  110106. this.onSuccessObservable = new BABYLON.Observable();
  110107. /**
  110108. * Defines an observable called when the optimizer enables an optimization
  110109. */
  110110. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  110111. /**
  110112. * Defines an observable called when the optimizer is not able to reach the target frame rate
  110113. */
  110114. this.onFailureObservable = new BABYLON.Observable();
  110115. if (!options) {
  110116. this._options = new SceneOptimizerOptions();
  110117. }
  110118. else {
  110119. this._options = options;
  110120. }
  110121. if (this._options.targetFrameRate) {
  110122. this._targetFrameRate = this._options.targetFrameRate;
  110123. }
  110124. if (this._options.trackerDuration) {
  110125. this._trackerDuration = this._options.trackerDuration;
  110126. }
  110127. if (autoGeneratePriorities) {
  110128. var priority = 0;
  110129. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  110130. var optim = _a[_i];
  110131. optim.priority = priority++;
  110132. }
  110133. }
  110134. this._improvementMode = improvementMode;
  110135. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  110136. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  110137. _this._sceneDisposeObserver = null;
  110138. _this.dispose();
  110139. });
  110140. }
  110141. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  110142. /**
  110143. * Gets a boolean indicating if the optimizer is in improvement mode
  110144. */
  110145. get: function () {
  110146. return this._improvementMode;
  110147. },
  110148. enumerable: true,
  110149. configurable: true
  110150. });
  110151. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  110152. /**
  110153. * Gets the current priority level (0 at start)
  110154. */
  110155. get: function () {
  110156. return this._currentPriorityLevel;
  110157. },
  110158. enumerable: true,
  110159. configurable: true
  110160. });
  110161. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  110162. /**
  110163. * Gets the current frame rate checked by the SceneOptimizer
  110164. */
  110165. get: function () {
  110166. return this._currentFrameRate;
  110167. },
  110168. enumerable: true,
  110169. configurable: true
  110170. });
  110171. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  110172. /**
  110173. * Gets or sets the current target frame rate (60 by default)
  110174. */
  110175. get: function () {
  110176. return this._targetFrameRate;
  110177. },
  110178. /**
  110179. * Gets or sets the current target frame rate (60 by default)
  110180. */
  110181. set: function (value) {
  110182. this._targetFrameRate = value;
  110183. },
  110184. enumerable: true,
  110185. configurable: true
  110186. });
  110187. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  110188. /**
  110189. * Gets or sets the current interval between two checks (every 2000ms by default)
  110190. */
  110191. get: function () {
  110192. return this._trackerDuration;
  110193. },
  110194. /**
  110195. * Gets or sets the current interval between two checks (every 2000ms by default)
  110196. */
  110197. set: function (value) {
  110198. this._trackerDuration = value;
  110199. },
  110200. enumerable: true,
  110201. configurable: true
  110202. });
  110203. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  110204. /**
  110205. * Gets the list of active optimizations
  110206. */
  110207. get: function () {
  110208. return this._options.optimizations;
  110209. },
  110210. enumerable: true,
  110211. configurable: true
  110212. });
  110213. /**
  110214. * Stops the current optimizer
  110215. */
  110216. SceneOptimizer.prototype.stop = function () {
  110217. this._isRunning = false;
  110218. };
  110219. /**
  110220. * Reset the optimizer to initial step (current priority level = 0)
  110221. */
  110222. SceneOptimizer.prototype.reset = function () {
  110223. this._currentPriorityLevel = 0;
  110224. };
  110225. /**
  110226. * Start the optimizer. By default it will try to reach a specific framerate
  110227. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  110228. */
  110229. SceneOptimizer.prototype.start = function () {
  110230. var _this = this;
  110231. if (this._isRunning) {
  110232. return;
  110233. }
  110234. this._isRunning = true;
  110235. // Let's wait for the scene to be ready before running our check
  110236. this._scene.executeWhenReady(function () {
  110237. setTimeout(function () {
  110238. _this._checkCurrentState();
  110239. }, _this._trackerDuration);
  110240. });
  110241. };
  110242. SceneOptimizer.prototype._checkCurrentState = function () {
  110243. var _this = this;
  110244. if (!this._isRunning) {
  110245. return;
  110246. }
  110247. var scene = this._scene;
  110248. var options = this._options;
  110249. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  110250. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  110251. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  110252. this._isRunning = false;
  110253. this.onSuccessObservable.notifyObservers(this);
  110254. return;
  110255. }
  110256. // Apply current level of optimizations
  110257. var allDone = true;
  110258. var noOptimizationApplied = true;
  110259. for (var index = 0; index < options.optimizations.length; index++) {
  110260. var optimization = options.optimizations[index];
  110261. if (optimization.priority === this._currentPriorityLevel) {
  110262. noOptimizationApplied = false;
  110263. allDone = allDone && optimization.apply(scene, this);
  110264. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  110265. }
  110266. }
  110267. // If no optimization was applied, this is a failure :(
  110268. if (noOptimizationApplied) {
  110269. this._isRunning = false;
  110270. this.onFailureObservable.notifyObservers(this);
  110271. return;
  110272. }
  110273. // If all optimizations were done, move to next level
  110274. if (allDone) {
  110275. this._currentPriorityLevel++;
  110276. }
  110277. // Let's the system running for a specific amount of time before checking FPS
  110278. scene.executeWhenReady(function () {
  110279. setTimeout(function () {
  110280. _this._checkCurrentState();
  110281. }, _this._trackerDuration);
  110282. });
  110283. };
  110284. /**
  110285. * Release all resources
  110286. */
  110287. SceneOptimizer.prototype.dispose = function () {
  110288. this.stop();
  110289. this.onSuccessObservable.clear();
  110290. this.onFailureObservable.clear();
  110291. this.onNewOptimizationAppliedObservable.clear();
  110292. if (this._sceneDisposeObserver) {
  110293. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  110294. }
  110295. };
  110296. /**
  110297. * Helper function to create a SceneOptimizer with one single line of code
  110298. * @param scene defines the scene to work on
  110299. * @param options defines the options to use with the SceneOptimizer
  110300. * @param onSuccess defines a callback to call on success
  110301. * @param onFailure defines a callback to call on failure
  110302. * @returns the new SceneOptimizer object
  110303. */
  110304. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  110305. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  110306. if (onSuccess) {
  110307. optimizer.onSuccessObservable.add(function () {
  110308. onSuccess();
  110309. });
  110310. }
  110311. if (onFailure) {
  110312. optimizer.onFailureObservable.add(function () {
  110313. onFailure();
  110314. });
  110315. }
  110316. optimizer.start();
  110317. return optimizer;
  110318. };
  110319. return SceneOptimizer;
  110320. }());
  110321. BABYLON.SceneOptimizer = SceneOptimizer;
  110322. })(BABYLON || (BABYLON = {}));
  110323. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  110324. var BABYLON;
  110325. (function (BABYLON) {
  110326. /**
  110327. * Gets the outline renderer associated with the scene
  110328. * @returns a OutlineRenderer
  110329. */
  110330. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  110331. if (!this._outlineRenderer) {
  110332. this._outlineRenderer = new OutlineRenderer(this);
  110333. }
  110334. return this._outlineRenderer;
  110335. };
  110336. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  110337. get: function () {
  110338. return this._renderOutline;
  110339. },
  110340. set: function (value) {
  110341. if (value) {
  110342. // Lazy Load the component.
  110343. this.getScene().getOutlineRenderer();
  110344. }
  110345. this._renderOutline = value;
  110346. },
  110347. enumerable: true,
  110348. configurable: true
  110349. });
  110350. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  110351. get: function () {
  110352. return this._renderOverlay;
  110353. },
  110354. set: function (value) {
  110355. if (value) {
  110356. // Lazy Load the component.
  110357. this.getScene().getOutlineRenderer();
  110358. }
  110359. this._renderOverlay = value;
  110360. },
  110361. enumerable: true,
  110362. configurable: true
  110363. });
  110364. /**
  110365. * This class is responsible to draw bothe outline/overlay of meshes.
  110366. * It should not be used directly but through the available method on mesh.
  110367. */
  110368. var OutlineRenderer = /** @class */ (function () {
  110369. /**
  110370. * Instantiates a new outline renderer. (There could be only one per scene).
  110371. * @param scene Defines the scene it belongs to
  110372. */
  110373. function OutlineRenderer(scene) {
  110374. /**
  110375. * The name of the component. Each component must have a unique name.
  110376. */
  110377. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  110378. /**
  110379. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  110380. */
  110381. this.zOffset = 1;
  110382. this.scene = scene;
  110383. this._engine = scene.getEngine();
  110384. this.scene._addComponent(this);
  110385. }
  110386. /**
  110387. * Register the component to one instance of a scene.
  110388. */
  110389. OutlineRenderer.prototype.register = function () {
  110390. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  110391. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  110392. };
  110393. /**
  110394. * Rebuilds the elements related to this component in case of
  110395. * context lost for instance.
  110396. */
  110397. OutlineRenderer.prototype.rebuild = function () {
  110398. // Nothing to do here.
  110399. };
  110400. /**
  110401. * Disposes the component and the associated ressources.
  110402. */
  110403. OutlineRenderer.prototype.dispose = function () {
  110404. // Nothing to do here.
  110405. };
  110406. /**
  110407. * Renders the outline in the canvas.
  110408. * @param subMesh Defines the sumesh to render
  110409. * @param batch Defines the batch of meshes in case of instances
  110410. * @param useOverlay Defines if the rendering is for the overlay or the outline
  110411. */
  110412. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  110413. var _this = this;
  110414. if (useOverlay === void 0) { useOverlay = false; }
  110415. var scene = this.scene;
  110416. var engine = scene.getEngine();
  110417. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  110418. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  110419. return;
  110420. }
  110421. var mesh = subMesh.getRenderingMesh();
  110422. var material = subMesh.getMaterial();
  110423. if (!material || !scene.activeCamera) {
  110424. return;
  110425. }
  110426. engine.enableEffect(this._effect);
  110427. // Logarithmic depth
  110428. if (material.useLogarithmicDepth) {
  110429. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  110430. }
  110431. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  110432. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  110433. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  110434. // Bones
  110435. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  110436. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  110437. }
  110438. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  110439. // Alpha test
  110440. if (material && material.needAlphaTesting()) {
  110441. var alphaTexture = material.getAlphaTestTexture();
  110442. if (alphaTexture) {
  110443. this._effect.setTexture("diffuseSampler", alphaTexture);
  110444. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  110445. }
  110446. }
  110447. engine.setZOffset(-this.zOffset);
  110448. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  110449. engine.setZOffset(0);
  110450. };
  110451. /**
  110452. * Returns whether or not the outline renderer is ready for a given submesh.
  110453. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  110454. * @param subMesh Defines the submesh to check readyness for
  110455. * @param useInstances Defines wheter wee are trying to render instances or not
  110456. * @returns true if ready otherwise false
  110457. */
  110458. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  110459. var defines = [];
  110460. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  110461. var mesh = subMesh.getMesh();
  110462. var material = subMesh.getMaterial();
  110463. if (material) {
  110464. // Alpha test
  110465. if (material.needAlphaTesting()) {
  110466. defines.push("#define ALPHATEST");
  110467. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110468. attribs.push(BABYLON.VertexBuffer.UVKind);
  110469. defines.push("#define UV1");
  110470. }
  110471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  110472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110473. defines.push("#define UV2");
  110474. }
  110475. }
  110476. //Logarithmic depth
  110477. if (material.useLogarithmicDepth) {
  110478. defines.push("#define LOGARITHMICDEPTH");
  110479. }
  110480. }
  110481. // Bones
  110482. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  110483. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  110484. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  110485. if (mesh.numBoneInfluencers > 4) {
  110486. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  110487. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  110488. }
  110489. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  110490. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  110491. }
  110492. else {
  110493. defines.push("#define NUM_BONE_INFLUENCERS 0");
  110494. }
  110495. // Instances
  110496. if (useInstances) {
  110497. defines.push("#define INSTANCES");
  110498. attribs.push("world0");
  110499. attribs.push("world1");
  110500. attribs.push("world2");
  110501. attribs.push("world3");
  110502. }
  110503. // Get correct effect
  110504. var join = defines.join("\n");
  110505. if (this._cachedDefines !== join) {
  110506. this._cachedDefines = join;
  110507. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  110508. }
  110509. return this._effect.isReady();
  110510. };
  110511. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  110512. // Outline - step 1
  110513. this._savedDepthWrite = this._engine.getDepthWrite();
  110514. if (mesh.renderOutline) {
  110515. this._engine.setDepthWrite(false);
  110516. this.render(subMesh, batch);
  110517. this._engine.setDepthWrite(this._savedDepthWrite);
  110518. }
  110519. };
  110520. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  110521. // Outline - step 2
  110522. if (mesh.renderOutline && this._savedDepthWrite) {
  110523. this._engine.setDepthWrite(true);
  110524. this._engine.setColorWrite(false);
  110525. this.render(subMesh, batch);
  110526. this._engine.setColorWrite(true);
  110527. }
  110528. // Overlay
  110529. if (mesh.renderOverlay) {
  110530. var currentMode = this._engine.getAlphaMode();
  110531. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110532. this.render(subMesh, batch, true);
  110533. this._engine.setAlphaMode(currentMode);
  110534. }
  110535. };
  110536. return OutlineRenderer;
  110537. }());
  110538. BABYLON.OutlineRenderer = OutlineRenderer;
  110539. })(BABYLON || (BABYLON = {}));
  110540. //# sourceMappingURL=babylon.outlineRenderer.js.map
  110541. var BABYLON;
  110542. (function (BABYLON) {
  110543. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  110544. if (this._edgesRenderer) {
  110545. this._edgesRenderer.dispose();
  110546. this._edgesRenderer = null;
  110547. }
  110548. return this;
  110549. };
  110550. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110551. if (epsilon === void 0) { epsilon = 0.95; }
  110552. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110553. this.disableEdgesRendering();
  110554. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110555. return this;
  110556. };
  110557. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  110558. get: function () {
  110559. return this._edgesRenderer;
  110560. },
  110561. enumerable: true,
  110562. configurable: true
  110563. });
  110564. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110565. if (epsilon === void 0) { epsilon = 0.95; }
  110566. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110567. this.disableEdgesRendering();
  110568. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110569. return this;
  110570. };
  110571. BABYLON.InstancedMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110572. if (epsilon === void 0) { epsilon = 0.95; }
  110573. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110574. if (this.sourceMesh.getClassName() === 'LinesMesh') {
  110575. BABYLON.LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);
  110576. }
  110577. else {
  110578. BABYLON.AbstractMesh.prototype.enableEdgesRendering.apply(this, arguments);
  110579. }
  110580. return this;
  110581. };
  110582. /**
  110583. * FaceAdjacencies Helper class to generate edges
  110584. */
  110585. var FaceAdjacencies = /** @class */ (function () {
  110586. function FaceAdjacencies() {
  110587. this.edges = new Array();
  110588. this.edgesConnectedCount = 0;
  110589. }
  110590. return FaceAdjacencies;
  110591. }());
  110592. /**
  110593. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  110594. */
  110595. var EdgesRenderer = /** @class */ (function () {
  110596. /**
  110597. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  110598. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  110599. * @param source Mesh used to create edges
  110600. * @param epsilon sum of angles in adjacency to check for edge
  110601. * @param checkVerticesInsteadOfIndices
  110602. * @param generateEdgesLines - should generate Lines or only prepare resources.
  110603. */
  110604. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  110605. if (epsilon === void 0) { epsilon = 0.95; }
  110606. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110607. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  110608. var _this = this;
  110609. /**
  110610. * Define the size of the edges with an orthographic camera
  110611. */
  110612. this.edgesWidthScalerForOrthographic = 1000.0;
  110613. /**
  110614. * Define the size of the edges with a perspective camera
  110615. */
  110616. this.edgesWidthScalerForPerspective = 50.0;
  110617. this._linesPositions = new Array();
  110618. this._linesNormals = new Array();
  110619. this._linesIndices = new Array();
  110620. this._buffers = {};
  110621. this._checkVerticesInsteadOfIndices = false;
  110622. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  110623. this.isEnabled = true;
  110624. this._source = source;
  110625. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  110626. this._epsilon = epsilon;
  110627. this._prepareRessources();
  110628. if (generateEdgesLines) {
  110629. this._generateEdgesLines();
  110630. }
  110631. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  110632. _this._rebuild();
  110633. });
  110634. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  110635. _this.dispose();
  110636. });
  110637. }
  110638. EdgesRenderer.prototype._prepareRessources = function () {
  110639. if (this._lineShader) {
  110640. return;
  110641. }
  110642. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  110643. attributes: ["position", "normal"],
  110644. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  110645. });
  110646. this._lineShader.disableDepthWrite = true;
  110647. this._lineShader.backFaceCulling = false;
  110648. };
  110649. /** @hidden */
  110650. EdgesRenderer.prototype._rebuild = function () {
  110651. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110652. if (buffer) {
  110653. buffer._rebuild();
  110654. }
  110655. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110656. if (buffer) {
  110657. buffer._rebuild();
  110658. }
  110659. var scene = this._source.getScene();
  110660. var engine = scene.getEngine();
  110661. this._ib = engine.createIndexBuffer(this._linesIndices);
  110662. };
  110663. /**
  110664. * Releases the required resources for the edges renderer
  110665. */
  110666. EdgesRenderer.prototype.dispose = function () {
  110667. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  110668. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  110669. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110670. if (buffer) {
  110671. buffer.dispose();
  110672. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  110673. }
  110674. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110675. if (buffer) {
  110676. buffer.dispose();
  110677. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  110678. }
  110679. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  110680. this._lineShader.dispose();
  110681. };
  110682. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  110683. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  110684. return 0;
  110685. }
  110686. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  110687. return 1;
  110688. }
  110689. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  110690. return 2;
  110691. }
  110692. return -1;
  110693. };
  110694. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  110695. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  110696. return 0;
  110697. }
  110698. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  110699. return 1;
  110700. }
  110701. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  110702. return 2;
  110703. }
  110704. return -1;
  110705. };
  110706. /**
  110707. * Checks if the pair of p0 and p1 is en edge
  110708. * @param faceIndex
  110709. * @param edge
  110710. * @param faceNormals
  110711. * @param p0
  110712. * @param p1
  110713. * @private
  110714. */
  110715. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  110716. var needToCreateLine;
  110717. if (edge === undefined) {
  110718. needToCreateLine = true;
  110719. }
  110720. else {
  110721. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  110722. needToCreateLine = dotProduct < this._epsilon;
  110723. }
  110724. if (needToCreateLine) {
  110725. this.createLine(p0, p1, this._linesPositions.length / 3);
  110726. }
  110727. };
  110728. /**
  110729. * push line into the position, normal and index buffer
  110730. * @protected
  110731. */
  110732. EdgesRenderer.prototype.createLine = function (p0, p1, offset) {
  110733. // Positions
  110734. this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);
  110735. // Normals
  110736. this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);
  110737. // Indices
  110738. this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);
  110739. };
  110740. /**
  110741. * Generates lines edges from adjacencjes
  110742. * @private
  110743. */
  110744. EdgesRenderer.prototype._generateEdgesLines = function () {
  110745. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110746. var indices = this._source.getIndices();
  110747. if (!indices || !positions) {
  110748. return;
  110749. }
  110750. // First let's find adjacencies
  110751. var adjacencies = new Array();
  110752. var faceNormals = new Array();
  110753. var index;
  110754. var faceAdjacencies;
  110755. // Prepare faces
  110756. for (index = 0; index < indices.length; index += 3) {
  110757. faceAdjacencies = new FaceAdjacencies();
  110758. var p0Index = indices[index];
  110759. var p1Index = indices[index + 1];
  110760. var p2Index = indices[index + 2];
  110761. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  110762. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  110763. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  110764. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  110765. faceNormal.normalize();
  110766. faceNormals.push(faceNormal);
  110767. adjacencies.push(faceAdjacencies);
  110768. }
  110769. // Scan
  110770. for (index = 0; index < adjacencies.length; index++) {
  110771. faceAdjacencies = adjacencies[index];
  110772. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  110773. var otherFaceAdjacencies = adjacencies[otherIndex];
  110774. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  110775. break;
  110776. }
  110777. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  110778. continue;
  110779. }
  110780. var otherP0 = indices[otherIndex * 3];
  110781. var otherP1 = indices[otherIndex * 3 + 1];
  110782. var otherP2 = indices[otherIndex * 3 + 2];
  110783. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  110784. var otherEdgeIndex = 0;
  110785. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  110786. continue;
  110787. }
  110788. switch (edgeIndex) {
  110789. case 0:
  110790. if (this._checkVerticesInsteadOfIndices) {
  110791. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110792. }
  110793. else {
  110794. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  110795. }
  110796. break;
  110797. case 1:
  110798. if (this._checkVerticesInsteadOfIndices) {
  110799. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110800. }
  110801. else {
  110802. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  110803. }
  110804. break;
  110805. case 2:
  110806. if (this._checkVerticesInsteadOfIndices) {
  110807. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110808. }
  110809. else {
  110810. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  110811. }
  110812. break;
  110813. }
  110814. if (otherEdgeIndex === -1) {
  110815. continue;
  110816. }
  110817. faceAdjacencies.edges[edgeIndex] = otherIndex;
  110818. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  110819. faceAdjacencies.edgesConnectedCount++;
  110820. otherFaceAdjacencies.edgesConnectedCount++;
  110821. if (faceAdjacencies.edgesConnectedCount === 3) {
  110822. break;
  110823. }
  110824. }
  110825. }
  110826. }
  110827. // Create lines
  110828. for (index = 0; index < adjacencies.length; index++) {
  110829. // 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
  110830. var current = adjacencies[index];
  110831. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110832. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  110833. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  110834. }
  110835. // Merge into a single mesh
  110836. var engine = this._source.getScene().getEngine();
  110837. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110838. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110839. this._ib = engine.createIndexBuffer(this._linesIndices);
  110840. this._indicesCount = this._linesIndices.length;
  110841. };
  110842. /**
  110843. * Checks wether or not the edges renderer is ready to render.
  110844. * @return true if ready, otherwise false.
  110845. */
  110846. EdgesRenderer.prototype.isReady = function () {
  110847. return this._lineShader.isReady();
  110848. };
  110849. /**
  110850. * Renders the edges of the attached mesh,
  110851. */
  110852. EdgesRenderer.prototype.render = function () {
  110853. var scene = this._source.getScene();
  110854. if (!this.isReady() || !scene.activeCamera) {
  110855. return;
  110856. }
  110857. var engine = scene.getEngine();
  110858. this._lineShader._preBind();
  110859. if (this._source.edgesColor.a !== 1) {
  110860. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110861. }
  110862. else {
  110863. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110864. }
  110865. // VBOs
  110866. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  110867. scene.resetCachedMaterial();
  110868. this._lineShader.setColor4("color", this._source.edgesColor);
  110869. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  110870. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  110871. }
  110872. else {
  110873. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  110874. }
  110875. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  110876. this._lineShader.bind(this._source.getWorldMatrix());
  110877. // Draw order
  110878. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  110879. this._lineShader.unbind();
  110880. };
  110881. return EdgesRenderer;
  110882. }());
  110883. BABYLON.EdgesRenderer = EdgesRenderer;
  110884. })(BABYLON || (BABYLON = {}));
  110885. //# sourceMappingURL=babylon.edgesRenderer.js.map
  110886. var BABYLON;
  110887. (function (BABYLON) {
  110888. /**
  110889. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  110890. */
  110891. var LineEdgesRenderer = /** @class */ (function (_super) {
  110892. __extends(LineEdgesRenderer, _super);
  110893. /**
  110894. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  110895. * @param source LineMesh used to generate edges
  110896. * @param epsilon not important (specified angle for edge detection)
  110897. * @param checkVerticesInsteadOfIndices not important for LineMesh
  110898. */
  110899. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  110900. if (epsilon === void 0) { epsilon = 0.95; }
  110901. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110902. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  110903. _this._generateEdgesLines();
  110904. return _this;
  110905. }
  110906. /**
  110907. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  110908. */
  110909. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  110910. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110911. var indices = this._source.getIndices();
  110912. if (!indices || !positions) {
  110913. return;
  110914. }
  110915. var p0 = BABYLON.Tmp.Vector3[0];
  110916. var p1 = BABYLON.Tmp.Vector3[1];
  110917. var len = indices.length - 1;
  110918. for (var i = 0, offset = 0; i < len; i += 2, offset += 4) {
  110919. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i], p0);
  110920. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);
  110921. this.createLine(p0, p1, offset);
  110922. }
  110923. // Merge into a single mesh
  110924. var engine = this._source.getScene().getEngine();
  110925. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110926. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110927. this._ib = engine.createIndexBuffer(this._linesIndices);
  110928. this._indicesCount = this._linesIndices.length;
  110929. };
  110930. return LineEdgesRenderer;
  110931. }(BABYLON.EdgesRenderer));
  110932. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  110933. })(BABYLON || (BABYLON = {}));
  110934. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  110935. var BABYLON;
  110936. (function (BABYLON) {
  110937. // Adds the parser to the scene parsers.
  110938. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  110939. if (parsedData.effectLayers) {
  110940. if (!container.effectLayers) {
  110941. container.effectLayers = new Array();
  110942. }
  110943. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  110944. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  110945. container.effectLayers.push(effectLayer);
  110946. }
  110947. }
  110948. });
  110949. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  110950. var index = this.effectLayers.indexOf(toRemove);
  110951. if (index !== -1) {
  110952. this.effectLayers.splice(index, 1);
  110953. }
  110954. return index;
  110955. };
  110956. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  110957. this.effectLayers.push(newEffectLayer);
  110958. };
  110959. /**
  110960. * Defines the layer scene component responsible to manage any effect layers
  110961. * in a given scene.
  110962. */
  110963. var EffectLayerSceneComponent = /** @class */ (function () {
  110964. /**
  110965. * Creates a new instance of the component for the given scene
  110966. * @param scene Defines the scene to register the component in
  110967. */
  110968. function EffectLayerSceneComponent(scene) {
  110969. /**
  110970. * The component name helpfull to identify the component in the list of scene components.
  110971. */
  110972. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  110973. this._renderEffects = false;
  110974. this._needStencil = false;
  110975. this._previousStencilState = false;
  110976. this.scene = scene;
  110977. this._engine = scene.getEngine();
  110978. scene.effectLayers = new Array();
  110979. }
  110980. /**
  110981. * Registers the component in a given scene
  110982. */
  110983. EffectLayerSceneComponent.prototype.register = function () {
  110984. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  110985. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  110986. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  110987. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  110988. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  110989. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  110990. };
  110991. /**
  110992. * Rebuilds the elements related to this component in case of
  110993. * context lost for instance.
  110994. */
  110995. EffectLayerSceneComponent.prototype.rebuild = function () {
  110996. var layers = this.scene.effectLayers;
  110997. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110998. var effectLayer = layers_1[_i];
  110999. effectLayer._rebuild();
  111000. }
  111001. };
  111002. /**
  111003. * Serializes the component data to the specified json object
  111004. * @param serializationObject The object to serialize to
  111005. */
  111006. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  111007. // Effect layers
  111008. serializationObject.effectLayers = [];
  111009. var layers = this.scene.effectLayers;
  111010. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111011. var effectLayer = layers_2[_i];
  111012. if (effectLayer.serialize) {
  111013. serializationObject.effectLayers.push(effectLayer.serialize());
  111014. }
  111015. }
  111016. };
  111017. /**
  111018. * Adds all the element from the container to the scene
  111019. * @param container the container holding the elements
  111020. */
  111021. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  111022. var _this = this;
  111023. if (!container.effectLayers) {
  111024. return;
  111025. }
  111026. container.effectLayers.forEach(function (o) {
  111027. _this.scene.addEffectLayer(o);
  111028. });
  111029. };
  111030. /**
  111031. * Removes all the elements in the container from the scene
  111032. * @param container contains the elements to remove
  111033. */
  111034. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  111035. var _this = this;
  111036. if (!container.effectLayers) {
  111037. return;
  111038. }
  111039. container.effectLayers.forEach(function (o) {
  111040. _this.scene.removeEffectLayer(o);
  111041. });
  111042. };
  111043. /**
  111044. * Disposes the component and the associated ressources.
  111045. */
  111046. EffectLayerSceneComponent.prototype.dispose = function () {
  111047. var layers = this.scene.effectLayers;
  111048. while (layers.length) {
  111049. layers[0].dispose();
  111050. }
  111051. };
  111052. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  111053. var layers = this.scene.effectLayers;
  111054. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  111055. var layer = layers_3[_i];
  111056. if (!layer.hasMesh(mesh)) {
  111057. continue;
  111058. }
  111059. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  111060. var subMesh = _b[_a];
  111061. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  111062. return false;
  111063. }
  111064. }
  111065. }
  111066. return true;
  111067. };
  111068. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  111069. this._renderEffects = false;
  111070. this._needStencil = false;
  111071. var layers = this.scene.effectLayers;
  111072. if (layers && layers.length > 0) {
  111073. this._previousStencilState = this._engine.getStencilBuffer();
  111074. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  111075. var effectLayer = layers_4[_i];
  111076. if (effectLayer.shouldRender() &&
  111077. (!effectLayer.camera ||
  111078. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  111079. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  111080. this._renderEffects = true;
  111081. this._needStencil = this._needStencil || effectLayer.needStencil();
  111082. var renderTarget = effectLayer._mainTexture;
  111083. if (renderTarget._shouldRender()) {
  111084. this.scene.incrementRenderId();
  111085. renderTarget.render(false, false);
  111086. }
  111087. }
  111088. }
  111089. this.scene.incrementRenderId();
  111090. }
  111091. };
  111092. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  111093. // Activate effect Layer stencil
  111094. if (this._needStencil) {
  111095. this._engine.setStencilBuffer(true);
  111096. }
  111097. };
  111098. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  111099. // Restore effect Layer stencil
  111100. if (this._needStencil) {
  111101. this._engine.setStencilBuffer(this._previousStencilState);
  111102. }
  111103. };
  111104. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  111105. if (this._renderEffects) {
  111106. this._engine.setDepthBuffer(false);
  111107. var layers = this.scene.effectLayers;
  111108. for (var i = 0; i < layers.length; i++) {
  111109. var effectLayer = layers[i];
  111110. if (effectLayer.renderingGroupId === renderingGroupId) {
  111111. if (effectLayer.shouldRender()) {
  111112. effectLayer.render();
  111113. }
  111114. }
  111115. }
  111116. this._engine.setDepthBuffer(true);
  111117. }
  111118. };
  111119. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  111120. if (this._renderEffects) {
  111121. this._draw(-1);
  111122. }
  111123. };
  111124. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  111125. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  111126. this._draw(index);
  111127. }
  111128. };
  111129. return EffectLayerSceneComponent;
  111130. }());
  111131. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  111132. })(BABYLON || (BABYLON = {}));
  111133. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  111134. var __assign = (this && this.__assign) || function () {
  111135. __assign = Object.assign || function(t) {
  111136. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111137. s = arguments[i];
  111138. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111139. t[p] = s[p];
  111140. }
  111141. return t;
  111142. };
  111143. return __assign.apply(this, arguments);
  111144. };
  111145. var BABYLON;
  111146. (function (BABYLON) {
  111147. /**
  111148. * The effect layer Helps adding post process effect blended with the main pass.
  111149. *
  111150. * This can be for instance use to generate glow or higlight effects on the scene.
  111151. *
  111152. * The effect layer class can not be used directly and is intented to inherited from to be
  111153. * customized per effects.
  111154. */
  111155. var EffectLayer = /** @class */ (function () {
  111156. /**
  111157. * Instantiates a new effect Layer and references it in the scene.
  111158. * @param name The name of the layer
  111159. * @param scene The scene to use the layer in
  111160. */
  111161. function EffectLayer(
  111162. /** The Friendly of the effect in the scene */
  111163. name, scene) {
  111164. this._vertexBuffers = {};
  111165. this._maxSize = 0;
  111166. this._mainTextureDesiredSize = { width: 0, height: 0 };
  111167. this._shouldRender = true;
  111168. this._postProcesses = [];
  111169. this._textures = [];
  111170. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  111171. /**
  111172. * The clear color of the texture used to generate the glow map.
  111173. */
  111174. this.neutralColor = new BABYLON.Color4();
  111175. /**
  111176. * Specifies wether the highlight layer is enabled or not.
  111177. */
  111178. this.isEnabled = true;
  111179. /**
  111180. * An event triggered when the effect layer has been disposed.
  111181. */
  111182. this.onDisposeObservable = new BABYLON.Observable();
  111183. /**
  111184. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  111185. */
  111186. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  111187. /**
  111188. * An event triggered when the generated texture is being merged in the scene.
  111189. */
  111190. this.onBeforeComposeObservable = new BABYLON.Observable();
  111191. /**
  111192. * An event triggered when the generated texture has been merged in the scene.
  111193. */
  111194. this.onAfterComposeObservable = new BABYLON.Observable();
  111195. /**
  111196. * An event triggered when the efffect layer changes its size.
  111197. */
  111198. this.onSizeChangedObservable = new BABYLON.Observable();
  111199. this.name = name;
  111200. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  111201. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  111202. if (!component) {
  111203. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  111204. this._scene._addComponent(component);
  111205. }
  111206. this._engine = this._scene.getEngine();
  111207. this._maxSize = this._engine.getCaps().maxTextureSize;
  111208. this._scene.effectLayers.push(this);
  111209. // Generate Buffers
  111210. this._generateIndexBuffer();
  111211. this._genrateVertexBuffer();
  111212. }
  111213. Object.defineProperty(EffectLayer.prototype, "camera", {
  111214. /**
  111215. * Gets the camera attached to the layer.
  111216. */
  111217. get: function () {
  111218. return this._effectLayerOptions.camera;
  111219. },
  111220. enumerable: true,
  111221. configurable: true
  111222. });
  111223. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  111224. /**
  111225. * Gets the rendering group id the layer should render in.
  111226. */
  111227. get: function () {
  111228. return this._effectLayerOptions.renderingGroupId;
  111229. },
  111230. enumerable: true,
  111231. configurable: true
  111232. });
  111233. /**
  111234. * Initializes the effect layer with the required options.
  111235. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  111236. */
  111237. EffectLayer.prototype._init = function (options) {
  111238. // Adapt options
  111239. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  111240. this._setMainTextureSize();
  111241. this._createMainTexture();
  111242. this._createTextureAndPostProcesses();
  111243. this._mergeEffect = this._createMergeEffect();
  111244. };
  111245. /**
  111246. * Generates the index buffer of the full screen quad blending to the main canvas.
  111247. */
  111248. EffectLayer.prototype._generateIndexBuffer = function () {
  111249. // Indices
  111250. var indices = [];
  111251. indices.push(0);
  111252. indices.push(1);
  111253. indices.push(2);
  111254. indices.push(0);
  111255. indices.push(2);
  111256. indices.push(3);
  111257. this._indexBuffer = this._engine.createIndexBuffer(indices);
  111258. };
  111259. /**
  111260. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  111261. */
  111262. EffectLayer.prototype._genrateVertexBuffer = function () {
  111263. // VBO
  111264. var vertices = [];
  111265. vertices.push(1, 1);
  111266. vertices.push(-1, 1);
  111267. vertices.push(-1, -1);
  111268. vertices.push(1, -1);
  111269. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111271. };
  111272. /**
  111273. * Sets the main texture desired size which is the closest power of two
  111274. * of the engine canvas size.
  111275. */
  111276. EffectLayer.prototype._setMainTextureSize = function () {
  111277. if (this._effectLayerOptions.mainTextureFixedSize) {
  111278. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  111279. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  111280. }
  111281. else {
  111282. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  111283. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  111284. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  111285. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  111286. }
  111287. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  111288. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  111289. };
  111290. /**
  111291. * Creates the main texture for the effect layer.
  111292. */
  111293. EffectLayer.prototype._createMainTexture = function () {
  111294. var _this = this;
  111295. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  111296. width: this._mainTextureDesiredSize.width,
  111297. height: this._mainTextureDesiredSize.height
  111298. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111299. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  111300. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111301. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111302. this._mainTexture.anisotropicFilteringLevel = 1;
  111303. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111304. this._mainTexture.renderParticles = false;
  111305. this._mainTexture.renderList = null;
  111306. this._mainTexture.ignoreCameraViewport = true;
  111307. // Custom render function
  111308. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  111309. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  111310. var index;
  111311. var engine = _this._scene.getEngine();
  111312. if (depthOnlySubMeshes.length) {
  111313. engine.setColorWrite(false);
  111314. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  111315. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  111316. }
  111317. engine.setColorWrite(true);
  111318. }
  111319. for (index = 0; index < opaqueSubMeshes.length; index++) {
  111320. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  111321. }
  111322. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  111323. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  111324. }
  111325. for (index = 0; index < transparentSubMeshes.length; index++) {
  111326. _this._renderSubMesh(transparentSubMeshes.data[index]);
  111327. }
  111328. };
  111329. this._mainTexture.onClearObservable.add(function (engine) {
  111330. engine.clear(_this.neutralColor, true, true, true);
  111331. });
  111332. };
  111333. /**
  111334. * Checks for the readiness of the element composing the layer.
  111335. * @param subMesh the mesh to check for
  111336. * @param useInstances specify wether or not to use instances to render the mesh
  111337. * @param emissiveTexture the associated emissive texture used to generate the glow
  111338. * @return true if ready otherwise, false
  111339. */
  111340. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  111341. var material = subMesh.getMaterial();
  111342. if (!material) {
  111343. return false;
  111344. }
  111345. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  111346. return false;
  111347. }
  111348. var defines = [];
  111349. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111350. var mesh = subMesh.getMesh();
  111351. var uv1 = false;
  111352. var uv2 = false;
  111353. // Alpha test
  111354. if (material && material.needAlphaTesting()) {
  111355. var alphaTexture = material.getAlphaTestTexture();
  111356. if (alphaTexture) {
  111357. defines.push("#define ALPHATEST");
  111358. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  111359. alphaTexture.coordinatesIndex === 1) {
  111360. defines.push("#define DIFFUSEUV2");
  111361. uv2 = true;
  111362. }
  111363. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111364. defines.push("#define DIFFUSEUV1");
  111365. uv1 = true;
  111366. }
  111367. }
  111368. }
  111369. // Emissive
  111370. if (emissiveTexture) {
  111371. defines.push("#define EMISSIVE");
  111372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  111373. emissiveTexture.coordinatesIndex === 1) {
  111374. defines.push("#define EMISSIVEUV2");
  111375. uv2 = true;
  111376. }
  111377. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111378. defines.push("#define EMISSIVEUV1");
  111379. uv1 = true;
  111380. }
  111381. }
  111382. if (uv1) {
  111383. attribs.push(BABYLON.VertexBuffer.UVKind);
  111384. defines.push("#define UV1");
  111385. }
  111386. if (uv2) {
  111387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111388. defines.push("#define UV2");
  111389. }
  111390. // Bones
  111391. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  111392. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  111393. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  111394. if (mesh.numBoneInfluencers > 4) {
  111395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  111396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  111397. }
  111398. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  111399. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  111400. }
  111401. else {
  111402. defines.push("#define NUM_BONE_INFLUENCERS 0");
  111403. }
  111404. // Morph targets
  111405. var manager = mesh.morphTargetManager;
  111406. var morphInfluencers = 0;
  111407. if (manager) {
  111408. if (manager.numInfluencers > 0) {
  111409. defines.push("#define MORPHTARGETS");
  111410. morphInfluencers = manager.numInfluencers;
  111411. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  111412. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  111413. }
  111414. }
  111415. // Instances
  111416. if (useInstances) {
  111417. defines.push("#define INSTANCES");
  111418. attribs.push("world0");
  111419. attribs.push("world1");
  111420. attribs.push("world2");
  111421. attribs.push("world3");
  111422. }
  111423. // Get correct effect
  111424. var join = defines.join("\n");
  111425. if (this._cachedDefines !== join) {
  111426. this._cachedDefines = join;
  111427. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  111428. }
  111429. return this._effectLayerMapGenerationEffect.isReady();
  111430. };
  111431. /**
  111432. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  111433. */
  111434. EffectLayer.prototype.render = function () {
  111435. var currentEffect = this._mergeEffect;
  111436. // Check
  111437. if (!currentEffect.isReady()) {
  111438. return;
  111439. }
  111440. for (var i = 0; i < this._postProcesses.length; i++) {
  111441. if (!this._postProcesses[i].isReady()) {
  111442. return;
  111443. }
  111444. }
  111445. var engine = this._scene.getEngine();
  111446. this.onBeforeComposeObservable.notifyObservers(this);
  111447. // Render
  111448. engine.enableEffect(currentEffect);
  111449. engine.setState(false);
  111450. // VBOs
  111451. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111452. // Cache
  111453. var previousAlphaMode = engine.getAlphaMode();
  111454. // Go Blend.
  111455. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  111456. // Blends the map on the main canvas.
  111457. this._internalRender(currentEffect);
  111458. // Restore Alpha
  111459. engine.setAlphaMode(previousAlphaMode);
  111460. this.onAfterComposeObservable.notifyObservers(this);
  111461. // Handle size changes.
  111462. var size = this._mainTexture.getSize();
  111463. this._setMainTextureSize();
  111464. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  111465. // Recreate RTT and post processes on size change.
  111466. this.onSizeChangedObservable.notifyObservers(this);
  111467. this._disposeTextureAndPostProcesses();
  111468. this._createMainTexture();
  111469. this._createTextureAndPostProcesses();
  111470. }
  111471. };
  111472. /**
  111473. * Determine if a given mesh will be used in the current effect.
  111474. * @param mesh mesh to test
  111475. * @returns true if the mesh will be used
  111476. */
  111477. EffectLayer.prototype.hasMesh = function (mesh) {
  111478. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  111479. return true;
  111480. }
  111481. return false;
  111482. };
  111483. /**
  111484. * Returns true if the layer contains information to display, otherwise false.
  111485. * @returns true if the glow layer should be rendered
  111486. */
  111487. EffectLayer.prototype.shouldRender = function () {
  111488. return this.isEnabled && this._shouldRender;
  111489. };
  111490. /**
  111491. * Returns true if the mesh should render, otherwise false.
  111492. * @param mesh The mesh to render
  111493. * @returns true if it should render otherwise false
  111494. */
  111495. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  111496. return true;
  111497. };
  111498. /**
  111499. * Returns true if the mesh should render, otherwise false.
  111500. * @param mesh The mesh to render
  111501. * @returns true if it should render otherwise false
  111502. */
  111503. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  111504. return true;
  111505. };
  111506. /**
  111507. * Renders the submesh passed in parameter to the generation map.
  111508. */
  111509. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  111510. var _this = this;
  111511. if (!this.shouldRender()) {
  111512. return;
  111513. }
  111514. var material = subMesh.getMaterial();
  111515. var mesh = subMesh.getRenderingMesh();
  111516. var scene = this._scene;
  111517. var engine = scene.getEngine();
  111518. if (!material) {
  111519. return;
  111520. }
  111521. // Do not block in blend mode.
  111522. if (material.needAlphaBlendingForMesh(mesh)) {
  111523. return;
  111524. }
  111525. // Culling
  111526. engine.setState(material.backFaceCulling);
  111527. // Managing instances
  111528. var batch = mesh._getInstancesRenderList(subMesh._id);
  111529. if (batch.mustReturn) {
  111530. return;
  111531. }
  111532. // Early Exit per mesh
  111533. if (!this._shouldRenderMesh(mesh)) {
  111534. return;
  111535. }
  111536. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  111537. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  111538. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  111539. engine.enableEffect(this._effectLayerMapGenerationEffect);
  111540. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  111541. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  111542. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  111543. // Alpha test
  111544. if (material && material.needAlphaTesting()) {
  111545. var alphaTexture = material.getAlphaTestTexture();
  111546. if (alphaTexture) {
  111547. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  111548. var textureMatrix = alphaTexture.getTextureMatrix();
  111549. if (textureMatrix) {
  111550. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  111551. }
  111552. }
  111553. }
  111554. // Glow emissive only
  111555. if (this._emissiveTextureAndColor.texture) {
  111556. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  111557. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  111558. }
  111559. // Bones
  111560. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  111561. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  111562. }
  111563. // Morph targets
  111564. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  111565. // Draw
  111566. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  111567. }
  111568. else {
  111569. // Need to reset refresh rate of the main map
  111570. this._mainTexture.resetRefreshCounter();
  111571. }
  111572. };
  111573. /**
  111574. * Rebuild the required buffers.
  111575. * @hidden Internal use only.
  111576. */
  111577. EffectLayer.prototype._rebuild = function () {
  111578. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111579. if (vb) {
  111580. vb._rebuild();
  111581. }
  111582. this._generateIndexBuffer();
  111583. };
  111584. /**
  111585. * Dispose only the render target textures and post process.
  111586. */
  111587. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  111588. this._mainTexture.dispose();
  111589. for (var i = 0; i < this._postProcesses.length; i++) {
  111590. if (this._postProcesses[i]) {
  111591. this._postProcesses[i].dispose();
  111592. }
  111593. }
  111594. this._postProcesses = [];
  111595. for (var i = 0; i < this._textures.length; i++) {
  111596. if (this._textures[i]) {
  111597. this._textures[i].dispose();
  111598. }
  111599. }
  111600. this._textures = [];
  111601. };
  111602. /**
  111603. * Dispose the highlight layer and free resources.
  111604. */
  111605. EffectLayer.prototype.dispose = function () {
  111606. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111607. if (vertexBuffer) {
  111608. vertexBuffer.dispose();
  111609. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111610. }
  111611. if (this._indexBuffer) {
  111612. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111613. this._indexBuffer = null;
  111614. }
  111615. // Clean textures and post processes
  111616. this._disposeTextureAndPostProcesses();
  111617. // Remove from scene
  111618. var index = this._scene.effectLayers.indexOf(this, 0);
  111619. if (index > -1) {
  111620. this._scene.effectLayers.splice(index, 1);
  111621. }
  111622. // Callback
  111623. this.onDisposeObservable.notifyObservers(this);
  111624. this.onDisposeObservable.clear();
  111625. this.onBeforeRenderMainTextureObservable.clear();
  111626. this.onBeforeComposeObservable.clear();
  111627. this.onAfterComposeObservable.clear();
  111628. this.onSizeChangedObservable.clear();
  111629. };
  111630. /**
  111631. * Gets the class name of the effect layer
  111632. * @returns the string with the class name of the effect layer
  111633. */
  111634. EffectLayer.prototype.getClassName = function () {
  111635. return "EffectLayer";
  111636. };
  111637. /**
  111638. * Creates an effect layer from parsed effect layer data
  111639. * @param parsedEffectLayer defines effect layer data
  111640. * @param scene defines the current scene
  111641. * @param rootUrl defines the root URL containing the effect layer information
  111642. * @returns a parsed effect Layer
  111643. */
  111644. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  111645. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  111646. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  111647. };
  111648. __decorate([
  111649. BABYLON.serialize()
  111650. ], EffectLayer.prototype, "name", void 0);
  111651. __decorate([
  111652. BABYLON.serializeAsColor4()
  111653. ], EffectLayer.prototype, "neutralColor", void 0);
  111654. __decorate([
  111655. BABYLON.serialize()
  111656. ], EffectLayer.prototype, "isEnabled", void 0);
  111657. __decorate([
  111658. BABYLON.serializeAsCameraReference()
  111659. ], EffectLayer.prototype, "camera", null);
  111660. __decorate([
  111661. BABYLON.serialize()
  111662. ], EffectLayer.prototype, "renderingGroupId", null);
  111663. return EffectLayer;
  111664. }());
  111665. BABYLON.EffectLayer = EffectLayer;
  111666. })(BABYLON || (BABYLON = {}));
  111667. //# sourceMappingURL=babylon.effectLayer.js.map
  111668. var BABYLON;
  111669. (function (BABYLON) {
  111670. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  111671. for (var index = 0; index < this.effectLayers.length; index++) {
  111672. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  111673. return this.effectLayers[index];
  111674. }
  111675. }
  111676. return null;
  111677. };
  111678. /**
  111679. * Special Glow Blur post process only blurring the alpha channel
  111680. * It enforces keeping the most luminous color in the color channel.
  111681. */
  111682. var GlowBlurPostProcess = /** @class */ (function (_super) {
  111683. __extends(GlowBlurPostProcess, _super);
  111684. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  111685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  111686. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  111687. _this.direction = direction;
  111688. _this.kernel = kernel;
  111689. _this.onApplyObservable.add(function (effect) {
  111690. effect.setFloat2("screenSize", _this.width, _this.height);
  111691. effect.setVector2("direction", _this.direction);
  111692. effect.setFloat("blurWidth", _this.kernel);
  111693. });
  111694. return _this;
  111695. }
  111696. return GlowBlurPostProcess;
  111697. }(BABYLON.PostProcess));
  111698. /**
  111699. * The highlight layer Helps adding a glow effect around a mesh.
  111700. *
  111701. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111702. * glowy meshes to your scene.
  111703. *
  111704. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  111705. */
  111706. var HighlightLayer = /** @class */ (function (_super) {
  111707. __extends(HighlightLayer, _super);
  111708. /**
  111709. * Instantiates a new highlight Layer and references it to the scene..
  111710. * @param name The name of the layer
  111711. * @param scene The scene to use the layer in
  111712. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  111713. */
  111714. function HighlightLayer(name, scene, options) {
  111715. var _this = _super.call(this, name, scene) || this;
  111716. _this.name = name;
  111717. /**
  111718. * Specifies whether or not the inner glow is ACTIVE in the layer.
  111719. */
  111720. _this.innerGlow = true;
  111721. /**
  111722. * Specifies whether or not the outer glow is ACTIVE in the layer.
  111723. */
  111724. _this.outerGlow = true;
  111725. /**
  111726. * An event triggered when the highlight layer is being blurred.
  111727. */
  111728. _this.onBeforeBlurObservable = new BABYLON.Observable();
  111729. /**
  111730. * An event triggered when the highlight layer has been blurred.
  111731. */
  111732. _this.onAfterBlurObservable = new BABYLON.Observable();
  111733. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  111734. _this._meshes = {};
  111735. _this._excludedMeshes = {};
  111736. _this.neutralColor = HighlightLayer.NeutralColor;
  111737. // Warn on stencil
  111738. if (!_this._engine.isStencilEnable) {
  111739. 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 }");
  111740. }
  111741. // Adapt options
  111742. _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);
  111743. // Initialize the layer
  111744. _this._init({
  111745. alphaBlendingMode: _this._options.alphaBlendingMode,
  111746. camera: _this._options.camera,
  111747. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111748. mainTextureRatio: _this._options.mainTextureRatio,
  111749. renderingGroupId: _this._options.renderingGroupId
  111750. });
  111751. // Do not render as long as no meshes have been added
  111752. _this._shouldRender = false;
  111753. return _this;
  111754. }
  111755. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  111756. /**
  111757. * Gets the horizontal size of the blur.
  111758. */
  111759. get: function () {
  111760. return this._horizontalBlurPostprocess.kernel;
  111761. },
  111762. /**
  111763. * Specifies the horizontal size of the blur.
  111764. */
  111765. set: function (value) {
  111766. this._horizontalBlurPostprocess.kernel = value;
  111767. },
  111768. enumerable: true,
  111769. configurable: true
  111770. });
  111771. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  111772. /**
  111773. * Gets the vertical size of the blur.
  111774. */
  111775. get: function () {
  111776. return this._verticalBlurPostprocess.kernel;
  111777. },
  111778. /**
  111779. * Specifies the vertical size of the blur.
  111780. */
  111781. set: function (value) {
  111782. this._verticalBlurPostprocess.kernel = value;
  111783. },
  111784. enumerable: true,
  111785. configurable: true
  111786. });
  111787. /**
  111788. * Get the effect name of the layer.
  111789. * @return The effect name
  111790. */
  111791. HighlightLayer.prototype.getEffectName = function () {
  111792. return HighlightLayer.EffectName;
  111793. };
  111794. /**
  111795. * Create the merge effect. This is the shader use to blit the information back
  111796. * to the main canvas at the end of the scene rendering.
  111797. */
  111798. HighlightLayer.prototype._createMergeEffect = function () {
  111799. // Effect
  111800. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  111801. };
  111802. /**
  111803. * Creates the render target textures and post processes used in the highlight layer.
  111804. */
  111805. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  111806. var _this = this;
  111807. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  111808. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  111809. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111810. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111811. var textureType = 0;
  111812. if (this._engine.getCaps().textureHalfFloatRender) {
  111813. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111814. }
  111815. else {
  111816. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111817. }
  111818. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  111819. width: blurTextureWidth,
  111820. height: blurTextureHeight
  111821. }, this._scene, false, true, textureType);
  111822. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111823. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111824. this._blurTexture.anisotropicFilteringLevel = 16;
  111825. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  111826. this._blurTexture.renderParticles = false;
  111827. this._blurTexture.ignoreCameraViewport = true;
  111828. this._textures = [this._blurTexture];
  111829. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  111830. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111831. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  111832. effect.setTexture("textureSampler", _this._mainTexture);
  111833. });
  111834. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111835. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111836. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111837. });
  111838. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111839. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  111840. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111841. });
  111842. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111843. }
  111844. else {
  111845. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  111846. width: blurTextureWidth,
  111847. height: blurTextureHeight
  111848. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111849. this._horizontalBlurPostprocess.width = blurTextureWidth;
  111850. this._horizontalBlurPostprocess.height = blurTextureHeight;
  111851. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111852. effect.setTexture("textureSampler", _this._mainTexture);
  111853. });
  111854. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  111855. width: blurTextureWidth,
  111856. height: blurTextureHeight
  111857. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111858. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111859. }
  111860. this._mainTexture.onAfterUnbindObservable.add(function () {
  111861. _this.onBeforeBlurObservable.notifyObservers(_this);
  111862. var internalTexture = _this._blurTexture.getInternalTexture();
  111863. if (internalTexture) {
  111864. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  111865. }
  111866. _this.onAfterBlurObservable.notifyObservers(_this);
  111867. });
  111868. // Prevent autoClear.
  111869. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  111870. };
  111871. /**
  111872. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  111873. */
  111874. HighlightLayer.prototype.needStencil = function () {
  111875. return true;
  111876. };
  111877. /**
  111878. * Checks for the readiness of the element composing the layer.
  111879. * @param subMesh the mesh to check for
  111880. * @param useInstances specify wether or not to use instances to render the mesh
  111881. * @param emissiveTexture the associated emissive texture used to generate the glow
  111882. * @return true if ready otherwise, false
  111883. */
  111884. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  111885. var material = subMesh.getMaterial();
  111886. var mesh = subMesh.getRenderingMesh();
  111887. if (!material || !mesh || !this._meshes) {
  111888. return false;
  111889. }
  111890. var emissiveTexture = null;
  111891. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111892. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111893. emissiveTexture = material.emissiveTexture;
  111894. }
  111895. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  111896. };
  111897. /**
  111898. * Implementation specific of rendering the generating effect on the main canvas.
  111899. * @param effect The effect used to render through
  111900. */
  111901. HighlightLayer.prototype._internalRender = function (effect) {
  111902. // Texture
  111903. effect.setTexture("textureSampler", this._blurTexture);
  111904. // Cache
  111905. var engine = this._engine;
  111906. var previousStencilBuffer = engine.getStencilBuffer();
  111907. var previousStencilFunction = engine.getStencilFunction();
  111908. var previousStencilMask = engine.getStencilMask();
  111909. var previousStencilOperationPass = engine.getStencilOperationPass();
  111910. var previousStencilOperationFail = engine.getStencilOperationFail();
  111911. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  111912. var previousStencilReference = engine.getStencilFunctionReference();
  111913. // Stencil operations
  111914. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  111915. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  111916. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  111917. // Draw order
  111918. engine.setStencilMask(0x00);
  111919. engine.setStencilBuffer(true);
  111920. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  111921. // 2 passes inner outer
  111922. if (this.outerGlow) {
  111923. effect.setFloat("offset", 0);
  111924. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  111925. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111926. }
  111927. if (this.innerGlow) {
  111928. effect.setFloat("offset", 1);
  111929. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  111930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111931. }
  111932. // Restore Cache
  111933. engine.setStencilFunction(previousStencilFunction);
  111934. engine.setStencilMask(previousStencilMask);
  111935. engine.setStencilBuffer(previousStencilBuffer);
  111936. engine.setStencilOperationPass(previousStencilOperationPass);
  111937. engine.setStencilOperationFail(previousStencilOperationFail);
  111938. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  111939. engine.setStencilFunctionReference(previousStencilReference);
  111940. };
  111941. /**
  111942. * Returns true if the layer contains information to display, otherwise false.
  111943. */
  111944. HighlightLayer.prototype.shouldRender = function () {
  111945. if (_super.prototype.shouldRender.call(this)) {
  111946. return this._meshes ? true : false;
  111947. }
  111948. return false;
  111949. };
  111950. /**
  111951. * Returns true if the mesh should render, otherwise false.
  111952. * @param mesh The mesh to render
  111953. * @returns true if it should render otherwise false
  111954. */
  111955. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  111956. // Excluded Mesh
  111957. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  111958. return false;
  111959. }
  111960. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111961. return false;
  111962. }
  111963. return true;
  111964. };
  111965. /**
  111966. * Sets the required values for both the emissive texture and and the main color.
  111967. */
  111968. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  111969. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111970. if (highlightLayerMesh) {
  111971. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  111972. }
  111973. else {
  111974. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  111975. }
  111976. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111977. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  111978. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  111979. }
  111980. else {
  111981. this._emissiveTextureAndColor.texture = null;
  111982. }
  111983. };
  111984. /**
  111985. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  111986. * @param mesh The mesh to exclude from the highlight layer
  111987. */
  111988. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  111989. if (!this._excludedMeshes) {
  111990. return;
  111991. }
  111992. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111993. if (!meshExcluded) {
  111994. this._excludedMeshes[mesh.uniqueId] = {
  111995. mesh: mesh,
  111996. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  111997. mesh.getEngine().setStencilBuffer(false);
  111998. }),
  111999. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  112000. mesh.getEngine().setStencilBuffer(true);
  112001. }),
  112002. };
  112003. }
  112004. };
  112005. /**
  112006. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  112007. * @param mesh The mesh to highlight
  112008. */
  112009. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  112010. if (!this._excludedMeshes) {
  112011. return;
  112012. }
  112013. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  112014. if (meshExcluded) {
  112015. if (meshExcluded.beforeRender) {
  112016. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  112017. }
  112018. if (meshExcluded.afterRender) {
  112019. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  112020. }
  112021. }
  112022. this._excludedMeshes[mesh.uniqueId] = null;
  112023. };
  112024. /**
  112025. * Determine if a given mesh will be highlighted by the current HighlightLayer
  112026. * @param mesh mesh to test
  112027. * @returns true if the mesh will be highlighted by the current HighlightLayer
  112028. */
  112029. HighlightLayer.prototype.hasMesh = function (mesh) {
  112030. if (!this._meshes) {
  112031. return false;
  112032. }
  112033. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112034. return false;
  112035. }
  112036. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  112037. };
  112038. /**
  112039. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  112040. * @param mesh The mesh to highlight
  112041. * @param color The color of the highlight
  112042. * @param glowEmissiveOnly Extract the glow from the emissive texture
  112043. */
  112044. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  112045. var _this = this;
  112046. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  112047. if (!this._meshes) {
  112048. return;
  112049. }
  112050. var meshHighlight = this._meshes[mesh.uniqueId];
  112051. if (meshHighlight) {
  112052. meshHighlight.color = color;
  112053. }
  112054. else {
  112055. this._meshes[mesh.uniqueId] = {
  112056. mesh: mesh,
  112057. color: color,
  112058. // Lambda required for capture due to Observable this context
  112059. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  112060. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  112061. _this._defaultStencilReference(mesh);
  112062. }
  112063. else {
  112064. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  112065. }
  112066. }),
  112067. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  112068. glowEmissiveOnly: glowEmissiveOnly
  112069. };
  112070. mesh.onDisposeObservable.add(function () {
  112071. _this._disposeMesh(mesh);
  112072. });
  112073. }
  112074. this._shouldRender = true;
  112075. };
  112076. /**
  112077. * Remove a mesh from the highlight layer in order to make it stop glowing.
  112078. * @param mesh The mesh to highlight
  112079. */
  112080. HighlightLayer.prototype.removeMesh = function (mesh) {
  112081. if (!this._meshes) {
  112082. return;
  112083. }
  112084. var meshHighlight = this._meshes[mesh.uniqueId];
  112085. if (meshHighlight) {
  112086. if (meshHighlight.observerHighlight) {
  112087. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112088. }
  112089. if (meshHighlight.observerDefault) {
  112090. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112091. }
  112092. delete this._meshes[mesh.uniqueId];
  112093. }
  112094. this._shouldRender = false;
  112095. for (var meshHighlightToCheck in this._meshes) {
  112096. if (this._meshes[meshHighlightToCheck]) {
  112097. this._shouldRender = true;
  112098. break;
  112099. }
  112100. }
  112101. };
  112102. /**
  112103. * Force the stencil to the normal expected value for none glowing parts
  112104. */
  112105. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  112106. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  112107. };
  112108. /**
  112109. * Free any resources and references associated to a mesh.
  112110. * Internal use
  112111. * @param mesh The mesh to free.
  112112. * @hidden
  112113. */
  112114. HighlightLayer.prototype._disposeMesh = function (mesh) {
  112115. this.removeMesh(mesh);
  112116. this.removeExcludedMesh(mesh);
  112117. };
  112118. /**
  112119. * Dispose the highlight layer and free resources.
  112120. */
  112121. HighlightLayer.prototype.dispose = function () {
  112122. if (this._meshes) {
  112123. // Clean mesh references
  112124. for (var id in this._meshes) {
  112125. var meshHighlight = this._meshes[id];
  112126. if (meshHighlight && meshHighlight.mesh) {
  112127. if (meshHighlight.observerHighlight) {
  112128. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112129. }
  112130. if (meshHighlight.observerDefault) {
  112131. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112132. }
  112133. }
  112134. }
  112135. this._meshes = null;
  112136. }
  112137. if (this._excludedMeshes) {
  112138. for (var id in this._excludedMeshes) {
  112139. var meshHighlight = this._excludedMeshes[id];
  112140. if (meshHighlight) {
  112141. if (meshHighlight.beforeRender) {
  112142. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  112143. }
  112144. if (meshHighlight.afterRender) {
  112145. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  112146. }
  112147. }
  112148. }
  112149. this._excludedMeshes = null;
  112150. }
  112151. _super.prototype.dispose.call(this);
  112152. };
  112153. /**
  112154. * Gets the class name of the effect layer
  112155. * @returns the string with the class name of the effect layer
  112156. */
  112157. HighlightLayer.prototype.getClassName = function () {
  112158. return "HighlightLayer";
  112159. };
  112160. /**
  112161. * Serializes this Highlight layer
  112162. * @returns a serialized Highlight layer object
  112163. */
  112164. HighlightLayer.prototype.serialize = function () {
  112165. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112166. serializationObject.customType = "BABYLON.HighlightLayer";
  112167. // Highlighted meshes
  112168. serializationObject.meshes = [];
  112169. if (this._meshes) {
  112170. for (var m in this._meshes) {
  112171. var mesh = this._meshes[m];
  112172. if (mesh) {
  112173. serializationObject.meshes.push({
  112174. glowEmissiveOnly: mesh.glowEmissiveOnly,
  112175. color: mesh.color.asArray(),
  112176. meshId: mesh.mesh.id
  112177. });
  112178. }
  112179. }
  112180. }
  112181. // Excluded meshes
  112182. serializationObject.excludedMeshes = [];
  112183. if (this._excludedMeshes) {
  112184. for (var e in this._excludedMeshes) {
  112185. var excludedMesh = this._excludedMeshes[e];
  112186. if (excludedMesh) {
  112187. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  112188. }
  112189. }
  112190. }
  112191. return serializationObject;
  112192. };
  112193. /**
  112194. * Creates a Highlight layer from parsed Highlight layer data
  112195. * @param parsedHightlightLayer defines the Highlight layer data
  112196. * @param scene defines the current scene
  112197. * @param rootUrl defines the root URL containing the Highlight layer information
  112198. * @returns a parsed Highlight layer
  112199. */
  112200. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  112201. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  112202. var index;
  112203. // Excluded meshes
  112204. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  112205. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  112206. if (mesh) {
  112207. hl.addExcludedMesh(mesh);
  112208. }
  112209. }
  112210. // Included meshes
  112211. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  112212. var highlightedMesh = parsedHightlightLayer.meshes[index];
  112213. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  112214. if (mesh) {
  112215. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  112216. }
  112217. }
  112218. return hl;
  112219. };
  112220. /**
  112221. * Effect Name of the highlight layer.
  112222. */
  112223. HighlightLayer.EffectName = "HighlightLayer";
  112224. /**
  112225. * The neutral color used during the preparation of the glow effect.
  112226. * This is black by default as the blend operation is a blend operation.
  112227. */
  112228. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  112229. /**
  112230. * Stencil value used for glowing meshes.
  112231. */
  112232. HighlightLayer.GlowingMeshStencilReference = 0x02;
  112233. /**
  112234. * Stencil value used for the other meshes in the scene.
  112235. */
  112236. HighlightLayer.NormalMeshStencilReference = 0x01;
  112237. __decorate([
  112238. BABYLON.serialize()
  112239. ], HighlightLayer.prototype, "innerGlow", void 0);
  112240. __decorate([
  112241. BABYLON.serialize()
  112242. ], HighlightLayer.prototype, "outerGlow", void 0);
  112243. __decorate([
  112244. BABYLON.serialize()
  112245. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  112246. __decorate([
  112247. BABYLON.serialize()
  112248. ], HighlightLayer.prototype, "blurVerticalSize", null);
  112249. __decorate([
  112250. BABYLON.serialize("options")
  112251. ], HighlightLayer.prototype, "_options", void 0);
  112252. return HighlightLayer;
  112253. }(BABYLON.EffectLayer));
  112254. BABYLON.HighlightLayer = HighlightLayer;
  112255. })(BABYLON || (BABYLON = {}));
  112256. //# sourceMappingURL=babylon.highlightLayer.js.map
  112257. var BABYLON;
  112258. (function (BABYLON) {
  112259. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  112260. for (var index = 0; index < this.effectLayers.length; index++) {
  112261. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  112262. return this.effectLayers[index];
  112263. }
  112264. }
  112265. return null;
  112266. };
  112267. /**
  112268. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  112269. *
  112270. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  112271. * glowy meshes to your scene.
  112272. *
  112273. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  112274. */
  112275. var GlowLayer = /** @class */ (function (_super) {
  112276. __extends(GlowLayer, _super);
  112277. /**
  112278. * Instantiates a new glow Layer and references it to the scene.
  112279. * @param name The name of the layer
  112280. * @param scene The scene to use the layer in
  112281. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  112282. */
  112283. function GlowLayer(name, scene, options) {
  112284. var _this = _super.call(this, name, scene) || this;
  112285. _this._intensity = 1.0;
  112286. _this._includedOnlyMeshes = [];
  112287. _this._excludedMeshes = [];
  112288. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  112289. // Adapt options
  112290. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  112291. // Initialize the layer
  112292. _this._init({
  112293. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  112294. camera: _this._options.camera,
  112295. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  112296. mainTextureRatio: _this._options.mainTextureRatio,
  112297. renderingGroupId: _this._options.renderingGroupId
  112298. });
  112299. return _this;
  112300. }
  112301. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  112302. /**
  112303. * Gets the kernel size of the blur.
  112304. */
  112305. get: function () {
  112306. return this._horizontalBlurPostprocess1.kernel;
  112307. },
  112308. /**
  112309. * Sets the kernel size of the blur.
  112310. */
  112311. set: function (value) {
  112312. this._horizontalBlurPostprocess1.kernel = value;
  112313. this._verticalBlurPostprocess1.kernel = value;
  112314. this._horizontalBlurPostprocess2.kernel = value;
  112315. this._verticalBlurPostprocess2.kernel = value;
  112316. },
  112317. enumerable: true,
  112318. configurable: true
  112319. });
  112320. Object.defineProperty(GlowLayer.prototype, "intensity", {
  112321. /**
  112322. * Gets the glow intensity.
  112323. */
  112324. get: function () {
  112325. return this._intensity;
  112326. },
  112327. /**
  112328. * Sets the glow intensity.
  112329. */
  112330. set: function (value) {
  112331. this._intensity = value;
  112332. },
  112333. enumerable: true,
  112334. configurable: true
  112335. });
  112336. /**
  112337. * Get the effect name of the layer.
  112338. * @return The effect name
  112339. */
  112340. GlowLayer.prototype.getEffectName = function () {
  112341. return GlowLayer.EffectName;
  112342. };
  112343. /**
  112344. * Create the merge effect. This is the shader use to blit the information back
  112345. * to the main canvas at the end of the scene rendering.
  112346. */
  112347. GlowLayer.prototype._createMergeEffect = function () {
  112348. // Effect
  112349. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  112350. };
  112351. /**
  112352. * Creates the render target textures and post processes used in the glow layer.
  112353. */
  112354. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  112355. var _this = this;
  112356. var blurTextureWidth = this._mainTextureDesiredSize.width;
  112357. var blurTextureHeight = this._mainTextureDesiredSize.height;
  112358. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  112359. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  112360. var textureType = 0;
  112361. if (this._engine.getCaps().textureHalfFloatRender) {
  112362. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  112363. }
  112364. else {
  112365. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  112366. }
  112367. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  112368. width: blurTextureWidth,
  112369. height: blurTextureHeight
  112370. }, this._scene, false, true, textureType);
  112371. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112372. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112373. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112374. this._blurTexture1.renderParticles = false;
  112375. this._blurTexture1.ignoreCameraViewport = true;
  112376. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  112377. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  112378. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  112379. width: blurTextureWidth2,
  112380. height: blurTextureHeight2
  112381. }, this._scene, false, true, textureType);
  112382. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112383. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112384. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112385. this._blurTexture2.renderParticles = false;
  112386. this._blurTexture2.ignoreCameraViewport = true;
  112387. this._textures = [this._blurTexture1, this._blurTexture2];
  112388. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  112389. width: blurTextureWidth,
  112390. height: blurTextureHeight
  112391. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112392. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  112393. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  112394. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  112395. effect.setTexture("textureSampler", _this._mainTexture);
  112396. });
  112397. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112398. width: blurTextureWidth,
  112399. height: blurTextureHeight
  112400. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112401. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  112402. width: blurTextureWidth2,
  112403. height: blurTextureHeight2
  112404. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112405. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  112406. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  112407. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  112408. effect.setTexture("textureSampler", _this._blurTexture1);
  112409. });
  112410. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112411. width: blurTextureWidth2,
  112412. height: blurTextureHeight2
  112413. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112414. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112415. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  112416. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112417. this._mainTexture.samples = this._options.mainTextureSamples;
  112418. this._mainTexture.onAfterUnbindObservable.add(function () {
  112419. var internalTexture = _this._blurTexture1.getInternalTexture();
  112420. if (internalTexture) {
  112421. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  112422. internalTexture = _this._blurTexture2.getInternalTexture();
  112423. if (internalTexture) {
  112424. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  112425. }
  112426. }
  112427. });
  112428. // Prevent autoClear.
  112429. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  112430. };
  112431. /**
  112432. * Checks for the readiness of the element composing the layer.
  112433. * @param subMesh the mesh to check for
  112434. * @param useInstances specify wether or not to use instances to render the mesh
  112435. * @param emissiveTexture the associated emissive texture used to generate the glow
  112436. * @return true if ready otherwise, false
  112437. */
  112438. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  112439. var material = subMesh.getMaterial();
  112440. var mesh = subMesh.getRenderingMesh();
  112441. if (!material || !mesh) {
  112442. return false;
  112443. }
  112444. var emissiveTexture = material.emissiveTexture;
  112445. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  112446. };
  112447. /**
  112448. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  112449. */
  112450. GlowLayer.prototype.needStencil = function () {
  112451. return false;
  112452. };
  112453. /**
  112454. * Implementation specific of rendering the generating effect on the main canvas.
  112455. * @param effect The effect used to render through
  112456. */
  112457. GlowLayer.prototype._internalRender = function (effect) {
  112458. // Texture
  112459. effect.setTexture("textureSampler", this._blurTexture1);
  112460. effect.setTexture("textureSampler2", this._blurTexture2);
  112461. effect.setFloat("offset", this._intensity);
  112462. // Cache
  112463. var engine = this._engine;
  112464. var previousStencilBuffer = engine.getStencilBuffer();
  112465. // Draw order
  112466. engine.setStencilBuffer(false);
  112467. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112468. // Draw order
  112469. engine.setStencilBuffer(previousStencilBuffer);
  112470. };
  112471. /**
  112472. * Sets the required values for both the emissive texture and and the main color.
  112473. */
  112474. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  112475. var textureLevel = 1.0;
  112476. if (this.customEmissiveTextureSelector) {
  112477. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  112478. }
  112479. else {
  112480. if (material) {
  112481. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  112482. if (this._emissiveTextureAndColor.texture) {
  112483. textureLevel = this._emissiveTextureAndColor.texture.level;
  112484. }
  112485. }
  112486. else {
  112487. this._emissiveTextureAndColor.texture = null;
  112488. }
  112489. }
  112490. if (this.customEmissiveColorSelector) {
  112491. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  112492. }
  112493. else {
  112494. if (material.emissiveColor) {
  112495. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  112496. }
  112497. else {
  112498. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  112499. }
  112500. }
  112501. };
  112502. /**
  112503. * Returns true if the mesh should render, otherwise false.
  112504. * @param mesh The mesh to render
  112505. * @returns true if it should render otherwise false
  112506. */
  112507. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  112508. return this.hasMesh(mesh);
  112509. };
  112510. /**
  112511. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  112512. * @param mesh The mesh to exclude from the glow layer
  112513. */
  112514. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  112515. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  112516. this._excludedMeshes.push(mesh.uniqueId);
  112517. }
  112518. };
  112519. /**
  112520. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  112521. * @param mesh The mesh to remove
  112522. */
  112523. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  112524. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  112525. if (index !== -1) {
  112526. this._excludedMeshes.splice(index, 1);
  112527. }
  112528. };
  112529. /**
  112530. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  112531. * @param mesh The mesh to include in the glow layer
  112532. */
  112533. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  112534. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  112535. this._includedOnlyMeshes.push(mesh.uniqueId);
  112536. }
  112537. };
  112538. /**
  112539. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  112540. * @param mesh The mesh to remove
  112541. */
  112542. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  112543. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  112544. if (index !== -1) {
  112545. this._includedOnlyMeshes.splice(index, 1);
  112546. }
  112547. };
  112548. /**
  112549. * Determine if a given mesh will be used in the glow layer
  112550. * @param mesh The mesh to test
  112551. * @returns true if the mesh will be highlighted by the current glow layer
  112552. */
  112553. GlowLayer.prototype.hasMesh = function (mesh) {
  112554. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112555. return false;
  112556. }
  112557. // Included Mesh
  112558. if (this._includedOnlyMeshes.length) {
  112559. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  112560. }
  112561. // Excluded Mesh
  112562. if (this._excludedMeshes.length) {
  112563. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  112564. }
  112565. return true;
  112566. };
  112567. /**
  112568. * Free any resources and references associated to a mesh.
  112569. * Internal use
  112570. * @param mesh The mesh to free.
  112571. * @hidden
  112572. */
  112573. GlowLayer.prototype._disposeMesh = function (mesh) {
  112574. this.removeIncludedOnlyMesh(mesh);
  112575. this.removeExcludedMesh(mesh);
  112576. };
  112577. /**
  112578. * Gets the class name of the effect layer
  112579. * @returns the string with the class name of the effect layer
  112580. */
  112581. GlowLayer.prototype.getClassName = function () {
  112582. return "GlowLayer";
  112583. };
  112584. /**
  112585. * Serializes this glow layer
  112586. * @returns a serialized glow layer object
  112587. */
  112588. GlowLayer.prototype.serialize = function () {
  112589. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112590. serializationObject.customType = "BABYLON.GlowLayer";
  112591. var index;
  112592. // Included meshes
  112593. serializationObject.includedMeshes = [];
  112594. if (this._includedOnlyMeshes.length) {
  112595. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  112596. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  112597. if (mesh) {
  112598. serializationObject.includedMeshes.push(mesh.id);
  112599. }
  112600. }
  112601. }
  112602. // Excluded meshes
  112603. serializationObject.excludedMeshes = [];
  112604. if (this._excludedMeshes.length) {
  112605. for (index = 0; index < this._excludedMeshes.length; index++) {
  112606. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  112607. if (mesh) {
  112608. serializationObject.excludedMeshes.push(mesh.id);
  112609. }
  112610. }
  112611. }
  112612. return serializationObject;
  112613. };
  112614. /**
  112615. * Creates a Glow Layer from parsed glow layer data
  112616. * @param parsedGlowLayer defines glow layer data
  112617. * @param scene defines the current scene
  112618. * @param rootUrl defines the root URL containing the glow layer information
  112619. * @returns a parsed Glow Layer
  112620. */
  112621. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  112622. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  112623. var index;
  112624. // Excluded meshes
  112625. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  112626. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  112627. if (mesh) {
  112628. gl.addExcludedMesh(mesh);
  112629. }
  112630. }
  112631. // Included meshes
  112632. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  112633. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  112634. if (mesh) {
  112635. gl.addIncludedOnlyMesh(mesh);
  112636. }
  112637. }
  112638. return gl;
  112639. };
  112640. /**
  112641. * Effect Name of the layer.
  112642. */
  112643. GlowLayer.EffectName = "GlowLayer";
  112644. /**
  112645. * The default blur kernel size used for the glow.
  112646. */
  112647. GlowLayer.DefaultBlurKernelSize = 32;
  112648. /**
  112649. * The default texture size ratio used for the glow.
  112650. */
  112651. GlowLayer.DefaultTextureRatio = 0.5;
  112652. __decorate([
  112653. BABYLON.serialize()
  112654. ], GlowLayer.prototype, "blurKernelSize", null);
  112655. __decorate([
  112656. BABYLON.serialize()
  112657. ], GlowLayer.prototype, "intensity", null);
  112658. __decorate([
  112659. BABYLON.serialize("options")
  112660. ], GlowLayer.prototype, "_options", void 0);
  112661. return GlowLayer;
  112662. }(BABYLON.EffectLayer));
  112663. BABYLON.GlowLayer = GlowLayer;
  112664. })(BABYLON || (BABYLON = {}));
  112665. //# sourceMappingURL=babylon.glowLayer.js.map
  112666. var BABYLON;
  112667. (function (BABYLON) {
  112668. /**
  112669. * Defines the list of states available for a task inside a AssetsManager
  112670. */
  112671. var AssetTaskState;
  112672. (function (AssetTaskState) {
  112673. /**
  112674. * Initialization
  112675. */
  112676. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  112677. /**
  112678. * Running
  112679. */
  112680. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  112681. /**
  112682. * Done
  112683. */
  112684. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  112685. /**
  112686. * Error
  112687. */
  112688. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  112689. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  112690. /**
  112691. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  112692. */
  112693. var AbstractAssetTask = /** @class */ (function () {
  112694. /**
  112695. * Creates a new AssetsManager
  112696. * @param name defines the name of the task
  112697. */
  112698. function AbstractAssetTask(
  112699. /**
  112700. * Task name
  112701. */ name) {
  112702. this.name = name;
  112703. this._isCompleted = false;
  112704. this._taskState = AssetTaskState.INIT;
  112705. }
  112706. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  112707. /**
  112708. * Get if the task is completed
  112709. */
  112710. get: function () {
  112711. return this._isCompleted;
  112712. },
  112713. enumerable: true,
  112714. configurable: true
  112715. });
  112716. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  112717. /**
  112718. * Gets the current state of the task
  112719. */
  112720. get: function () {
  112721. return this._taskState;
  112722. },
  112723. enumerable: true,
  112724. configurable: true
  112725. });
  112726. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  112727. /**
  112728. * Gets the current error object (if task is in error)
  112729. */
  112730. get: function () {
  112731. return this._errorObject;
  112732. },
  112733. enumerable: true,
  112734. configurable: true
  112735. });
  112736. /**
  112737. * Internal only
  112738. * @hidden
  112739. */
  112740. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  112741. if (this._errorObject) {
  112742. return;
  112743. }
  112744. this._errorObject = {
  112745. message: message,
  112746. exception: exception
  112747. };
  112748. };
  112749. /**
  112750. * Execute the current task
  112751. * @param scene defines the scene where you want your assets to be loaded
  112752. * @param onSuccess is a callback called when the task is successfully executed
  112753. * @param onError is a callback called if an error occurs
  112754. */
  112755. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112756. var _this = this;
  112757. this._taskState = AssetTaskState.RUNNING;
  112758. this.runTask(scene, function () {
  112759. _this.onDoneCallback(onSuccess, onError);
  112760. }, function (msg, exception) {
  112761. _this.onErrorCallback(onError, msg, exception);
  112762. });
  112763. };
  112764. /**
  112765. * Execute the current task
  112766. * @param scene defines the scene where you want your assets to be loaded
  112767. * @param onSuccess is a callback called when the task is successfully executed
  112768. * @param onError is a callback called if an error occurs
  112769. */
  112770. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112771. throw new Error("runTask is not implemented");
  112772. };
  112773. /**
  112774. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  112775. * This can be used with failed tasks that have the reason for failure fixed.
  112776. */
  112777. AbstractAssetTask.prototype.reset = function () {
  112778. this._taskState = AssetTaskState.INIT;
  112779. };
  112780. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  112781. this._taskState = AssetTaskState.ERROR;
  112782. this._errorObject = {
  112783. message: message,
  112784. exception: exception
  112785. };
  112786. if (this.onError) {
  112787. this.onError(this, message, exception);
  112788. }
  112789. onError();
  112790. };
  112791. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  112792. try {
  112793. this._taskState = AssetTaskState.DONE;
  112794. this._isCompleted = true;
  112795. if (this.onSuccess) {
  112796. this.onSuccess(this);
  112797. }
  112798. onSuccess();
  112799. }
  112800. catch (e) {
  112801. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  112802. }
  112803. };
  112804. return AbstractAssetTask;
  112805. }());
  112806. BABYLON.AbstractAssetTask = AbstractAssetTask;
  112807. /**
  112808. * Class used to share progress information about assets loading
  112809. */
  112810. var AssetsProgressEvent = /** @class */ (function () {
  112811. /**
  112812. * Creates a AssetsProgressEvent
  112813. * @param remainingCount defines the number of remaining tasks to process
  112814. * @param totalCount defines the total number of tasks
  112815. * @param task defines the task that was just processed
  112816. */
  112817. function AssetsProgressEvent(remainingCount, totalCount, task) {
  112818. this.remainingCount = remainingCount;
  112819. this.totalCount = totalCount;
  112820. this.task = task;
  112821. }
  112822. return AssetsProgressEvent;
  112823. }());
  112824. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  112825. /**
  112826. * Define a task used by AssetsManager to load meshes
  112827. */
  112828. var MeshAssetTask = /** @class */ (function (_super) {
  112829. __extends(MeshAssetTask, _super);
  112830. /**
  112831. * Creates a new MeshAssetTask
  112832. * @param name defines the name of the task
  112833. * @param meshesNames defines the list of mesh's names you want to load
  112834. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  112835. * @param sceneFilename defines the filename of the scene to load from
  112836. */
  112837. function MeshAssetTask(
  112838. /**
  112839. * Defines the name of the task
  112840. */
  112841. name,
  112842. /**
  112843. * Defines the list of mesh's names you want to load
  112844. */
  112845. meshesNames,
  112846. /**
  112847. * Defines the root url to use as a base to load your meshes and associated resources
  112848. */
  112849. rootUrl,
  112850. /**
  112851. * Defines the filename of the scene to load from
  112852. */
  112853. sceneFilename) {
  112854. var _this = _super.call(this, name) || this;
  112855. _this.name = name;
  112856. _this.meshesNames = meshesNames;
  112857. _this.rootUrl = rootUrl;
  112858. _this.sceneFilename = sceneFilename;
  112859. return _this;
  112860. }
  112861. /**
  112862. * Execute the current task
  112863. * @param scene defines the scene where you want your assets to be loaded
  112864. * @param onSuccess is a callback called when the task is successfully executed
  112865. * @param onError is a callback called if an error occurs
  112866. */
  112867. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112868. var _this = this;
  112869. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  112870. _this.loadedMeshes = meshes;
  112871. _this.loadedParticleSystems = particleSystems;
  112872. _this.loadedSkeletons = skeletons;
  112873. onSuccess();
  112874. }, null, function (scene, message, exception) {
  112875. onError(message, exception);
  112876. });
  112877. };
  112878. return MeshAssetTask;
  112879. }(AbstractAssetTask));
  112880. BABYLON.MeshAssetTask = MeshAssetTask;
  112881. /**
  112882. * Define a task used by AssetsManager to load text content
  112883. */
  112884. var TextFileAssetTask = /** @class */ (function (_super) {
  112885. __extends(TextFileAssetTask, _super);
  112886. /**
  112887. * Creates a new TextFileAssetTask object
  112888. * @param name defines the name of the task
  112889. * @param url defines the location of the file to load
  112890. */
  112891. function TextFileAssetTask(
  112892. /**
  112893. * Defines the name of the task
  112894. */
  112895. name,
  112896. /**
  112897. * Defines the location of the file to load
  112898. */
  112899. url) {
  112900. var _this = _super.call(this, name) || this;
  112901. _this.name = name;
  112902. _this.url = url;
  112903. return _this;
  112904. }
  112905. /**
  112906. * Execute the current task
  112907. * @param scene defines the scene where you want your assets to be loaded
  112908. * @param onSuccess is a callback called when the task is successfully executed
  112909. * @param onError is a callback called if an error occurs
  112910. */
  112911. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112912. var _this = this;
  112913. scene._loadFile(this.url, function (data) {
  112914. _this.text = data;
  112915. onSuccess();
  112916. }, undefined, false, false, function (request, exception) {
  112917. if (request) {
  112918. onError(request.status + " " + request.statusText, exception);
  112919. }
  112920. });
  112921. };
  112922. return TextFileAssetTask;
  112923. }(AbstractAssetTask));
  112924. BABYLON.TextFileAssetTask = TextFileAssetTask;
  112925. /**
  112926. * Define a task used by AssetsManager to load binary data
  112927. */
  112928. var BinaryFileAssetTask = /** @class */ (function (_super) {
  112929. __extends(BinaryFileAssetTask, _super);
  112930. /**
  112931. * Creates a new BinaryFileAssetTask object
  112932. * @param name defines the name of the new task
  112933. * @param url defines the location of the file to load
  112934. */
  112935. function BinaryFileAssetTask(
  112936. /**
  112937. * Defines the name of the task
  112938. */
  112939. name,
  112940. /**
  112941. * Defines the location of the file to load
  112942. */
  112943. url) {
  112944. var _this = _super.call(this, name) || this;
  112945. _this.name = name;
  112946. _this.url = url;
  112947. return _this;
  112948. }
  112949. /**
  112950. * Execute the current task
  112951. * @param scene defines the scene where you want your assets to be loaded
  112952. * @param onSuccess is a callback called when the task is successfully executed
  112953. * @param onError is a callback called if an error occurs
  112954. */
  112955. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112956. var _this = this;
  112957. scene._loadFile(this.url, function (data) {
  112958. _this.data = data;
  112959. onSuccess();
  112960. }, undefined, true, true, function (request, exception) {
  112961. if (request) {
  112962. onError(request.status + " " + request.statusText, exception);
  112963. }
  112964. });
  112965. };
  112966. return BinaryFileAssetTask;
  112967. }(AbstractAssetTask));
  112968. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  112969. /**
  112970. * Define a task used by AssetsManager to load images
  112971. */
  112972. var ImageAssetTask = /** @class */ (function (_super) {
  112973. __extends(ImageAssetTask, _super);
  112974. /**
  112975. * Creates a new ImageAssetTask
  112976. * @param name defines the name of the task
  112977. * @param url defines the location of the image to load
  112978. */
  112979. function ImageAssetTask(
  112980. /**
  112981. * Defines the name of the task
  112982. */
  112983. name,
  112984. /**
  112985. * Defines the location of the image to load
  112986. */
  112987. url) {
  112988. var _this = _super.call(this, name) || this;
  112989. _this.name = name;
  112990. _this.url = url;
  112991. return _this;
  112992. }
  112993. /**
  112994. * Execute the current task
  112995. * @param scene defines the scene where you want your assets to be loaded
  112996. * @param onSuccess is a callback called when the task is successfully executed
  112997. * @param onError is a callback called if an error occurs
  112998. */
  112999. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113000. var _this = this;
  113001. var img = new Image();
  113002. BABYLON.Tools.SetCorsBehavior(this.url, img);
  113003. img.onload = function () {
  113004. _this.image = img;
  113005. onSuccess();
  113006. };
  113007. img.onerror = function (err) {
  113008. onError("Error loading image", err);
  113009. };
  113010. img.src = this.url;
  113011. };
  113012. return ImageAssetTask;
  113013. }(AbstractAssetTask));
  113014. BABYLON.ImageAssetTask = ImageAssetTask;
  113015. /**
  113016. * Define a task used by AssetsManager to load 2D textures
  113017. */
  113018. var TextureAssetTask = /** @class */ (function (_super) {
  113019. __extends(TextureAssetTask, _super);
  113020. /**
  113021. * Creates a new TextureAssetTask object
  113022. * @param name defines the name of the task
  113023. * @param url defines the location of the file to load
  113024. * @param noMipmap defines if mipmap should not be generated (default is false)
  113025. * @param invertY defines if texture must be inverted on Y axis (default is false)
  113026. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  113027. */
  113028. function TextureAssetTask(
  113029. /**
  113030. * Defines the name of the task
  113031. */
  113032. name,
  113033. /**
  113034. * Defines the location of the file to load
  113035. */
  113036. url,
  113037. /**
  113038. * Defines if mipmap should not be generated (default is false)
  113039. */
  113040. noMipmap,
  113041. /**
  113042. * Defines if texture must be inverted on Y axis (default is false)
  113043. */
  113044. invertY,
  113045. /**
  113046. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  113047. */
  113048. samplingMode) {
  113049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113050. var _this = _super.call(this, name) || this;
  113051. _this.name = name;
  113052. _this.url = url;
  113053. _this.noMipmap = noMipmap;
  113054. _this.invertY = invertY;
  113055. _this.samplingMode = samplingMode;
  113056. return _this;
  113057. }
  113058. /**
  113059. * Execute the current task
  113060. * @param scene defines the scene where you want your assets to be loaded
  113061. * @param onSuccess is a callback called when the task is successfully executed
  113062. * @param onError is a callback called if an error occurs
  113063. */
  113064. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113065. var onload = function () {
  113066. onSuccess();
  113067. };
  113068. var onerror = function (message, exception) {
  113069. onError(message, exception);
  113070. };
  113071. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  113072. };
  113073. return TextureAssetTask;
  113074. }(AbstractAssetTask));
  113075. BABYLON.TextureAssetTask = TextureAssetTask;
  113076. /**
  113077. * Define a task used by AssetsManager to load cube textures
  113078. */
  113079. var CubeTextureAssetTask = /** @class */ (function (_super) {
  113080. __extends(CubeTextureAssetTask, _super);
  113081. /**
  113082. * Creates a new CubeTextureAssetTask
  113083. * @param name defines the name of the task
  113084. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113085. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113086. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113087. * @param files defines the explicit list of files (undefined by default)
  113088. */
  113089. function CubeTextureAssetTask(
  113090. /**
  113091. * Defines the name of the task
  113092. */
  113093. name,
  113094. /**
  113095. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113096. */
  113097. url,
  113098. /**
  113099. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113100. */
  113101. extensions,
  113102. /**
  113103. * Defines if mipmaps should not be generated (default is false)
  113104. */
  113105. noMipmap,
  113106. /**
  113107. * Defines the explicit list of files (undefined by default)
  113108. */
  113109. files) {
  113110. var _this = _super.call(this, name) || this;
  113111. _this.name = name;
  113112. _this.url = url;
  113113. _this.extensions = extensions;
  113114. _this.noMipmap = noMipmap;
  113115. _this.files = files;
  113116. return _this;
  113117. }
  113118. /**
  113119. * Execute the current task
  113120. * @param scene defines the scene where you want your assets to be loaded
  113121. * @param onSuccess is a callback called when the task is successfully executed
  113122. * @param onError is a callback called if an error occurs
  113123. */
  113124. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113125. var onload = function () {
  113126. onSuccess();
  113127. };
  113128. var onerror = function (message, exception) {
  113129. onError(message, exception);
  113130. };
  113131. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  113132. };
  113133. return CubeTextureAssetTask;
  113134. }(AbstractAssetTask));
  113135. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  113136. /**
  113137. * Define a task used by AssetsManager to load HDR cube textures
  113138. */
  113139. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  113140. __extends(HDRCubeTextureAssetTask, _super);
  113141. /**
  113142. * Creates a new HDRCubeTextureAssetTask object
  113143. * @param name defines the name of the task
  113144. * @param url defines the location of the file to load
  113145. * @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.
  113146. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113147. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113148. * @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)
  113149. * @param reserved Internal use only
  113150. */
  113151. function HDRCubeTextureAssetTask(
  113152. /**
  113153. * Defines the name of the task
  113154. */
  113155. name,
  113156. /**
  113157. * Defines the location of the file to load
  113158. */
  113159. url,
  113160. /**
  113161. * Defines the desired size (the more it increases the longer the generation will be)
  113162. */
  113163. size,
  113164. /**
  113165. * Defines if mipmaps should not be generated (default is false)
  113166. */
  113167. noMipmap,
  113168. /**
  113169. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113170. */
  113171. generateHarmonics,
  113172. /**
  113173. * 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)
  113174. */
  113175. gammaSpace,
  113176. /**
  113177. * Internal Use Only
  113178. */
  113179. reserved) {
  113180. if (noMipmap === void 0) { noMipmap = false; }
  113181. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113182. if (gammaSpace === void 0) { gammaSpace = false; }
  113183. if (reserved === void 0) { reserved = false; }
  113184. var _this = _super.call(this, name) || this;
  113185. _this.name = name;
  113186. _this.url = url;
  113187. _this.size = size;
  113188. _this.noMipmap = noMipmap;
  113189. _this.generateHarmonics = generateHarmonics;
  113190. _this.gammaSpace = gammaSpace;
  113191. _this.reserved = reserved;
  113192. return _this;
  113193. }
  113194. /**
  113195. * Execute the current task
  113196. * @param scene defines the scene where you want your assets to be loaded
  113197. * @param onSuccess is a callback called when the task is successfully executed
  113198. * @param onError is a callback called if an error occurs
  113199. */
  113200. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  113201. var onload = function () {
  113202. onSuccess();
  113203. };
  113204. var onerror = function (message, exception) {
  113205. onError(message, exception);
  113206. };
  113207. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  113208. };
  113209. return HDRCubeTextureAssetTask;
  113210. }(AbstractAssetTask));
  113211. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  113212. /**
  113213. * This class can be used to easily import assets into a scene
  113214. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  113215. */
  113216. var AssetsManager = /** @class */ (function () {
  113217. /**
  113218. * Creates a new AssetsManager
  113219. * @param scene defines the scene to work on
  113220. */
  113221. function AssetsManager(scene) {
  113222. this._isLoading = false;
  113223. this._tasks = new Array();
  113224. this._waitingTasksCount = 0;
  113225. this._totalTasksCount = 0;
  113226. /**
  113227. * Observable called when all tasks are processed
  113228. */
  113229. this.onTaskSuccessObservable = new BABYLON.Observable();
  113230. /**
  113231. * Observable called when a task had an error
  113232. */
  113233. this.onTaskErrorObservable = new BABYLON.Observable();
  113234. /**
  113235. * Observable called when a task is successful
  113236. */
  113237. this.onTasksDoneObservable = new BABYLON.Observable();
  113238. /**
  113239. * Observable called when a task is done (whatever the result is)
  113240. */
  113241. this.onProgressObservable = new BABYLON.Observable();
  113242. /**
  113243. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  113244. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  113245. */
  113246. this.useDefaultLoadingScreen = true;
  113247. this._scene = scene;
  113248. }
  113249. /**
  113250. * Add a MeshAssetTask to the list of active tasks
  113251. * @param taskName defines the name of the new task
  113252. * @param meshesNames defines the name of meshes to load
  113253. * @param rootUrl defines the root url to use to locate files
  113254. * @param sceneFilename defines the filename of the scene file
  113255. * @returns a new MeshAssetTask object
  113256. */
  113257. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  113258. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  113259. this._tasks.push(task);
  113260. return task;
  113261. };
  113262. /**
  113263. * Add a TextFileAssetTask to the list of active tasks
  113264. * @param taskName defines the name of the new task
  113265. * @param url defines the url of the file to load
  113266. * @returns a new TextFileAssetTask object
  113267. */
  113268. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  113269. var task = new TextFileAssetTask(taskName, url);
  113270. this._tasks.push(task);
  113271. return task;
  113272. };
  113273. /**
  113274. * Add a BinaryFileAssetTask to the list of active tasks
  113275. * @param taskName defines the name of the new task
  113276. * @param url defines the url of the file to load
  113277. * @returns a new BinaryFileAssetTask object
  113278. */
  113279. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  113280. var task = new BinaryFileAssetTask(taskName, url);
  113281. this._tasks.push(task);
  113282. return task;
  113283. };
  113284. /**
  113285. * Add a ImageAssetTask to the list of active tasks
  113286. * @param taskName defines the name of the new task
  113287. * @param url defines the url of the file to load
  113288. * @returns a new ImageAssetTask object
  113289. */
  113290. AssetsManager.prototype.addImageTask = function (taskName, url) {
  113291. var task = new ImageAssetTask(taskName, url);
  113292. this._tasks.push(task);
  113293. return task;
  113294. };
  113295. /**
  113296. * Add a TextureAssetTask to the list of active tasks
  113297. * @param taskName defines the name of the new task
  113298. * @param url defines the url of the file to load
  113299. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113300. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  113301. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  113302. * @returns a new TextureAssetTask object
  113303. */
  113304. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  113305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113306. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  113307. this._tasks.push(task);
  113308. return task;
  113309. };
  113310. /**
  113311. * Add a CubeTextureAssetTask to the list of active tasks
  113312. * @param taskName defines the name of the new task
  113313. * @param url defines the url of the file to load
  113314. * @param extensions defines the extension to use to load the cube map (can be null)
  113315. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113316. * @param files defines the list of files to load (can be null)
  113317. * @returns a new CubeTextureAssetTask object
  113318. */
  113319. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  113320. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  113321. this._tasks.push(task);
  113322. return task;
  113323. };
  113324. /**
  113325. *
  113326. * Add a HDRCubeTextureAssetTask to the list of active tasks
  113327. * @param taskName defines the name of the new task
  113328. * @param url defines the url of the file to load
  113329. * @param size defines the size you want for the cubemap (can be null)
  113330. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113331. * @param generateHarmonics defines if you want to automatically generate (true by default)
  113332. * @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)
  113333. * @param reserved Internal use only
  113334. * @returns a new HDRCubeTextureAssetTask object
  113335. */
  113336. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  113337. if (noMipmap === void 0) { noMipmap = false; }
  113338. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113339. if (gammaSpace === void 0) { gammaSpace = false; }
  113340. if (reserved === void 0) { reserved = false; }
  113341. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  113342. this._tasks.push(task);
  113343. return task;
  113344. };
  113345. /**
  113346. * Remove a task from the assets manager.
  113347. * @param task the task to remove
  113348. */
  113349. AssetsManager.prototype.removeTask = function (task) {
  113350. var index = this._tasks.indexOf(task);
  113351. if (index > -1) {
  113352. this._tasks.splice(index, 1);
  113353. }
  113354. };
  113355. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  113356. this._waitingTasksCount--;
  113357. try {
  113358. if (this.onProgress) {
  113359. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  113360. }
  113361. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  113362. }
  113363. catch (e) {
  113364. BABYLON.Tools.Error("Error running progress callbacks.");
  113365. console.log(e);
  113366. }
  113367. if (this._waitingTasksCount === 0) {
  113368. try {
  113369. if (this.onFinish) {
  113370. this.onFinish(this._tasks);
  113371. }
  113372. // Let's remove successfull tasks
  113373. var currentTasks = this._tasks.slice();
  113374. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  113375. var task = currentTasks_1[_i];
  113376. if (task.taskState === AssetTaskState.DONE) {
  113377. var index = this._tasks.indexOf(task);
  113378. if (index > -1) {
  113379. this._tasks.splice(index, 1);
  113380. }
  113381. }
  113382. }
  113383. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113384. }
  113385. catch (e) {
  113386. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  113387. console.log(e);
  113388. }
  113389. this._isLoading = false;
  113390. this._scene.getEngine().hideLoadingUI();
  113391. }
  113392. };
  113393. AssetsManager.prototype._runTask = function (task) {
  113394. var _this = this;
  113395. var done = function () {
  113396. try {
  113397. if (_this.onTaskSuccess) {
  113398. _this.onTaskSuccess(task);
  113399. }
  113400. _this.onTaskSuccessObservable.notifyObservers(task);
  113401. _this._decreaseWaitingTasksCount(task);
  113402. }
  113403. catch (e) {
  113404. error("Error executing task success callbacks", e);
  113405. }
  113406. };
  113407. var error = function (message, exception) {
  113408. task._setErrorObject(message, exception);
  113409. if (_this.onTaskError) {
  113410. _this.onTaskError(task);
  113411. }
  113412. _this.onTaskErrorObservable.notifyObservers(task);
  113413. _this._decreaseWaitingTasksCount(task);
  113414. };
  113415. task.run(this._scene, done, error);
  113416. };
  113417. /**
  113418. * Reset the AssetsManager and remove all tasks
  113419. * @return the current instance of the AssetsManager
  113420. */
  113421. AssetsManager.prototype.reset = function () {
  113422. this._isLoading = false;
  113423. this._tasks = new Array();
  113424. return this;
  113425. };
  113426. /**
  113427. * Start the loading process
  113428. * @return the current instance of the AssetsManager
  113429. */
  113430. AssetsManager.prototype.load = function () {
  113431. if (this._isLoading) {
  113432. return this;
  113433. }
  113434. this._isLoading = true;
  113435. this._waitingTasksCount = this._tasks.length;
  113436. this._totalTasksCount = this._tasks.length;
  113437. if (this._waitingTasksCount === 0) {
  113438. this._isLoading = false;
  113439. if (this.onFinish) {
  113440. this.onFinish(this._tasks);
  113441. }
  113442. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113443. return this;
  113444. }
  113445. if (this.useDefaultLoadingScreen) {
  113446. this._scene.getEngine().displayLoadingUI();
  113447. }
  113448. for (var index = 0; index < this._tasks.length; index++) {
  113449. var task = this._tasks[index];
  113450. if (task.taskState === AssetTaskState.INIT) {
  113451. this._runTask(task);
  113452. }
  113453. }
  113454. return this;
  113455. };
  113456. return AssetsManager;
  113457. }());
  113458. BABYLON.AssetsManager = AssetsManager;
  113459. })(BABYLON || (BABYLON = {}));
  113460. //# sourceMappingURL=babylon.assetsManager.js.map
  113461. var BABYLON;
  113462. (function (BABYLON) {
  113463. var serializedGeometries = [];
  113464. var serializeGeometry = function (geometry, serializationGeometries) {
  113465. if (serializedGeometries[geometry.id]) {
  113466. return;
  113467. }
  113468. if (geometry.doNotSerialize) {
  113469. return;
  113470. }
  113471. if (geometry instanceof BABYLON.BoxGeometry) {
  113472. serializationGeometries.boxes.push(geometry.serialize());
  113473. }
  113474. else if (geometry instanceof BABYLON.SphereGeometry) {
  113475. serializationGeometries.spheres.push(geometry.serialize());
  113476. }
  113477. else if (geometry instanceof BABYLON.CylinderGeometry) {
  113478. serializationGeometries.cylinders.push(geometry.serialize());
  113479. }
  113480. else if (geometry instanceof BABYLON.TorusGeometry) {
  113481. serializationGeometries.toruses.push(geometry.serialize());
  113482. }
  113483. else if (geometry instanceof BABYLON.GroundGeometry) {
  113484. serializationGeometries.grounds.push(geometry.serialize());
  113485. }
  113486. else if (geometry instanceof BABYLON.Plane) {
  113487. serializationGeometries.planes.push(geometry.serialize());
  113488. }
  113489. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  113490. serializationGeometries.torusKnots.push(geometry.serialize());
  113491. }
  113492. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  113493. throw new Error("Unknown primitive type");
  113494. }
  113495. else {
  113496. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  113497. }
  113498. serializedGeometries[geometry.id] = true;
  113499. };
  113500. var serializeMesh = function (mesh, serializationScene) {
  113501. var serializationObject = {};
  113502. // Geometry
  113503. var geometry = mesh._geometry;
  113504. if (geometry) {
  113505. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  113506. // 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
  113507. serializeGeometry(geometry, serializationScene.geometries);
  113508. }
  113509. }
  113510. // Custom
  113511. if (mesh.serialize) {
  113512. mesh.serialize(serializationObject);
  113513. }
  113514. return serializationObject;
  113515. };
  113516. var finalizeSingleMesh = function (mesh, serializationObject) {
  113517. //only works if the mesh is already loaded
  113518. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113519. //serialize material
  113520. if (mesh.material) {
  113521. if (mesh.material instanceof BABYLON.MultiMaterial) {
  113522. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  113523. serializationObject.materials = serializationObject.materials || [];
  113524. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113525. serializationObject.multiMaterials.push(mesh.material.serialize());
  113526. var _loop_1 = function (submaterial) {
  113527. if (submaterial) {
  113528. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  113529. serializationObject.materials.push(submaterial.serialize());
  113530. }
  113531. }
  113532. };
  113533. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  113534. var submaterial = _a[_i];
  113535. _loop_1(submaterial);
  113536. }
  113537. }
  113538. }
  113539. else {
  113540. serializationObject.materials = serializationObject.materials || [];
  113541. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113542. serializationObject.materials.push(mesh.material.serialize());
  113543. }
  113544. }
  113545. }
  113546. //serialize geometry
  113547. var geometry = mesh._geometry;
  113548. if (geometry) {
  113549. if (!serializationObject.geometries) {
  113550. serializationObject.geometries = {};
  113551. serializationObject.geometries.boxes = [];
  113552. serializationObject.geometries.spheres = [];
  113553. serializationObject.geometries.cylinders = [];
  113554. serializationObject.geometries.toruses = [];
  113555. serializationObject.geometries.grounds = [];
  113556. serializationObject.geometries.planes = [];
  113557. serializationObject.geometries.torusKnots = [];
  113558. serializationObject.geometries.vertexData = [];
  113559. }
  113560. serializeGeometry(geometry, serializationObject.geometries);
  113561. }
  113562. // Skeletons
  113563. if (mesh.skeleton) {
  113564. serializationObject.skeletons = serializationObject.skeletons || [];
  113565. serializationObject.skeletons.push(mesh.skeleton.serialize());
  113566. }
  113567. //serialize the actual mesh
  113568. serializationObject.meshes = serializationObject.meshes || [];
  113569. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113570. }
  113571. };
  113572. /**
  113573. * Class used to serialize a scene into a string
  113574. */
  113575. var SceneSerializer = /** @class */ (function () {
  113576. function SceneSerializer() {
  113577. }
  113578. /**
  113579. * Clear cache used by a previous serialization
  113580. */
  113581. SceneSerializer.ClearCache = function () {
  113582. serializedGeometries = [];
  113583. };
  113584. /**
  113585. * Serialize a scene into a JSON compatible object
  113586. * @param scene defines the scene to serialize
  113587. * @returns a JSON compatible object
  113588. */
  113589. SceneSerializer.Serialize = function (scene) {
  113590. var serializationObject = {};
  113591. SceneSerializer.ClearCache();
  113592. // Scene
  113593. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  113594. serializationObject.autoClear = scene.autoClear;
  113595. serializationObject.clearColor = scene.clearColor.asArray();
  113596. serializationObject.ambientColor = scene.ambientColor.asArray();
  113597. serializationObject.gravity = scene.gravity.asArray();
  113598. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  113599. serializationObject.workerCollisions = scene.workerCollisions;
  113600. // Fog
  113601. if (scene.fogMode && scene.fogMode !== 0) {
  113602. serializationObject.fogMode = scene.fogMode;
  113603. serializationObject.fogColor = scene.fogColor.asArray();
  113604. serializationObject.fogStart = scene.fogStart;
  113605. serializationObject.fogEnd = scene.fogEnd;
  113606. serializationObject.fogDensity = scene.fogDensity;
  113607. }
  113608. //Physics
  113609. if (scene.isPhysicsEnabled()) {
  113610. var physicEngine = scene.getPhysicsEngine();
  113611. if (physicEngine) {
  113612. serializationObject.physicsEnabled = true;
  113613. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  113614. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  113615. }
  113616. }
  113617. // Metadata
  113618. if (scene.metadata) {
  113619. serializationObject.metadata = scene.metadata;
  113620. }
  113621. // Morph targets
  113622. serializationObject.morphTargetManagers = [];
  113623. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  113624. var abstractMesh = _a[_i];
  113625. var manager = abstractMesh.morphTargetManager;
  113626. if (manager) {
  113627. serializationObject.morphTargetManagers.push(manager.serialize());
  113628. }
  113629. }
  113630. // Lights
  113631. serializationObject.lights = [];
  113632. var index;
  113633. var light;
  113634. for (index = 0; index < scene.lights.length; index++) {
  113635. light = scene.lights[index];
  113636. if (!light.doNotSerialize) {
  113637. serializationObject.lights.push(light.serialize());
  113638. }
  113639. }
  113640. // Cameras
  113641. serializationObject.cameras = [];
  113642. for (index = 0; index < scene.cameras.length; index++) {
  113643. var camera = scene.cameras[index];
  113644. if (!camera.doNotSerialize) {
  113645. serializationObject.cameras.push(camera.serialize());
  113646. }
  113647. }
  113648. if (scene.activeCamera) {
  113649. serializationObject.activeCameraID = scene.activeCamera.id;
  113650. }
  113651. // Animations
  113652. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  113653. // Materials
  113654. serializationObject.materials = [];
  113655. serializationObject.multiMaterials = [];
  113656. var material;
  113657. for (index = 0; index < scene.materials.length; index++) {
  113658. material = scene.materials[index];
  113659. if (!material.doNotSerialize) {
  113660. serializationObject.materials.push(material.serialize());
  113661. }
  113662. }
  113663. // MultiMaterials
  113664. serializationObject.multiMaterials = [];
  113665. for (index = 0; index < scene.multiMaterials.length; index++) {
  113666. var multiMaterial = scene.multiMaterials[index];
  113667. serializationObject.multiMaterials.push(multiMaterial.serialize());
  113668. }
  113669. // Environment texture
  113670. if (scene.environmentTexture) {
  113671. serializationObject.environmentTexture = scene.environmentTexture.name;
  113672. }
  113673. // Skeletons
  113674. serializationObject.skeletons = [];
  113675. for (index = 0; index < scene.skeletons.length; index++) {
  113676. var skeleton = scene.skeletons[index];
  113677. if (!skeleton.doNotSerialize) {
  113678. serializationObject.skeletons.push(skeleton.serialize());
  113679. }
  113680. }
  113681. // Transform nodes
  113682. serializationObject.transformNodes = [];
  113683. for (index = 0; index < scene.transformNodes.length; index++) {
  113684. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  113685. }
  113686. // Geometries
  113687. serializationObject.geometries = {};
  113688. serializationObject.geometries.boxes = [];
  113689. serializationObject.geometries.spheres = [];
  113690. serializationObject.geometries.cylinders = [];
  113691. serializationObject.geometries.toruses = [];
  113692. serializationObject.geometries.grounds = [];
  113693. serializationObject.geometries.planes = [];
  113694. serializationObject.geometries.torusKnots = [];
  113695. serializationObject.geometries.vertexData = [];
  113696. serializedGeometries = [];
  113697. var geometries = scene.getGeometries();
  113698. for (index = 0; index < geometries.length; index++) {
  113699. var geometry = geometries[index];
  113700. if (geometry.isReady()) {
  113701. serializeGeometry(geometry, serializationObject.geometries);
  113702. }
  113703. }
  113704. // Meshes
  113705. serializationObject.meshes = [];
  113706. for (index = 0; index < scene.meshes.length; index++) {
  113707. var abstractMesh = scene.meshes[index];
  113708. if (abstractMesh instanceof BABYLON.Mesh) {
  113709. var mesh = abstractMesh;
  113710. if (!mesh.doNotSerialize) {
  113711. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113712. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113713. }
  113714. }
  113715. }
  113716. }
  113717. // Particles Systems
  113718. serializationObject.particleSystems = [];
  113719. for (index = 0; index < scene.particleSystems.length; index++) {
  113720. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  113721. }
  113722. // Action Manager
  113723. if (scene.actionManager) {
  113724. serializationObject.actions = scene.actionManager.serialize("scene");
  113725. }
  113726. // Components
  113727. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  113728. var component = _c[_b];
  113729. component.serialize(serializationObject);
  113730. }
  113731. return serializationObject;
  113732. };
  113733. /**
  113734. * Serialize a mesh into a JSON compatible object
  113735. * @param toSerialize defines the mesh to serialize
  113736. * @param withParents defines if parents must be serialized as well
  113737. * @param withChildren defines if children must be serialized as well
  113738. * @returns a JSON compatible object
  113739. */
  113740. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  113741. if (withParents === void 0) { withParents = false; }
  113742. if (withChildren === void 0) { withChildren = false; }
  113743. var serializationObject = {};
  113744. SceneSerializer.ClearCache();
  113745. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  113746. if (withParents || withChildren) {
  113747. //deliberate for loop! not for each, appended should be processed as well.
  113748. for (var i = 0; i < toSerialize.length; ++i) {
  113749. if (withChildren) {
  113750. toSerialize[i].getDescendants().forEach(function (node) {
  113751. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  113752. toSerialize.push(node);
  113753. }
  113754. });
  113755. }
  113756. //make sure the array doesn't contain the object already
  113757. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  113758. toSerialize.push(toSerialize[i].parent);
  113759. }
  113760. }
  113761. }
  113762. toSerialize.forEach(function (mesh) {
  113763. finalizeSingleMesh(mesh, serializationObject);
  113764. });
  113765. return serializationObject;
  113766. };
  113767. return SceneSerializer;
  113768. }());
  113769. BABYLON.SceneSerializer = SceneSerializer;
  113770. })(BABYLON || (BABYLON = {}));
  113771. //# sourceMappingURL=babylon.sceneSerializer.js.map
  113772. var BABYLON;
  113773. (function (BABYLON) {
  113774. /**
  113775. * Class used to generate realtime reflection / refraction cube textures
  113776. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  113777. */
  113778. var ReflectionProbe = /** @class */ (function () {
  113779. /**
  113780. * Creates a new reflection probe
  113781. * @param name defines the name of the probe
  113782. * @param size defines the texture resolution (for each face)
  113783. * @param scene defines the hosting scene
  113784. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  113785. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  113786. */
  113787. function ReflectionProbe(
  113788. /** defines the name of the probe */
  113789. name, size, scene, generateMipMaps, useFloat) {
  113790. if (generateMipMaps === void 0) { generateMipMaps = true; }
  113791. if (useFloat === void 0) { useFloat = false; }
  113792. var _this = this;
  113793. this.name = name;
  113794. this._viewMatrix = BABYLON.Matrix.Identity();
  113795. this._target = BABYLON.Vector3.Zero();
  113796. this._add = BABYLON.Vector3.Zero();
  113797. this._invertYAxis = false;
  113798. /** Gets or sets probe position (center of the cube map) */
  113799. this.position = BABYLON.Vector3.Zero();
  113800. this._scene = scene;
  113801. // Create the scene field if not exist.
  113802. if (!this._scene.reflectionProbes) {
  113803. this._scene.reflectionProbes = new Array();
  113804. }
  113805. this._scene.reflectionProbes.push(this);
  113806. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  113807. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  113808. switch (faceIndex) {
  113809. case 0:
  113810. _this._add.copyFromFloats(1, 0, 0);
  113811. break;
  113812. case 1:
  113813. _this._add.copyFromFloats(-1, 0, 0);
  113814. break;
  113815. case 2:
  113816. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  113817. break;
  113818. case 3:
  113819. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  113820. break;
  113821. case 4:
  113822. _this._add.copyFromFloats(0, 0, 1);
  113823. break;
  113824. case 5:
  113825. _this._add.copyFromFloats(0, 0, -1);
  113826. break;
  113827. }
  113828. if (_this._attachedMesh) {
  113829. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  113830. }
  113831. _this.position.addToRef(_this._add, _this._target);
  113832. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  113833. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  113834. scene._forcedViewPosition = _this.position;
  113835. });
  113836. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  113837. scene._forcedViewPosition = null;
  113838. scene.updateTransformMatrix(true);
  113839. });
  113840. if (scene.activeCamera) {
  113841. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  113842. }
  113843. }
  113844. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  113845. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  113846. get: function () {
  113847. return this._renderTargetTexture.samples;
  113848. },
  113849. set: function (value) {
  113850. this._renderTargetTexture.samples = value;
  113851. },
  113852. enumerable: true,
  113853. configurable: true
  113854. });
  113855. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  113856. /** Gets or sets the refresh rate to use (on every frame by default) */
  113857. get: function () {
  113858. return this._renderTargetTexture.refreshRate;
  113859. },
  113860. set: function (value) {
  113861. this._renderTargetTexture.refreshRate = value;
  113862. },
  113863. enumerable: true,
  113864. configurable: true
  113865. });
  113866. /**
  113867. * Gets the hosting scene
  113868. * @returns a Scene
  113869. */
  113870. ReflectionProbe.prototype.getScene = function () {
  113871. return this._scene;
  113872. };
  113873. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  113874. /** Gets the internal CubeTexture used to render to */
  113875. get: function () {
  113876. return this._renderTargetTexture;
  113877. },
  113878. enumerable: true,
  113879. configurable: true
  113880. });
  113881. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  113882. /** Gets the list of meshes to render */
  113883. get: function () {
  113884. return this._renderTargetTexture.renderList;
  113885. },
  113886. enumerable: true,
  113887. configurable: true
  113888. });
  113889. /**
  113890. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  113891. * @param mesh defines the mesh to attach to
  113892. */
  113893. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  113894. this._attachedMesh = mesh;
  113895. };
  113896. /**
  113897. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  113898. * @param renderingGroupId The rendering group id corresponding to its index
  113899. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  113900. */
  113901. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  113902. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  113903. };
  113904. /**
  113905. * Clean all associated resources
  113906. */
  113907. ReflectionProbe.prototype.dispose = function () {
  113908. var index = this._scene.reflectionProbes.indexOf(this);
  113909. if (index !== -1) {
  113910. // Remove from the scene if found
  113911. this._scene.reflectionProbes.splice(index, 1);
  113912. }
  113913. if (this._renderTargetTexture) {
  113914. this._renderTargetTexture.dispose();
  113915. this._renderTargetTexture = null;
  113916. }
  113917. };
  113918. return ReflectionProbe;
  113919. }());
  113920. BABYLON.ReflectionProbe = ReflectionProbe;
  113921. })(BABYLON || (BABYLON = {}));
  113922. //# sourceMappingURL=babylon.reflectionProbe.js.map
  113923. var BABYLON;
  113924. (function (BABYLON) {
  113925. /**
  113926. * Defines the layer scene component responsible to manage any layers
  113927. * in a given scene.
  113928. */
  113929. var LayerSceneComponent = /** @class */ (function () {
  113930. /**
  113931. * Creates a new instance of the component for the given scene
  113932. * @param scene Defines the scene to register the component in
  113933. */
  113934. function LayerSceneComponent(scene) {
  113935. /**
  113936. * The component name helpfull to identify the component in the list of scene components.
  113937. */
  113938. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  113939. this.scene = scene;
  113940. this._engine = scene.getEngine();
  113941. scene.layers = new Array();
  113942. }
  113943. /**
  113944. * Registers the component in a given scene
  113945. */
  113946. LayerSceneComponent.prototype.register = function () {
  113947. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  113948. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  113949. };
  113950. /**
  113951. * Rebuilds the elements related to this component in case of
  113952. * context lost for instance.
  113953. */
  113954. LayerSceneComponent.prototype.rebuild = function () {
  113955. var layers = this.scene.layers;
  113956. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  113957. var layer = layers_1[_i];
  113958. layer._rebuild();
  113959. }
  113960. };
  113961. /**
  113962. * Disposes the component and the associated ressources.
  113963. */
  113964. LayerSceneComponent.prototype.dispose = function () {
  113965. var layers = this.scene.layers;
  113966. while (layers.length) {
  113967. layers[0].dispose();
  113968. }
  113969. };
  113970. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  113971. var layers = this.scene.layers;
  113972. if (layers.length) {
  113973. this._engine.setDepthBuffer(false);
  113974. var cameraLayerMask = camera.layerMask;
  113975. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  113976. var layer = layers_2[_i];
  113977. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  113978. layer.render();
  113979. }
  113980. }
  113981. this._engine.setDepthBuffer(true);
  113982. }
  113983. };
  113984. LayerSceneComponent.prototype._drawBackground = function (camera) {
  113985. this._draw(camera, true);
  113986. };
  113987. LayerSceneComponent.prototype._drawForeground = function (camera) {
  113988. this._draw(camera, false);
  113989. };
  113990. return LayerSceneComponent;
  113991. }());
  113992. BABYLON.LayerSceneComponent = LayerSceneComponent;
  113993. })(BABYLON || (BABYLON = {}));
  113994. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  113995. var BABYLON;
  113996. (function (BABYLON) {
  113997. /**
  113998. * This represents a full screen 2d layer.
  113999. * This can be usefull to display a picture in the background of your scene for instance.
  114000. * @see https://www.babylonjs-playground.com/#08A2BS#1
  114001. */
  114002. var Layer = /** @class */ (function () {
  114003. /**
  114004. * Instantiates a new layer.
  114005. * This represents a full screen 2d layer.
  114006. * This can be usefull to display a picture in the background of your scene for instance.
  114007. * @see https://www.babylonjs-playground.com/#08A2BS#1
  114008. * @param name Define the name of the layer in the scene
  114009. * @param imgUrl Define the url of the texture to display in the layer
  114010. * @param scene Define the scene the layer belongs to
  114011. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  114012. * @param color Defines a color for the layer
  114013. */
  114014. function Layer(
  114015. /**
  114016. * Define the name of the layer.
  114017. */
  114018. name, imgUrl, scene, isBackground, color) {
  114019. this.name = name;
  114020. /**
  114021. * Define the scale of the layer in order to zoom in out of the texture.
  114022. */
  114023. this.scale = new BABYLON.Vector2(1, 1);
  114024. /**
  114025. * Define an offset for the layer in order to shift the texture.
  114026. */
  114027. this.offset = new BABYLON.Vector2(0, 0);
  114028. /**
  114029. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  114030. */
  114031. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  114032. /**
  114033. * Define a mask to restrict the layer to only some of the scene cameras.
  114034. */
  114035. this.layerMask = 0x0FFFFFFF;
  114036. this._vertexBuffers = {};
  114037. /**
  114038. * An event triggered when the layer is disposed.
  114039. */
  114040. this.onDisposeObservable = new BABYLON.Observable();
  114041. /**
  114042. * An event triggered before rendering the scene
  114043. */
  114044. this.onBeforeRenderObservable = new BABYLON.Observable();
  114045. /**
  114046. * An event triggered after rendering the scene
  114047. */
  114048. this.onAfterRenderObservable = new BABYLON.Observable();
  114049. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  114050. this.isBackground = isBackground === undefined ? true : isBackground;
  114051. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  114052. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  114053. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  114054. if (!layerComponent) {
  114055. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  114056. this._scene._addComponent(layerComponent);
  114057. }
  114058. this._scene.layers.push(this);
  114059. var engine = this._scene.getEngine();
  114060. // VBO
  114061. var vertices = [];
  114062. vertices.push(1, 1);
  114063. vertices.push(-1, 1);
  114064. vertices.push(-1, -1);
  114065. vertices.push(1, -1);
  114066. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  114067. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  114068. this._createIndexBuffer();
  114069. // Effects
  114070. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  114071. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  114072. }
  114073. Object.defineProperty(Layer.prototype, "onDispose", {
  114074. /**
  114075. * Back compatibility with callback before the onDisposeObservable existed.
  114076. * The set callback will be triggered when the layer has been disposed.
  114077. */
  114078. set: function (callback) {
  114079. if (this._onDisposeObserver) {
  114080. this.onDisposeObservable.remove(this._onDisposeObserver);
  114081. }
  114082. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  114083. },
  114084. enumerable: true,
  114085. configurable: true
  114086. });
  114087. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  114088. /**
  114089. * Back compatibility with callback before the onBeforeRenderObservable existed.
  114090. * The set callback will be triggered just before rendering the layer.
  114091. */
  114092. set: function (callback) {
  114093. if (this._onBeforeRenderObserver) {
  114094. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  114095. }
  114096. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  114097. },
  114098. enumerable: true,
  114099. configurable: true
  114100. });
  114101. Object.defineProperty(Layer.prototype, "onAfterRender", {
  114102. /**
  114103. * Back compatibility with callback before the onAfterRenderObservable existed.
  114104. * The set callback will be triggered just after rendering the layer.
  114105. */
  114106. set: function (callback) {
  114107. if (this._onAfterRenderObserver) {
  114108. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114109. }
  114110. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  114111. },
  114112. enumerable: true,
  114113. configurable: true
  114114. });
  114115. Layer.prototype._createIndexBuffer = function () {
  114116. var engine = this._scene.getEngine();
  114117. // Indices
  114118. var indices = [];
  114119. indices.push(0);
  114120. indices.push(1);
  114121. indices.push(2);
  114122. indices.push(0);
  114123. indices.push(2);
  114124. indices.push(3);
  114125. this._indexBuffer = engine.createIndexBuffer(indices);
  114126. };
  114127. /** @hidden */
  114128. Layer.prototype._rebuild = function () {
  114129. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114130. if (vb) {
  114131. vb._rebuild();
  114132. }
  114133. this._createIndexBuffer();
  114134. };
  114135. /**
  114136. * Renders the layer in the scene.
  114137. */
  114138. Layer.prototype.render = function () {
  114139. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  114140. // Check
  114141. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  114142. return;
  114143. }
  114144. var engine = this._scene.getEngine();
  114145. this.onBeforeRenderObservable.notifyObservers(this);
  114146. // Render
  114147. engine.enableEffect(currentEffect);
  114148. engine.setState(false);
  114149. // Texture
  114150. currentEffect.setTexture("textureSampler", this.texture);
  114151. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  114152. // Color
  114153. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  114154. // Scale / offset
  114155. currentEffect.setVector2("offset", this.offset);
  114156. currentEffect.setVector2("scale", this.scale);
  114157. // VBOs
  114158. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  114159. // Draw order
  114160. if (!this.alphaTest) {
  114161. engine.setAlphaMode(this.alphaBlendingMode);
  114162. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114163. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  114164. }
  114165. else {
  114166. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114167. }
  114168. this.onAfterRenderObservable.notifyObservers(this);
  114169. };
  114170. /**
  114171. * Disposes and releases the associated ressources.
  114172. */
  114173. Layer.prototype.dispose = function () {
  114174. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114175. if (vertexBuffer) {
  114176. vertexBuffer.dispose();
  114177. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  114178. }
  114179. if (this._indexBuffer) {
  114180. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  114181. this._indexBuffer = null;
  114182. }
  114183. if (this.texture) {
  114184. this.texture.dispose();
  114185. this.texture = null;
  114186. }
  114187. // Remove from scene
  114188. var index = this._scene.layers.indexOf(this);
  114189. this._scene.layers.splice(index, 1);
  114190. // Callback
  114191. this.onDisposeObservable.notifyObservers(this);
  114192. this.onDisposeObservable.clear();
  114193. this.onAfterRenderObservable.clear();
  114194. this.onBeforeRenderObservable.clear();
  114195. };
  114196. return Layer;
  114197. }());
  114198. BABYLON.Layer = Layer;
  114199. })(BABYLON || (BABYLON = {}));
  114200. //# sourceMappingURL=babylon.layer.js.map
  114201. var BABYLON;
  114202. (function (BABYLON) {
  114203. /**
  114204. * Class used to host texture specific utilities
  114205. */
  114206. var TextureTools = /** @class */ (function () {
  114207. function TextureTools() {
  114208. }
  114209. /**
  114210. * Uses the GPU to create a copy texture rescaled at a given size
  114211. * @param texture Texture to copy from
  114212. * @param width defines the desired width
  114213. * @param height defines the desired height
  114214. * @param useBilinearMode defines if bilinear mode has to be used
  114215. * @return the generated texture
  114216. */
  114217. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  114218. if (useBilinearMode === void 0) { useBilinearMode = true; }
  114219. var scene = texture.getScene();
  114220. var engine = scene.getEngine();
  114221. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  114222. rtt.wrapU = texture.wrapU;
  114223. rtt.wrapV = texture.wrapV;
  114224. rtt.uOffset = texture.uOffset;
  114225. rtt.vOffset = texture.vOffset;
  114226. rtt.uScale = texture.uScale;
  114227. rtt.vScale = texture.vScale;
  114228. rtt.uAng = texture.uAng;
  114229. rtt.vAng = texture.vAng;
  114230. rtt.wAng = texture.wAng;
  114231. rtt.coordinatesIndex = texture.coordinatesIndex;
  114232. rtt.level = texture.level;
  114233. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  114234. rtt._texture.isReady = false;
  114235. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114236. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114237. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  114238. passPostProcess.getEffect().executeWhenCompiled(function () {
  114239. passPostProcess.onApply = function (effect) {
  114240. effect.setTexture("textureSampler", texture);
  114241. };
  114242. var internalTexture = rtt.getInternalTexture();
  114243. if (internalTexture) {
  114244. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  114245. engine.unBindFramebuffer(internalTexture);
  114246. rtt.disposeFramebufferObjects();
  114247. passPostProcess.dispose();
  114248. internalTexture.isReady = true;
  114249. }
  114250. });
  114251. return rtt;
  114252. };
  114253. /**
  114254. * Gets an environment BRDF texture for a given scene
  114255. * @param scene defines the hosting scene
  114256. * @returns the environment BRDF texture
  114257. */
  114258. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  114259. if (!scene._environmentBRDFTexture) {
  114260. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  114261. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114262. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114263. scene._environmentBRDFTexture = texture;
  114264. }
  114265. return scene._environmentBRDFTexture;
  114266. };
  114267. 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=";
  114268. return TextureTools;
  114269. }());
  114270. BABYLON.TextureTools = TextureTools;
  114271. })(BABYLON || (BABYLON = {}));
  114272. //# sourceMappingURL=babylon.textureTools.js.map
  114273. var BABYLON;
  114274. (function (BABYLON) {
  114275. /**
  114276. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  114277. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  114278. */
  114279. var FramingBehavior = /** @class */ (function () {
  114280. function FramingBehavior() {
  114281. this._mode = FramingBehavior.FitFrustumSidesMode;
  114282. this._radiusScale = 1.0;
  114283. this._positionScale = 0.5;
  114284. this._defaultElevation = 0.3;
  114285. this._elevationReturnTime = 1500;
  114286. this._elevationReturnWaitTime = 1000;
  114287. this._zoomStopsAnimation = false;
  114288. this._framingTime = 1500;
  114289. /**
  114290. * Define if the behavior should automatically change the configured
  114291. * camera limits and sensibilities.
  114292. */
  114293. this.autoCorrectCameraLimitsAndSensibility = true;
  114294. this._isPointerDown = false;
  114295. this._lastInteractionTime = -Infinity;
  114296. // Framing control
  114297. this._animatables = new Array();
  114298. this._betaIsAnimating = false;
  114299. }
  114300. Object.defineProperty(FramingBehavior.prototype, "name", {
  114301. /**
  114302. * Gets the name of the behavior.
  114303. */
  114304. get: function () {
  114305. return "Framing";
  114306. },
  114307. enumerable: true,
  114308. configurable: true
  114309. });
  114310. Object.defineProperty(FramingBehavior.prototype, "mode", {
  114311. /**
  114312. * Gets current mode used by the behavior.
  114313. */
  114314. get: function () {
  114315. return this._mode;
  114316. },
  114317. /**
  114318. * Sets the current mode used by the behavior
  114319. */
  114320. set: function (mode) {
  114321. this._mode = mode;
  114322. },
  114323. enumerable: true,
  114324. configurable: true
  114325. });
  114326. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  114327. /**
  114328. * Gets the scale applied to the radius
  114329. */
  114330. get: function () {
  114331. return this._radiusScale;
  114332. },
  114333. /**
  114334. * Sets the scale applied to the radius (1 by default)
  114335. */
  114336. set: function (radius) {
  114337. this._radiusScale = radius;
  114338. },
  114339. enumerable: true,
  114340. configurable: true
  114341. });
  114342. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  114343. /**
  114344. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  114345. */
  114346. get: function () {
  114347. return this._positionScale;
  114348. },
  114349. /**
  114350. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  114351. */
  114352. set: function (scale) {
  114353. this._positionScale = scale;
  114354. },
  114355. enumerable: true,
  114356. configurable: true
  114357. });
  114358. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  114359. /**
  114360. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  114361. * behaviour is triggered, in radians.
  114362. */
  114363. get: function () {
  114364. return this._defaultElevation;
  114365. },
  114366. /**
  114367. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  114368. * behaviour is triggered, in radians.
  114369. */
  114370. set: function (elevation) {
  114371. this._defaultElevation = elevation;
  114372. },
  114373. enumerable: true,
  114374. configurable: true
  114375. });
  114376. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  114377. /**
  114378. * Gets the time (in milliseconds) taken to return to the default beta position.
  114379. * Negative value indicates camera should not return to default.
  114380. */
  114381. get: function () {
  114382. return this._elevationReturnTime;
  114383. },
  114384. /**
  114385. * Sets the time (in milliseconds) taken to return to the default beta position.
  114386. * Negative value indicates camera should not return to default.
  114387. */
  114388. set: function (speed) {
  114389. this._elevationReturnTime = speed;
  114390. },
  114391. enumerable: true,
  114392. configurable: true
  114393. });
  114394. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  114395. /**
  114396. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  114397. */
  114398. get: function () {
  114399. return this._elevationReturnWaitTime;
  114400. },
  114401. /**
  114402. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  114403. */
  114404. set: function (time) {
  114405. this._elevationReturnWaitTime = time;
  114406. },
  114407. enumerable: true,
  114408. configurable: true
  114409. });
  114410. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  114411. /**
  114412. * Gets the flag that indicates if user zooming should stop animation.
  114413. */
  114414. get: function () {
  114415. return this._zoomStopsAnimation;
  114416. },
  114417. /**
  114418. * Sets the flag that indicates if user zooming should stop animation.
  114419. */
  114420. set: function (flag) {
  114421. this._zoomStopsAnimation = flag;
  114422. },
  114423. enumerable: true,
  114424. configurable: true
  114425. });
  114426. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  114427. /**
  114428. * Gets the transition time when framing the mesh, in milliseconds
  114429. */
  114430. get: function () {
  114431. return this._framingTime;
  114432. },
  114433. /**
  114434. * Sets the transition time when framing the mesh, in milliseconds
  114435. */
  114436. set: function (time) {
  114437. this._framingTime = time;
  114438. },
  114439. enumerable: true,
  114440. configurable: true
  114441. });
  114442. /**
  114443. * Initializes the behavior.
  114444. */
  114445. FramingBehavior.prototype.init = function () {
  114446. // Do notihng
  114447. };
  114448. /**
  114449. * Attaches the behavior to its arc rotate camera.
  114450. * @param camera Defines the camera to attach the behavior to
  114451. */
  114452. FramingBehavior.prototype.attach = function (camera) {
  114453. var _this = this;
  114454. this._attachedCamera = camera;
  114455. var scene = this._attachedCamera.getScene();
  114456. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  114457. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  114458. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  114459. _this._isPointerDown = true;
  114460. return;
  114461. }
  114462. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  114463. _this._isPointerDown = false;
  114464. }
  114465. });
  114466. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114467. if (mesh) {
  114468. _this.zoomOnMesh(mesh);
  114469. }
  114470. });
  114471. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114472. // Stop the animation if there is user interaction and the animation should stop for this interaction
  114473. _this._applyUserInteraction();
  114474. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  114475. // back to the default position after a given timeout
  114476. _this._maintainCameraAboveGround();
  114477. });
  114478. };
  114479. /**
  114480. * Detaches the behavior from its current arc rotate camera.
  114481. */
  114482. FramingBehavior.prototype.detach = function () {
  114483. if (!this._attachedCamera) {
  114484. return;
  114485. }
  114486. var scene = this._attachedCamera.getScene();
  114487. if (this._onPrePointerObservableObserver) {
  114488. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  114489. }
  114490. if (this._onAfterCheckInputsObserver) {
  114491. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114492. }
  114493. if (this._onMeshTargetChangedObserver) {
  114494. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114495. }
  114496. this._attachedCamera = null;
  114497. };
  114498. /**
  114499. * Targets the given mesh and updates zoom level accordingly.
  114500. * @param mesh The mesh to target.
  114501. * @param radius Optional. If a cached radius position already exists, overrides default.
  114502. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114503. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114504. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114505. */
  114506. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114507. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114508. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114509. mesh.computeWorldMatrix(true);
  114510. var boundingBox = mesh.getBoundingInfo().boundingBox;
  114511. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  114512. };
  114513. /**
  114514. * Targets the given mesh with its children and updates zoom level accordingly.
  114515. * @param mesh The mesh to target.
  114516. * @param radius Optional. If a cached radius position already exists, overrides default.
  114517. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114518. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114519. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114520. */
  114521. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114522. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114523. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114524. mesh.computeWorldMatrix(true);
  114525. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  114526. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  114527. };
  114528. /**
  114529. * Targets the given meshes with their children and updates zoom level accordingly.
  114530. * @param meshes The mesh to target.
  114531. * @param radius Optional. If a cached radius position already exists, overrides default.
  114532. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114533. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114534. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114535. */
  114536. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  114537. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114538. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114539. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  114540. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  114541. for (var i = 0; i < meshes.length; i++) {
  114542. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  114543. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  114544. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  114545. }
  114546. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  114547. };
  114548. /**
  114549. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  114550. * @param minimumWorld Determines the smaller position of the bounding box extend
  114551. * @param maximumWorld Determines the bigger position of the bounding box extend
  114552. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114553. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114554. */
  114555. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  114556. var _this = this;
  114557. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114558. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114559. var zoomTarget;
  114560. if (!this._attachedCamera) {
  114561. return;
  114562. }
  114563. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  114564. var bottom = minimumWorld.y;
  114565. var top = maximumWorld.y;
  114566. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  114567. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  114568. if (focusOnOriginXZ) {
  114569. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  114570. }
  114571. else {
  114572. var centerWorld = minimumWorld.add(radiusWorld);
  114573. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  114574. }
  114575. if (!this._vectorTransition) {
  114576. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  114577. }
  114578. this._betaIsAnimating = true;
  114579. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  114580. if (animatable) {
  114581. this._animatables.push(animatable);
  114582. }
  114583. // sets the radius and lower radius bounds
  114584. // Small delta ensures camera is not always at lower zoom limit.
  114585. var radius = 0;
  114586. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  114587. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114588. if (this.autoCorrectCameraLimitsAndSensibility) {
  114589. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  114590. }
  114591. radius = position;
  114592. }
  114593. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114594. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114595. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  114596. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  114597. }
  114598. }
  114599. // Set sensibilities
  114600. if (this.autoCorrectCameraLimitsAndSensibility) {
  114601. var extend = maximumWorld.subtract(minimumWorld).length();
  114602. this._attachedCamera.panningSensibility = 5000 / extend;
  114603. this._attachedCamera.wheelPrecision = 100 / radius;
  114604. }
  114605. // transition to new radius
  114606. if (!this._radiusTransition) {
  114607. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114608. }
  114609. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  114610. _this.stopAllAnimations();
  114611. if (onAnimationEnd) {
  114612. onAnimationEnd();
  114613. }
  114614. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  114615. _this._attachedCamera.storeState();
  114616. }
  114617. });
  114618. if (animatable) {
  114619. this._animatables.push(animatable);
  114620. }
  114621. };
  114622. /**
  114623. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  114624. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  114625. * frustum width.
  114626. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  114627. * to fully enclose the mesh in the viewing frustum.
  114628. */
  114629. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  114630. var size = maximumWorld.subtract(minimumWorld);
  114631. var boxVectorGlobalDiagonal = size.length();
  114632. var frustumSlope = this._getFrustumSlope();
  114633. // Formula for setting distance
  114634. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  114635. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  114636. // Horizon distance
  114637. var radius = radiusWithoutFraming * this._radiusScale;
  114638. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  114639. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  114640. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  114641. var camera = this._attachedCamera;
  114642. if (!camera) {
  114643. return 0;
  114644. }
  114645. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114646. // Don't exceed the requested limit
  114647. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  114648. }
  114649. // Don't exceed the upper radius limit
  114650. if (camera.upperRadiusLimit) {
  114651. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  114652. }
  114653. return distance;
  114654. };
  114655. /**
  114656. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  114657. * is automatically returned to its default position (expected to be above ground plane).
  114658. */
  114659. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  114660. var _this = this;
  114661. if (this._elevationReturnTime < 0) {
  114662. return;
  114663. }
  114664. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  114665. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  114666. var limitBeta = Math.PI * 0.5;
  114667. // Bring the camera back up if below the ground plane
  114668. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  114669. this._betaIsAnimating = true;
  114670. //Transition to new position
  114671. this.stopAllAnimations();
  114672. if (!this._betaTransition) {
  114673. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114674. }
  114675. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  114676. _this._clearAnimationLocks();
  114677. _this.stopAllAnimations();
  114678. });
  114679. if (animatabe) {
  114680. this._animatables.push(animatabe);
  114681. }
  114682. }
  114683. };
  114684. /**
  114685. * Returns the frustum slope based on the canvas ratio and camera FOV
  114686. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  114687. */
  114688. FramingBehavior.prototype._getFrustumSlope = function () {
  114689. // Calculate the viewport ratio
  114690. // Aspect Ratio is Height/Width.
  114691. var camera = this._attachedCamera;
  114692. if (!camera) {
  114693. return BABYLON.Vector2.Zero();
  114694. }
  114695. var engine = camera.getScene().getEngine();
  114696. var aspectRatio = engine.getAspectRatio(camera);
  114697. // Camera FOV is the vertical field of view (top-bottom) in radians.
  114698. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  114699. var frustumSlopeY = Math.tan(camera.fov / 2);
  114700. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  114701. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  114702. // along the forward vector.
  114703. var frustumSlopeX = frustumSlopeY * aspectRatio;
  114704. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  114705. };
  114706. /**
  114707. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  114708. */
  114709. FramingBehavior.prototype._clearAnimationLocks = function () {
  114710. this._betaIsAnimating = false;
  114711. };
  114712. /**
  114713. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114714. */
  114715. FramingBehavior.prototype._applyUserInteraction = function () {
  114716. if (this.isUserIsMoving) {
  114717. this._lastInteractionTime = BABYLON.Tools.Now;
  114718. this.stopAllAnimations();
  114719. this._clearAnimationLocks();
  114720. }
  114721. };
  114722. /**
  114723. * Stops and removes all animations that have been applied to the camera
  114724. */
  114725. FramingBehavior.prototype.stopAllAnimations = function () {
  114726. if (this._attachedCamera) {
  114727. this._attachedCamera.animations = [];
  114728. }
  114729. while (this._animatables.length) {
  114730. if (this._animatables[0]) {
  114731. this._animatables[0].onAnimationEnd = null;
  114732. this._animatables[0].stop();
  114733. }
  114734. this._animatables.shift();
  114735. }
  114736. };
  114737. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  114738. /**
  114739. * Gets a value indicating if the user is moving the camera
  114740. */
  114741. get: function () {
  114742. if (!this._attachedCamera) {
  114743. return false;
  114744. }
  114745. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114746. this._attachedCamera.inertialBetaOffset !== 0 ||
  114747. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114748. this._attachedCamera.inertialPanningX !== 0 ||
  114749. this._attachedCamera.inertialPanningY !== 0 ||
  114750. this._isPointerDown;
  114751. },
  114752. enumerable: true,
  114753. configurable: true
  114754. });
  114755. /**
  114756. * The easing function used by animations
  114757. */
  114758. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  114759. /**
  114760. * The easing mode used by animations
  114761. */
  114762. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  114763. // Statics
  114764. /**
  114765. * The camera can move all the way towards the mesh.
  114766. */
  114767. FramingBehavior.IgnoreBoundsSizeMode = 0;
  114768. /**
  114769. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  114770. */
  114771. FramingBehavior.FitFrustumSidesMode = 1;
  114772. return FramingBehavior;
  114773. }());
  114774. BABYLON.FramingBehavior = FramingBehavior;
  114775. })(BABYLON || (BABYLON = {}));
  114776. //# sourceMappingURL=babylon.framingBehavior.js.map
  114777. var BABYLON;
  114778. (function (BABYLON) {
  114779. /**
  114780. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  114781. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  114782. */
  114783. var BouncingBehavior = /** @class */ (function () {
  114784. function BouncingBehavior() {
  114785. /**
  114786. * The duration of the animation, in milliseconds
  114787. */
  114788. this.transitionDuration = 450;
  114789. /**
  114790. * Length of the distance animated by the transition when lower radius is reached
  114791. */
  114792. this.lowerRadiusTransitionRange = 2;
  114793. /**
  114794. * Length of the distance animated by the transition when upper radius is reached
  114795. */
  114796. this.upperRadiusTransitionRange = -2;
  114797. this._autoTransitionRange = false;
  114798. // Animations
  114799. this._radiusIsAnimating = false;
  114800. this._radiusBounceTransition = null;
  114801. this._animatables = new Array();
  114802. }
  114803. Object.defineProperty(BouncingBehavior.prototype, "name", {
  114804. /**
  114805. * Gets the name of the behavior.
  114806. */
  114807. get: function () {
  114808. return "Bouncing";
  114809. },
  114810. enumerable: true,
  114811. configurable: true
  114812. });
  114813. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  114814. /**
  114815. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114816. */
  114817. get: function () {
  114818. return this._autoTransitionRange;
  114819. },
  114820. /**
  114821. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114822. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  114823. */
  114824. set: function (value) {
  114825. var _this = this;
  114826. if (this._autoTransitionRange === value) {
  114827. return;
  114828. }
  114829. this._autoTransitionRange = value;
  114830. var camera = this._attachedCamera;
  114831. if (!camera) {
  114832. return;
  114833. }
  114834. if (value) {
  114835. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114836. if (!mesh) {
  114837. return;
  114838. }
  114839. mesh.computeWorldMatrix(true);
  114840. var diagonal = mesh.getBoundingInfo().diagonalLength;
  114841. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  114842. _this.upperRadiusTransitionRange = diagonal * 0.05;
  114843. });
  114844. }
  114845. else if (this._onMeshTargetChangedObserver) {
  114846. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114847. }
  114848. },
  114849. enumerable: true,
  114850. configurable: true
  114851. });
  114852. /**
  114853. * Initializes the behavior.
  114854. */
  114855. BouncingBehavior.prototype.init = function () {
  114856. // Do notihng
  114857. };
  114858. /**
  114859. * Attaches the behavior to its arc rotate camera.
  114860. * @param camera Defines the camera to attach the behavior to
  114861. */
  114862. BouncingBehavior.prototype.attach = function (camera) {
  114863. var _this = this;
  114864. this._attachedCamera = camera;
  114865. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114866. if (!_this._attachedCamera) {
  114867. return;
  114868. }
  114869. // Add the bounce animation to the lower radius limit
  114870. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  114871. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  114872. }
  114873. // Add the bounce animation to the upper radius limit
  114874. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  114875. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  114876. }
  114877. });
  114878. };
  114879. /**
  114880. * Detaches the behavior from its current arc rotate camera.
  114881. */
  114882. BouncingBehavior.prototype.detach = function () {
  114883. if (!this._attachedCamera) {
  114884. return;
  114885. }
  114886. if (this._onAfterCheckInputsObserver) {
  114887. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114888. }
  114889. if (this._onMeshTargetChangedObserver) {
  114890. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114891. }
  114892. this._attachedCamera = null;
  114893. };
  114894. /**
  114895. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  114896. * @param radiusLimit The limit to check against.
  114897. * @return Bool to indicate if at limit.
  114898. */
  114899. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  114900. if (!this._attachedCamera) {
  114901. return false;
  114902. }
  114903. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  114904. return true;
  114905. }
  114906. return false;
  114907. };
  114908. /**
  114909. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  114910. * @param radiusDelta The delta by which to animate to. Can be negative.
  114911. */
  114912. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  114913. var _this = this;
  114914. if (!this._attachedCamera) {
  114915. return;
  114916. }
  114917. if (!this._radiusBounceTransition) {
  114918. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  114919. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  114920. }
  114921. // Prevent zoom until bounce has completed
  114922. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  114923. this._attachedCamera.wheelPrecision = Infinity;
  114924. this._attachedCamera.inertialRadiusOffset = 0;
  114925. // Animate to the radius limit
  114926. this.stopAllAnimations();
  114927. this._radiusIsAnimating = true;
  114928. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  114929. if (animatable) {
  114930. this._animatables.push(animatable);
  114931. }
  114932. };
  114933. /**
  114934. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  114935. */
  114936. BouncingBehavior.prototype._clearAnimationLocks = function () {
  114937. this._radiusIsAnimating = false;
  114938. if (this._attachedCamera) {
  114939. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  114940. }
  114941. };
  114942. /**
  114943. * Stops and removes all animations that have been applied to the camera
  114944. */
  114945. BouncingBehavior.prototype.stopAllAnimations = function () {
  114946. if (this._attachedCamera) {
  114947. this._attachedCamera.animations = [];
  114948. }
  114949. while (this._animatables.length) {
  114950. this._animatables[0].onAnimationEnd = null;
  114951. this._animatables[0].stop();
  114952. this._animatables.shift();
  114953. }
  114954. };
  114955. /**
  114956. * The easing function used by animations
  114957. */
  114958. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  114959. /**
  114960. * The easing mode used by animations
  114961. */
  114962. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  114963. return BouncingBehavior;
  114964. }());
  114965. BABYLON.BouncingBehavior = BouncingBehavior;
  114966. })(BABYLON || (BABYLON = {}));
  114967. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  114968. var BABYLON;
  114969. (function (BABYLON) {
  114970. /**
  114971. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  114972. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  114973. */
  114974. var AutoRotationBehavior = /** @class */ (function () {
  114975. function AutoRotationBehavior() {
  114976. this._zoomStopsAnimation = false;
  114977. this._idleRotationSpeed = 0.05;
  114978. this._idleRotationWaitTime = 2000;
  114979. this._idleRotationSpinupTime = 2000;
  114980. this._isPointerDown = false;
  114981. this._lastFrameTime = null;
  114982. this._lastInteractionTime = -Infinity;
  114983. this._cameraRotationSpeed = 0;
  114984. this._lastFrameRadius = 0;
  114985. }
  114986. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  114987. /**
  114988. * Gets the name of the behavior.
  114989. */
  114990. get: function () {
  114991. return "AutoRotation";
  114992. },
  114993. enumerable: true,
  114994. configurable: true
  114995. });
  114996. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  114997. /**
  114998. * Gets the flag that indicates if user zooming should stop animation.
  114999. */
  115000. get: function () {
  115001. return this._zoomStopsAnimation;
  115002. },
  115003. /**
  115004. * Sets the flag that indicates if user zooming should stop animation.
  115005. */
  115006. set: function (flag) {
  115007. this._zoomStopsAnimation = flag;
  115008. },
  115009. enumerable: true,
  115010. configurable: true
  115011. });
  115012. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  115013. /**
  115014. * Gets the default speed at which the camera rotates around the model.
  115015. */
  115016. get: function () {
  115017. return this._idleRotationSpeed;
  115018. },
  115019. /**
  115020. * Sets the default speed at which the camera rotates around the model.
  115021. */
  115022. set: function (speed) {
  115023. this._idleRotationSpeed = speed;
  115024. },
  115025. enumerable: true,
  115026. configurable: true
  115027. });
  115028. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  115029. /**
  115030. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  115031. */
  115032. get: function () {
  115033. return this._idleRotationWaitTime;
  115034. },
  115035. /**
  115036. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  115037. */
  115038. set: function (time) {
  115039. this._idleRotationWaitTime = time;
  115040. },
  115041. enumerable: true,
  115042. configurable: true
  115043. });
  115044. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  115045. /**
  115046. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115047. */
  115048. get: function () {
  115049. return this._idleRotationSpinupTime;
  115050. },
  115051. /**
  115052. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115053. */
  115054. set: function (time) {
  115055. this._idleRotationSpinupTime = time;
  115056. },
  115057. enumerable: true,
  115058. configurable: true
  115059. });
  115060. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  115061. /**
  115062. * Gets a value indicating if the camera is currently rotating because of this behavior
  115063. */
  115064. get: function () {
  115065. return Math.abs(this._cameraRotationSpeed) > 0;
  115066. },
  115067. enumerable: true,
  115068. configurable: true
  115069. });
  115070. /**
  115071. * Initializes the behavior.
  115072. */
  115073. AutoRotationBehavior.prototype.init = function () {
  115074. // Do notihng
  115075. };
  115076. /**
  115077. * Attaches the behavior to its arc rotate camera.
  115078. * @param camera Defines the camera to attach the behavior to
  115079. */
  115080. AutoRotationBehavior.prototype.attach = function (camera) {
  115081. var _this = this;
  115082. this._attachedCamera = camera;
  115083. var scene = this._attachedCamera.getScene();
  115084. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  115085. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  115086. _this._isPointerDown = true;
  115087. return;
  115088. }
  115089. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  115090. _this._isPointerDown = false;
  115091. }
  115092. });
  115093. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115094. var now = BABYLON.Tools.Now;
  115095. var dt = 0;
  115096. if (_this._lastFrameTime != null) {
  115097. dt = now - _this._lastFrameTime;
  115098. }
  115099. _this._lastFrameTime = now;
  115100. // Stop the animation if there is user interaction and the animation should stop for this interaction
  115101. _this._applyUserInteraction();
  115102. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  115103. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  115104. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  115105. // Step camera rotation by rotation speed
  115106. if (_this._attachedCamera) {
  115107. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  115108. }
  115109. });
  115110. };
  115111. /**
  115112. * Detaches the behavior from its current arc rotate camera.
  115113. */
  115114. AutoRotationBehavior.prototype.detach = function () {
  115115. if (!this._attachedCamera) {
  115116. return;
  115117. }
  115118. var scene = this._attachedCamera.getScene();
  115119. if (this._onPrePointerObservableObserver) {
  115120. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  115121. }
  115122. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115123. this._attachedCamera = null;
  115124. };
  115125. /**
  115126. * Returns true if user is scrolling.
  115127. * @return true if user is scrolling.
  115128. */
  115129. AutoRotationBehavior.prototype._userIsZooming = function () {
  115130. if (!this._attachedCamera) {
  115131. return false;
  115132. }
  115133. return this._attachedCamera.inertialRadiusOffset !== 0;
  115134. };
  115135. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  115136. if (!this._attachedCamera) {
  115137. return false;
  115138. }
  115139. var zoomHasHitLimit = false;
  115140. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  115141. zoomHasHitLimit = true;
  115142. }
  115143. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  115144. this._lastFrameRadius = this._attachedCamera.radius;
  115145. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  115146. };
  115147. /**
  115148. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  115149. */
  115150. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  115151. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  115152. this._lastInteractionTime = BABYLON.Tools.Now;
  115153. }
  115154. };
  115155. // Tools
  115156. AutoRotationBehavior.prototype._userIsMoving = function () {
  115157. if (!this._attachedCamera) {
  115158. return false;
  115159. }
  115160. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  115161. this._attachedCamera.inertialBetaOffset !== 0 ||
  115162. this._attachedCamera.inertialRadiusOffset !== 0 ||
  115163. this._attachedCamera.inertialPanningX !== 0 ||
  115164. this._attachedCamera.inertialPanningY !== 0 ||
  115165. this._isPointerDown;
  115166. };
  115167. return AutoRotationBehavior;
  115168. }());
  115169. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  115170. })(BABYLON || (BABYLON = {}));
  115171. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  115172. var BABYLON;
  115173. (function (BABYLON) {
  115174. /**
  115175. * Options to create the null engine
  115176. */
  115177. var NullEngineOptions = /** @class */ (function () {
  115178. function NullEngineOptions() {
  115179. /**
  115180. * Render width (Default: 512)
  115181. */
  115182. this.renderWidth = 512;
  115183. /**
  115184. * Render height (Default: 256)
  115185. */
  115186. this.renderHeight = 256;
  115187. /**
  115188. * Texture size (Default: 512)
  115189. */
  115190. this.textureSize = 512;
  115191. /**
  115192. * If delta time between frames should be constant
  115193. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115194. */
  115195. this.deterministicLockstep = false;
  115196. /**
  115197. * Maximum about of steps between frames (Default: 4)
  115198. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115199. */
  115200. this.lockstepMaxSteps = 4;
  115201. }
  115202. return NullEngineOptions;
  115203. }());
  115204. BABYLON.NullEngineOptions = NullEngineOptions;
  115205. /**
  115206. * The null engine class provides support for headless version of babylon.js.
  115207. * This can be used in server side scenario or for testing purposes
  115208. */
  115209. var NullEngine = /** @class */ (function (_super) {
  115210. __extends(NullEngine, _super);
  115211. function NullEngine(options) {
  115212. if (options === void 0) { options = new NullEngineOptions(); }
  115213. var _this = _super.call(this, null) || this;
  115214. if (options.deterministicLockstep === undefined) {
  115215. options.deterministicLockstep = false;
  115216. }
  115217. if (options.lockstepMaxSteps === undefined) {
  115218. options.lockstepMaxSteps = 4;
  115219. }
  115220. _this._options = options;
  115221. // Init caps
  115222. // We consider we are on a webgl1 capable device
  115223. _this._caps = new BABYLON.EngineCapabilities();
  115224. _this._caps.maxTexturesImageUnits = 16;
  115225. _this._caps.maxVertexTextureImageUnits = 16;
  115226. _this._caps.maxTextureSize = 512;
  115227. _this._caps.maxCubemapTextureSize = 512;
  115228. _this._caps.maxRenderTextureSize = 512;
  115229. _this._caps.maxVertexAttribs = 16;
  115230. _this._caps.maxVaryingVectors = 16;
  115231. _this._caps.maxFragmentUniformVectors = 16;
  115232. _this._caps.maxVertexUniformVectors = 16;
  115233. // Extensions
  115234. _this._caps.standardDerivatives = false;
  115235. _this._caps.astc = null;
  115236. _this._caps.s3tc = null;
  115237. _this._caps.pvrtc = null;
  115238. _this._caps.etc1 = null;
  115239. _this._caps.etc2 = null;
  115240. _this._caps.textureAnisotropicFilterExtension = null;
  115241. _this._caps.maxAnisotropy = 0;
  115242. _this._caps.uintIndices = false;
  115243. _this._caps.fragmentDepthSupported = false;
  115244. _this._caps.highPrecisionShaderSupported = true;
  115245. _this._caps.colorBufferFloat = false;
  115246. _this._caps.textureFloat = false;
  115247. _this._caps.textureFloatLinearFiltering = false;
  115248. _this._caps.textureFloatRender = false;
  115249. _this._caps.textureHalfFloat = false;
  115250. _this._caps.textureHalfFloatLinearFiltering = false;
  115251. _this._caps.textureHalfFloatRender = false;
  115252. _this._caps.textureLOD = false;
  115253. _this._caps.drawBuffersExtension = false;
  115254. _this._caps.depthTextureExtension = false;
  115255. _this._caps.vertexArrayObject = false;
  115256. _this._caps.instancedArrays = false;
  115257. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  115258. // Wrappers
  115259. if (typeof URL === "undefined") {
  115260. URL = {
  115261. createObjectURL: function () { },
  115262. revokeObjectURL: function () { }
  115263. };
  115264. }
  115265. if (typeof Blob === "undefined") {
  115266. Blob = function () { };
  115267. }
  115268. return _this;
  115269. }
  115270. /**
  115271. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115272. */
  115273. NullEngine.prototype.isDeterministicLockStep = function () {
  115274. return this._options.deterministicLockstep;
  115275. };
  115276. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  115277. NullEngine.prototype.getLockstepMaxSteps = function () {
  115278. return this._options.lockstepMaxSteps;
  115279. };
  115280. /**
  115281. * Sets hardware scaling, used to save performance if needed
  115282. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  115283. */
  115284. NullEngine.prototype.getHardwareScalingLevel = function () {
  115285. return 1.0;
  115286. };
  115287. NullEngine.prototype.createVertexBuffer = function (vertices) {
  115288. return {
  115289. capacity: 0,
  115290. references: 1,
  115291. is32Bits: false
  115292. };
  115293. };
  115294. NullEngine.prototype.createIndexBuffer = function (indices) {
  115295. return {
  115296. capacity: 0,
  115297. references: 1,
  115298. is32Bits: false
  115299. };
  115300. };
  115301. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  115302. if (stencil === void 0) { stencil = false; }
  115303. };
  115304. NullEngine.prototype.getRenderWidth = function (useScreen) {
  115305. if (useScreen === void 0) { useScreen = false; }
  115306. if (!useScreen && this._currentRenderTarget) {
  115307. return this._currentRenderTarget.width;
  115308. }
  115309. return this._options.renderWidth;
  115310. };
  115311. NullEngine.prototype.getRenderHeight = function (useScreen) {
  115312. if (useScreen === void 0) { useScreen = false; }
  115313. if (!useScreen && this._currentRenderTarget) {
  115314. return this._currentRenderTarget.height;
  115315. }
  115316. return this._options.renderHeight;
  115317. };
  115318. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  115319. this._cachedViewport = viewport;
  115320. };
  115321. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  115322. return {
  115323. transformFeedback: null,
  115324. __SPECTOR_rebuildProgram: null,
  115325. isParallelCompiled: false
  115326. };
  115327. };
  115328. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  115329. return [];
  115330. };
  115331. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  115332. return [];
  115333. };
  115334. NullEngine.prototype.bindSamplers = function (effect) {
  115335. this._currentEffect = null;
  115336. };
  115337. NullEngine.prototype.enableEffect = function (effect) {
  115338. this._currentEffect = effect;
  115339. if (effect.onBind) {
  115340. effect.onBind(effect);
  115341. }
  115342. if (effect._onBindObservable) {
  115343. effect._onBindObservable.notifyObservers(effect);
  115344. }
  115345. };
  115346. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  115347. if (zOffset === void 0) { zOffset = 0; }
  115348. if (reverseSide === void 0) { reverseSide = false; }
  115349. };
  115350. NullEngine.prototype.setIntArray = function (uniform, array) {
  115351. };
  115352. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  115353. };
  115354. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  115355. };
  115356. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  115357. };
  115358. NullEngine.prototype.setFloatArray = function (uniform, array) {
  115359. };
  115360. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  115361. };
  115362. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  115363. };
  115364. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  115365. };
  115366. NullEngine.prototype.setArray = function (uniform, array) {
  115367. };
  115368. NullEngine.prototype.setArray2 = function (uniform, array) {
  115369. };
  115370. NullEngine.prototype.setArray3 = function (uniform, array) {
  115371. };
  115372. NullEngine.prototype.setArray4 = function (uniform, array) {
  115373. };
  115374. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  115375. };
  115376. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  115377. };
  115378. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  115379. };
  115380. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  115381. };
  115382. NullEngine.prototype.setFloat = function (uniform, value) {
  115383. };
  115384. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  115385. };
  115386. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  115387. };
  115388. NullEngine.prototype.setBool = function (uniform, bool) {
  115389. };
  115390. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  115391. };
  115392. NullEngine.prototype.setColor3 = function (uniform, color3) {
  115393. };
  115394. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  115395. };
  115396. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  115397. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  115398. if (this._alphaMode === mode) {
  115399. return;
  115400. }
  115401. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  115402. if (!noDepthWriteChange) {
  115403. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  115404. }
  115405. this._alphaMode = mode;
  115406. };
  115407. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  115408. };
  115409. NullEngine.prototype.wipeCaches = function (bruteForce) {
  115410. if (this.preventCacheWipeBetweenFrames) {
  115411. return;
  115412. }
  115413. this.resetTextureCache();
  115414. this._currentEffect = null;
  115415. if (bruteForce) {
  115416. this._currentProgram = null;
  115417. this._stencilState.reset();
  115418. this._depthCullingState.reset();
  115419. this._alphaState.reset();
  115420. }
  115421. this._cachedVertexBuffers = null;
  115422. this._cachedIndexBuffer = null;
  115423. this._cachedEffectForVertexBuffers = null;
  115424. };
  115425. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  115426. };
  115427. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  115428. };
  115429. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  115430. };
  115431. /** @hidden */
  115432. NullEngine.prototype._createTexture = function () {
  115433. return {};
  115434. };
  115435. /** @hidden */
  115436. NullEngine.prototype._releaseTexture = function (texture) {
  115437. };
  115438. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  115439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  115440. if (onLoad === void 0) { onLoad = null; }
  115441. if (onError === void 0) { onError = null; }
  115442. if (buffer === void 0) { buffer = null; }
  115443. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  115444. var url = String(urlArg);
  115445. texture.url = url;
  115446. texture.generateMipMaps = !noMipmap;
  115447. texture.samplingMode = samplingMode;
  115448. texture.invertY = invertY;
  115449. texture.baseWidth = this._options.textureSize;
  115450. texture.baseHeight = this._options.textureSize;
  115451. texture.width = this._options.textureSize;
  115452. texture.height = this._options.textureSize;
  115453. if (format) {
  115454. texture.format = format;
  115455. }
  115456. texture.isReady = true;
  115457. if (onLoad) {
  115458. onLoad();
  115459. }
  115460. this._internalTexturesCache.push(texture);
  115461. return texture;
  115462. };
  115463. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  115464. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  115465. if (options !== undefined && typeof options === "object") {
  115466. fullOptions.generateMipMaps = options.generateMipMaps;
  115467. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  115468. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  115469. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  115470. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  115471. }
  115472. else {
  115473. fullOptions.generateMipMaps = options;
  115474. fullOptions.generateDepthBuffer = true;
  115475. fullOptions.generateStencilBuffer = false;
  115476. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  115477. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  115478. }
  115479. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  115480. var width = size.width || size;
  115481. var height = size.height || size;
  115482. texture._depthStencilBuffer = {};
  115483. texture._framebuffer = {};
  115484. texture.baseWidth = width;
  115485. texture.baseHeight = height;
  115486. texture.width = width;
  115487. texture.height = height;
  115488. texture.isReady = true;
  115489. texture.samples = 1;
  115490. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  115491. texture.samplingMode = fullOptions.samplingMode;
  115492. texture.type = fullOptions.type;
  115493. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  115494. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  115495. this._internalTexturesCache.push(texture);
  115496. return texture;
  115497. };
  115498. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  115499. texture.samplingMode = samplingMode;
  115500. };
  115501. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  115502. if (this._currentRenderTarget) {
  115503. this.unBindFramebuffer(this._currentRenderTarget);
  115504. }
  115505. this._currentRenderTarget = texture;
  115506. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  115507. if (this._cachedViewport && !forceFullscreenViewport) {
  115508. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  115509. }
  115510. };
  115511. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  115512. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  115513. this._currentRenderTarget = null;
  115514. if (onBeforeUnbind) {
  115515. if (texture._MSAAFramebuffer) {
  115516. this._currentFramebuffer = texture._framebuffer;
  115517. }
  115518. onBeforeUnbind();
  115519. }
  115520. this._currentFramebuffer = null;
  115521. };
  115522. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  115523. var vbo = {
  115524. capacity: 1,
  115525. references: 1,
  115526. is32Bits: false
  115527. };
  115528. return vbo;
  115529. };
  115530. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  115531. if (premulAlpha === void 0) { premulAlpha = false; }
  115532. };
  115533. NullEngine.prototype.areAllEffectsReady = function () {
  115534. return true;
  115535. };
  115536. /**
  115537. * @hidden
  115538. * Get the current error code of the webGL context
  115539. * @returns the error code
  115540. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  115541. */
  115542. NullEngine.prototype.getError = function () {
  115543. return 0;
  115544. };
  115545. /** @hidden */
  115546. NullEngine.prototype._getUnpackAlignement = function () {
  115547. return 1;
  115548. };
  115549. /** @hidden */
  115550. NullEngine.prototype._unpackFlipY = function (value) {
  115551. };
  115552. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  115553. if (offset === void 0) { offset = 0; }
  115554. };
  115555. /**
  115556. * Updates a dynamic vertex buffer.
  115557. * @param vertexBuffer the vertex buffer to update
  115558. * @param data the data used to update the vertex buffer
  115559. * @param byteOffset the byte offset of the data (optional)
  115560. * @param byteLength the byte length of the data (optional)
  115561. */
  115562. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  115563. };
  115564. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  115565. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  115566. this._boundTexturesCache[this._activeChannel] = texture;
  115567. return true;
  115568. }
  115569. return false;
  115570. };
  115571. /** @hidden */
  115572. NullEngine.prototype._bindTexture = function (channel, texture) {
  115573. if (channel < 0) {
  115574. return;
  115575. }
  115576. this._bindTextureDirectly(0, texture);
  115577. };
  115578. /** @hidden */
  115579. NullEngine.prototype._releaseBuffer = function (buffer) {
  115580. buffer.references--;
  115581. if (buffer.references === 0) {
  115582. return true;
  115583. }
  115584. return false;
  115585. };
  115586. NullEngine.prototype.releaseEffects = function () {
  115587. };
  115588. NullEngine.prototype.displayLoadingUI = function () {
  115589. };
  115590. NullEngine.prototype.hideLoadingUI = function () {
  115591. };
  115592. /** @hidden */
  115593. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  115594. if (faceIndex === void 0) { faceIndex = 0; }
  115595. if (lod === void 0) { lod = 0; }
  115596. };
  115597. /** @hidden */
  115598. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  115599. if (faceIndex === void 0) { faceIndex = 0; }
  115600. if (lod === void 0) { lod = 0; }
  115601. };
  115602. /** @hidden */
  115603. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  115604. if (faceIndex === void 0) { faceIndex = 0; }
  115605. if (lod === void 0) { lod = 0; }
  115606. };
  115607. /** @hidden */
  115608. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  115609. if (faceIndex === void 0) { faceIndex = 0; }
  115610. if (lod === void 0) { lod = 0; }
  115611. };
  115612. return NullEngine;
  115613. }(BABYLON.Engine));
  115614. BABYLON.NullEngine = NullEngine;
  115615. })(BABYLON || (BABYLON = {}));
  115616. //# sourceMappingURL=babylon.nullEngine.js.map
  115617. var BABYLON;
  115618. (function (BABYLON) {
  115619. /**
  115620. * This class can be used to get instrumentation data from a Babylon engine
  115621. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115622. */
  115623. var EngineInstrumentation = /** @class */ (function () {
  115624. /**
  115625. * Instantiates a new engine instrumentation.
  115626. * This class can be used to get instrumentation data from a Babylon engine
  115627. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115628. * @param engine Defines the engine to instrument
  115629. */
  115630. function EngineInstrumentation(
  115631. /**
  115632. * Define the instrumented engine.
  115633. */
  115634. engine) {
  115635. this.engine = engine;
  115636. this._captureGPUFrameTime = false;
  115637. this._gpuFrameTime = new BABYLON.PerfCounter();
  115638. this._captureShaderCompilationTime = false;
  115639. this._shaderCompilationTime = new BABYLON.PerfCounter();
  115640. // Observers
  115641. this._onBeginFrameObserver = null;
  115642. this._onEndFrameObserver = null;
  115643. this._onBeforeShaderCompilationObserver = null;
  115644. this._onAfterShaderCompilationObserver = null;
  115645. }
  115646. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  115647. // Properties
  115648. /**
  115649. * Gets the perf counter used for GPU frame time
  115650. */
  115651. get: function () {
  115652. return this._gpuFrameTime;
  115653. },
  115654. enumerable: true,
  115655. configurable: true
  115656. });
  115657. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  115658. /**
  115659. * Gets the GPU frame time capture status
  115660. */
  115661. get: function () {
  115662. return this._captureGPUFrameTime;
  115663. },
  115664. /**
  115665. * Enable or disable the GPU frame time capture
  115666. */
  115667. set: function (value) {
  115668. var _this = this;
  115669. if (value === this._captureGPUFrameTime) {
  115670. return;
  115671. }
  115672. this._captureGPUFrameTime = value;
  115673. if (value) {
  115674. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  115675. if (!_this._gpuFrameTimeToken) {
  115676. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  115677. }
  115678. });
  115679. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  115680. if (!_this._gpuFrameTimeToken) {
  115681. return;
  115682. }
  115683. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  115684. if (time > -1) {
  115685. _this._gpuFrameTimeToken = null;
  115686. _this._gpuFrameTime.fetchNewFrame();
  115687. _this._gpuFrameTime.addCount(time, true);
  115688. }
  115689. });
  115690. }
  115691. else {
  115692. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115693. this._onBeginFrameObserver = null;
  115694. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115695. this._onEndFrameObserver = null;
  115696. }
  115697. },
  115698. enumerable: true,
  115699. configurable: true
  115700. });
  115701. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  115702. /**
  115703. * Gets the perf counter used for shader compilation time
  115704. */
  115705. get: function () {
  115706. return this._shaderCompilationTime;
  115707. },
  115708. enumerable: true,
  115709. configurable: true
  115710. });
  115711. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  115712. /**
  115713. * Gets the shader compilation time capture status
  115714. */
  115715. get: function () {
  115716. return this._captureShaderCompilationTime;
  115717. },
  115718. /**
  115719. * Enable or disable the shader compilation time capture
  115720. */
  115721. set: function (value) {
  115722. var _this = this;
  115723. if (value === this._captureShaderCompilationTime) {
  115724. return;
  115725. }
  115726. this._captureShaderCompilationTime = value;
  115727. if (value) {
  115728. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  115729. _this._shaderCompilationTime.fetchNewFrame();
  115730. _this._shaderCompilationTime.beginMonitoring();
  115731. });
  115732. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  115733. _this._shaderCompilationTime.endMonitoring();
  115734. });
  115735. }
  115736. else {
  115737. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115738. this._onBeforeShaderCompilationObserver = null;
  115739. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115740. this._onAfterShaderCompilationObserver = null;
  115741. }
  115742. },
  115743. enumerable: true,
  115744. configurable: true
  115745. });
  115746. /**
  115747. * Dispose and release associated resources.
  115748. */
  115749. EngineInstrumentation.prototype.dispose = function () {
  115750. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115751. this._onBeginFrameObserver = null;
  115752. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115753. this._onEndFrameObserver = null;
  115754. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115755. this._onBeforeShaderCompilationObserver = null;
  115756. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115757. this._onAfterShaderCompilationObserver = null;
  115758. this.engine = null;
  115759. };
  115760. return EngineInstrumentation;
  115761. }());
  115762. BABYLON.EngineInstrumentation = EngineInstrumentation;
  115763. })(BABYLON || (BABYLON = {}));
  115764. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  115765. var BABYLON;
  115766. (function (BABYLON) {
  115767. /**
  115768. * This class can be used to get instrumentation data from a Babylon engine
  115769. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115770. */
  115771. var SceneInstrumentation = /** @class */ (function () {
  115772. /**
  115773. * Instantiates a new scene instrumentation.
  115774. * This class can be used to get instrumentation data from a Babylon engine
  115775. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115776. * @param scene Defines the scene to instrument
  115777. */
  115778. function SceneInstrumentation(
  115779. /**
  115780. * Defines the scene to instrument
  115781. */
  115782. scene) {
  115783. var _this = this;
  115784. this.scene = scene;
  115785. this._captureActiveMeshesEvaluationTime = false;
  115786. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  115787. this._captureRenderTargetsRenderTime = false;
  115788. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  115789. this._captureFrameTime = false;
  115790. this._frameTime = new BABYLON.PerfCounter();
  115791. this._captureRenderTime = false;
  115792. this._renderTime = new BABYLON.PerfCounter();
  115793. this._captureInterFrameTime = false;
  115794. this._interFrameTime = new BABYLON.PerfCounter();
  115795. this._captureParticlesRenderTime = false;
  115796. this._particlesRenderTime = new BABYLON.PerfCounter();
  115797. this._captureSpritesRenderTime = false;
  115798. this._spritesRenderTime = new BABYLON.PerfCounter();
  115799. this._capturePhysicsTime = false;
  115800. this._physicsTime = new BABYLON.PerfCounter();
  115801. this._captureAnimationsTime = false;
  115802. this._animationsTime = new BABYLON.PerfCounter();
  115803. this._captureCameraRenderTime = false;
  115804. this._cameraRenderTime = new BABYLON.PerfCounter();
  115805. // Observers
  115806. this._onBeforeActiveMeshesEvaluationObserver = null;
  115807. this._onAfterActiveMeshesEvaluationObserver = null;
  115808. this._onBeforeRenderTargetsRenderObserver = null;
  115809. this._onAfterRenderTargetsRenderObserver = null;
  115810. this._onAfterRenderObserver = null;
  115811. this._onBeforeDrawPhaseObserver = null;
  115812. this._onAfterDrawPhaseObserver = null;
  115813. this._onBeforeAnimationsObserver = null;
  115814. this._onBeforeParticlesRenderingObserver = null;
  115815. this._onAfterParticlesRenderingObserver = null;
  115816. this._onBeforeSpritesRenderingObserver = null;
  115817. this._onAfterSpritesRenderingObserver = null;
  115818. this._onBeforePhysicsObserver = null;
  115819. this._onAfterPhysicsObserver = null;
  115820. this._onAfterAnimationsObserver = null;
  115821. this._onBeforeCameraRenderObserver = null;
  115822. this._onAfterCameraRenderObserver = null;
  115823. // Before render
  115824. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  115825. if (_this._captureActiveMeshesEvaluationTime) {
  115826. _this._activeMeshesEvaluationTime.fetchNewFrame();
  115827. }
  115828. if (_this._captureRenderTargetsRenderTime) {
  115829. _this._renderTargetsRenderTime.fetchNewFrame();
  115830. }
  115831. if (_this._captureFrameTime) {
  115832. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  115833. _this._frameTime.beginMonitoring();
  115834. }
  115835. if (_this._captureInterFrameTime) {
  115836. _this._interFrameTime.endMonitoring();
  115837. }
  115838. if (_this._captureParticlesRenderTime) {
  115839. _this._particlesRenderTime.fetchNewFrame();
  115840. }
  115841. if (_this._captureSpritesRenderTime) {
  115842. _this._spritesRenderTime.fetchNewFrame();
  115843. }
  115844. if (_this._captureAnimationsTime) {
  115845. _this._animationsTime.beginMonitoring();
  115846. }
  115847. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  115848. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  115849. });
  115850. // After render
  115851. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  115852. if (_this._captureFrameTime) {
  115853. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  115854. _this._frameTime.endMonitoring();
  115855. }
  115856. if (_this._captureRenderTime) {
  115857. _this._renderTime.endMonitoring(false);
  115858. }
  115859. if (_this._captureInterFrameTime) {
  115860. _this._interFrameTime.beginMonitoring();
  115861. }
  115862. });
  115863. }
  115864. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  115865. // Properties
  115866. /**
  115867. * Gets the perf counter used for active meshes evaluation time
  115868. */
  115869. get: function () {
  115870. return this._activeMeshesEvaluationTime;
  115871. },
  115872. enumerable: true,
  115873. configurable: true
  115874. });
  115875. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  115876. /**
  115877. * Gets the active meshes evaluation time capture status
  115878. */
  115879. get: function () {
  115880. return this._captureActiveMeshesEvaluationTime;
  115881. },
  115882. /**
  115883. * Enable or disable the active meshes evaluation time capture
  115884. */
  115885. set: function (value) {
  115886. var _this = this;
  115887. if (value === this._captureActiveMeshesEvaluationTime) {
  115888. return;
  115889. }
  115890. this._captureActiveMeshesEvaluationTime = value;
  115891. if (value) {
  115892. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  115893. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  115894. _this._activeMeshesEvaluationTime.beginMonitoring();
  115895. });
  115896. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  115897. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  115898. _this._activeMeshesEvaluationTime.endMonitoring();
  115899. });
  115900. }
  115901. else {
  115902. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  115903. this._onBeforeActiveMeshesEvaluationObserver = null;
  115904. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  115905. this._onAfterActiveMeshesEvaluationObserver = null;
  115906. }
  115907. },
  115908. enumerable: true,
  115909. configurable: true
  115910. });
  115911. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  115912. /**
  115913. * Gets the perf counter used for render targets render time
  115914. */
  115915. get: function () {
  115916. return this._renderTargetsRenderTime;
  115917. },
  115918. enumerable: true,
  115919. configurable: true
  115920. });
  115921. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  115922. /**
  115923. * Gets the render targets render time capture status
  115924. */
  115925. get: function () {
  115926. return this._captureRenderTargetsRenderTime;
  115927. },
  115928. /**
  115929. * Enable or disable the render targets render time capture
  115930. */
  115931. set: function (value) {
  115932. var _this = this;
  115933. if (value === this._captureRenderTargetsRenderTime) {
  115934. return;
  115935. }
  115936. this._captureRenderTargetsRenderTime = value;
  115937. if (value) {
  115938. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  115939. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  115940. _this._renderTargetsRenderTime.beginMonitoring();
  115941. });
  115942. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  115943. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  115944. _this._renderTargetsRenderTime.endMonitoring(false);
  115945. });
  115946. }
  115947. else {
  115948. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  115949. this._onBeforeRenderTargetsRenderObserver = null;
  115950. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  115951. this._onAfterRenderTargetsRenderObserver = null;
  115952. }
  115953. },
  115954. enumerable: true,
  115955. configurable: true
  115956. });
  115957. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  115958. /**
  115959. * Gets the perf counter used for particles render time
  115960. */
  115961. get: function () {
  115962. return this._particlesRenderTime;
  115963. },
  115964. enumerable: true,
  115965. configurable: true
  115966. });
  115967. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  115968. /**
  115969. * Gets the particles render time capture status
  115970. */
  115971. get: function () {
  115972. return this._captureParticlesRenderTime;
  115973. },
  115974. /**
  115975. * Enable or disable the particles render time capture
  115976. */
  115977. set: function (value) {
  115978. var _this = this;
  115979. if (value === this._captureParticlesRenderTime) {
  115980. return;
  115981. }
  115982. this._captureParticlesRenderTime = value;
  115983. if (value) {
  115984. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  115985. BABYLON.Tools.StartPerformanceCounter("Particles");
  115986. _this._particlesRenderTime.beginMonitoring();
  115987. });
  115988. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  115989. BABYLON.Tools.EndPerformanceCounter("Particles");
  115990. _this._particlesRenderTime.endMonitoring(false);
  115991. });
  115992. }
  115993. else {
  115994. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  115995. this._onBeforeParticlesRenderingObserver = null;
  115996. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  115997. this._onAfterParticlesRenderingObserver = null;
  115998. }
  115999. },
  116000. enumerable: true,
  116001. configurable: true
  116002. });
  116003. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  116004. /**
  116005. * Gets the perf counter used for sprites render time
  116006. */
  116007. get: function () {
  116008. return this._spritesRenderTime;
  116009. },
  116010. enumerable: true,
  116011. configurable: true
  116012. });
  116013. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  116014. /**
  116015. * Gets the sprites render time capture status
  116016. */
  116017. get: function () {
  116018. return this._captureSpritesRenderTime;
  116019. },
  116020. /**
  116021. * Enable or disable the sprites render time capture
  116022. */
  116023. set: function (value) {
  116024. var _this = this;
  116025. if (value === this._captureSpritesRenderTime) {
  116026. return;
  116027. }
  116028. this._captureSpritesRenderTime = value;
  116029. if (!this.scene.spriteManagers) {
  116030. return;
  116031. }
  116032. if (value) {
  116033. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  116034. BABYLON.Tools.StartPerformanceCounter("Sprites");
  116035. _this._spritesRenderTime.beginMonitoring();
  116036. });
  116037. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  116038. BABYLON.Tools.EndPerformanceCounter("Sprites");
  116039. _this._spritesRenderTime.endMonitoring(false);
  116040. });
  116041. }
  116042. else {
  116043. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  116044. this._onBeforeSpritesRenderingObserver = null;
  116045. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  116046. this._onAfterSpritesRenderingObserver = null;
  116047. }
  116048. },
  116049. enumerable: true,
  116050. configurable: true
  116051. });
  116052. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  116053. /**
  116054. * Gets the perf counter used for physics time
  116055. */
  116056. get: function () {
  116057. return this._physicsTime;
  116058. },
  116059. enumerable: true,
  116060. configurable: true
  116061. });
  116062. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  116063. /**
  116064. * Gets the physics time capture status
  116065. */
  116066. get: function () {
  116067. return this._capturePhysicsTime;
  116068. },
  116069. /**
  116070. * Enable or disable the physics time capture
  116071. */
  116072. set: function (value) {
  116073. var _this = this;
  116074. if (value === this._capturePhysicsTime) {
  116075. return;
  116076. }
  116077. if (!this.scene.onBeforePhysicsObservable) {
  116078. return;
  116079. }
  116080. this._capturePhysicsTime = value;
  116081. if (value) {
  116082. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  116083. BABYLON.Tools.StartPerformanceCounter("Physics");
  116084. _this._physicsTime.beginMonitoring();
  116085. });
  116086. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  116087. BABYLON.Tools.EndPerformanceCounter("Physics");
  116088. _this._physicsTime.endMonitoring();
  116089. });
  116090. }
  116091. else {
  116092. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116093. this._onBeforePhysicsObserver = null;
  116094. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116095. this._onAfterPhysicsObserver = null;
  116096. }
  116097. },
  116098. enumerable: true,
  116099. configurable: true
  116100. });
  116101. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  116102. /**
  116103. * Gets the perf counter used for animations time
  116104. */
  116105. get: function () {
  116106. return this._animationsTime;
  116107. },
  116108. enumerable: true,
  116109. configurable: true
  116110. });
  116111. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  116112. /**
  116113. * Gets the animations time capture status
  116114. */
  116115. get: function () {
  116116. return this._captureAnimationsTime;
  116117. },
  116118. /**
  116119. * Enable or disable the animations time capture
  116120. */
  116121. set: function (value) {
  116122. var _this = this;
  116123. if (value === this._captureAnimationsTime) {
  116124. return;
  116125. }
  116126. this._captureAnimationsTime = value;
  116127. if (value) {
  116128. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  116129. _this._animationsTime.endMonitoring();
  116130. });
  116131. }
  116132. else {
  116133. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116134. this._onAfterAnimationsObserver = null;
  116135. }
  116136. },
  116137. enumerable: true,
  116138. configurable: true
  116139. });
  116140. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  116141. /**
  116142. * Gets the perf counter used for frame time capture
  116143. */
  116144. get: function () {
  116145. return this._frameTime;
  116146. },
  116147. enumerable: true,
  116148. configurable: true
  116149. });
  116150. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  116151. /**
  116152. * Gets the frame time capture status
  116153. */
  116154. get: function () {
  116155. return this._captureFrameTime;
  116156. },
  116157. /**
  116158. * Enable or disable the frame time capture
  116159. */
  116160. set: function (value) {
  116161. this._captureFrameTime = value;
  116162. },
  116163. enumerable: true,
  116164. configurable: true
  116165. });
  116166. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  116167. /**
  116168. * Gets the perf counter used for inter-frames time capture
  116169. */
  116170. get: function () {
  116171. return this._interFrameTime;
  116172. },
  116173. enumerable: true,
  116174. configurable: true
  116175. });
  116176. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  116177. /**
  116178. * Gets the inter-frames time capture status
  116179. */
  116180. get: function () {
  116181. return this._captureInterFrameTime;
  116182. },
  116183. /**
  116184. * Enable or disable the inter-frames time capture
  116185. */
  116186. set: function (value) {
  116187. this._captureInterFrameTime = value;
  116188. },
  116189. enumerable: true,
  116190. configurable: true
  116191. });
  116192. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  116193. /**
  116194. * Gets the perf counter used for render time capture
  116195. */
  116196. get: function () {
  116197. return this._renderTime;
  116198. },
  116199. enumerable: true,
  116200. configurable: true
  116201. });
  116202. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  116203. /**
  116204. * Gets the render time capture status
  116205. */
  116206. get: function () {
  116207. return this._captureRenderTime;
  116208. },
  116209. /**
  116210. * Enable or disable the render time capture
  116211. */
  116212. set: function (value) {
  116213. var _this = this;
  116214. if (value === this._captureRenderTime) {
  116215. return;
  116216. }
  116217. this._captureRenderTime = value;
  116218. if (value) {
  116219. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  116220. _this._renderTime.beginMonitoring();
  116221. BABYLON.Tools.StartPerformanceCounter("Main render");
  116222. });
  116223. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  116224. _this._renderTime.endMonitoring(false);
  116225. BABYLON.Tools.EndPerformanceCounter("Main render");
  116226. });
  116227. }
  116228. else {
  116229. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116230. this._onBeforeDrawPhaseObserver = null;
  116231. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116232. this._onAfterDrawPhaseObserver = null;
  116233. }
  116234. },
  116235. enumerable: true,
  116236. configurable: true
  116237. });
  116238. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  116239. /**
  116240. * Gets the perf counter used for camera render time capture
  116241. */
  116242. get: function () {
  116243. return this._cameraRenderTime;
  116244. },
  116245. enumerable: true,
  116246. configurable: true
  116247. });
  116248. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  116249. /**
  116250. * Gets the camera render time capture status
  116251. */
  116252. get: function () {
  116253. return this._captureCameraRenderTime;
  116254. },
  116255. /**
  116256. * Enable or disable the camera render time capture
  116257. */
  116258. set: function (value) {
  116259. var _this = this;
  116260. if (value === this._captureCameraRenderTime) {
  116261. return;
  116262. }
  116263. this._captureCameraRenderTime = value;
  116264. if (value) {
  116265. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  116266. _this._cameraRenderTime.beginMonitoring();
  116267. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  116268. });
  116269. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  116270. _this._cameraRenderTime.endMonitoring(false);
  116271. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  116272. });
  116273. }
  116274. else {
  116275. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116276. this._onBeforeCameraRenderObserver = null;
  116277. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116278. this._onAfterCameraRenderObserver = null;
  116279. }
  116280. },
  116281. enumerable: true,
  116282. configurable: true
  116283. });
  116284. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  116285. /**
  116286. * Gets the perf counter used for draw calls
  116287. */
  116288. get: function () {
  116289. return this.scene.getEngine()._drawCalls;
  116290. },
  116291. enumerable: true,
  116292. configurable: true
  116293. });
  116294. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  116295. /**
  116296. * Gets the perf counter used for texture collisions
  116297. */
  116298. get: function () {
  116299. return this.scene.getEngine()._textureCollisions;
  116300. },
  116301. enumerable: true,
  116302. configurable: true
  116303. });
  116304. /**
  116305. * Dispose and release associated resources.
  116306. */
  116307. SceneInstrumentation.prototype.dispose = function () {
  116308. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  116309. this._onAfterRenderObserver = null;
  116310. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  116311. this._onBeforeActiveMeshesEvaluationObserver = null;
  116312. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  116313. this._onAfterActiveMeshesEvaluationObserver = null;
  116314. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  116315. this._onBeforeRenderTargetsRenderObserver = null;
  116316. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  116317. this._onAfterRenderTargetsRenderObserver = null;
  116318. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  116319. this._onBeforeAnimationsObserver = null;
  116320. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  116321. this._onBeforeParticlesRenderingObserver = null;
  116322. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  116323. this._onAfterParticlesRenderingObserver = null;
  116324. if (this._onBeforeSpritesRenderingObserver) {
  116325. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  116326. this._onBeforeSpritesRenderingObserver = null;
  116327. }
  116328. if (this._onAfterSpritesRenderingObserver) {
  116329. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  116330. this._onAfterSpritesRenderingObserver = null;
  116331. }
  116332. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116333. this._onBeforeDrawPhaseObserver = null;
  116334. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116335. this._onAfterDrawPhaseObserver = null;
  116336. if (this._onBeforePhysicsObserver) {
  116337. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116338. this._onBeforePhysicsObserver = null;
  116339. }
  116340. if (this._onAfterPhysicsObserver) {
  116341. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116342. this._onAfterPhysicsObserver = null;
  116343. }
  116344. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116345. this._onAfterAnimationsObserver = null;
  116346. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116347. this._onBeforeCameraRenderObserver = null;
  116348. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116349. this._onAfterCameraRenderObserver = null;
  116350. this.scene = null;
  116351. };
  116352. return SceneInstrumentation;
  116353. }());
  116354. BABYLON.SceneInstrumentation = SceneInstrumentation;
  116355. })(BABYLON || (BABYLON = {}));
  116356. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  116357. var BABYLON;
  116358. (function (BABYLON) {
  116359. /**
  116360. * @hidden
  116361. **/
  116362. var _TimeToken = /** @class */ (function () {
  116363. function _TimeToken() {
  116364. this._timeElapsedQueryEnded = false;
  116365. }
  116366. return _TimeToken;
  116367. }());
  116368. BABYLON._TimeToken = _TimeToken;
  116369. })(BABYLON || (BABYLON = {}));
  116370. //# sourceMappingURL=babylon.timeToken.js.map
  116371. var BABYLON;
  116372. (function (BABYLON) {
  116373. /**
  116374. * Background material defines definition.
  116375. * @hidden Mainly internal Use
  116376. */
  116377. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  116378. __extends(BackgroundMaterialDefines, _super);
  116379. /**
  116380. * Constructor of the defines.
  116381. */
  116382. function BackgroundMaterialDefines() {
  116383. var _this = _super.call(this) || this;
  116384. /**
  116385. * True if the diffuse texture is in use.
  116386. */
  116387. _this.DIFFUSE = false;
  116388. /**
  116389. * The direct UV channel to use.
  116390. */
  116391. _this.DIFFUSEDIRECTUV = 0;
  116392. /**
  116393. * True if the diffuse texture is in gamma space.
  116394. */
  116395. _this.GAMMADIFFUSE = false;
  116396. /**
  116397. * True if the diffuse texture has opacity in the alpha channel.
  116398. */
  116399. _this.DIFFUSEHASALPHA = false;
  116400. /**
  116401. * True if you want the material to fade to transparent at grazing angle.
  116402. */
  116403. _this.OPACITYFRESNEL = false;
  116404. /**
  116405. * True if an extra blur needs to be added in the reflection.
  116406. */
  116407. _this.REFLECTIONBLUR = false;
  116408. /**
  116409. * True if you want the material to fade to reflection at grazing angle.
  116410. */
  116411. _this.REFLECTIONFRESNEL = false;
  116412. /**
  116413. * True if you want the material to falloff as far as you move away from the scene center.
  116414. */
  116415. _this.REFLECTIONFALLOFF = false;
  116416. /**
  116417. * False if the current Webgl implementation does not support the texture lod extension.
  116418. */
  116419. _this.TEXTURELODSUPPORT = false;
  116420. /**
  116421. * True to ensure the data are premultiplied.
  116422. */
  116423. _this.PREMULTIPLYALPHA = false;
  116424. /**
  116425. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  116426. */
  116427. _this.USERGBCOLOR = false;
  116428. /**
  116429. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  116430. * stays aligned with the desired configuration.
  116431. */
  116432. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  116433. /**
  116434. * True to add noise in order to reduce the banding effect.
  116435. */
  116436. _this.NOISE = false;
  116437. /**
  116438. * is the reflection texture in BGR color scheme?
  116439. * Mainly used to solve a bug in ios10 video tag
  116440. */
  116441. _this.REFLECTIONBGR = false;
  116442. _this.IMAGEPROCESSING = false;
  116443. _this.VIGNETTE = false;
  116444. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  116445. _this.VIGNETTEBLENDMODEOPAQUE = false;
  116446. _this.TONEMAPPING = false;
  116447. _this.TONEMAPPING_ACES = false;
  116448. _this.CONTRAST = false;
  116449. _this.COLORCURVES = false;
  116450. _this.COLORGRADING = false;
  116451. _this.COLORGRADING3D = false;
  116452. _this.SAMPLER3DGREENDEPTH = false;
  116453. _this.SAMPLER3DBGRMAP = false;
  116454. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  116455. _this.EXPOSURE = false;
  116456. // Reflection.
  116457. _this.REFLECTION = false;
  116458. _this.REFLECTIONMAP_3D = false;
  116459. _this.REFLECTIONMAP_SPHERICAL = false;
  116460. _this.REFLECTIONMAP_PLANAR = false;
  116461. _this.REFLECTIONMAP_CUBIC = false;
  116462. _this.REFLECTIONMAP_PROJECTION = false;
  116463. _this.REFLECTIONMAP_SKYBOX = false;
  116464. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116465. _this.REFLECTIONMAP_EXPLICIT = false;
  116466. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116467. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116468. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116469. _this.INVERTCUBICMAP = false;
  116470. _this.REFLECTIONMAP_OPPOSITEZ = false;
  116471. _this.LODINREFLECTIONALPHA = false;
  116472. _this.GAMMAREFLECTION = false;
  116473. _this.RGBDREFLECTION = false;
  116474. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  116475. // Default BJS.
  116476. _this.MAINUV1 = false;
  116477. _this.MAINUV2 = false;
  116478. _this.UV1 = false;
  116479. _this.UV2 = false;
  116480. _this.CLIPPLANE = false;
  116481. _this.CLIPPLANE2 = false;
  116482. _this.CLIPPLANE3 = false;
  116483. _this.CLIPPLANE4 = false;
  116484. _this.POINTSIZE = false;
  116485. _this.FOG = false;
  116486. _this.NORMAL = false;
  116487. _this.NUM_BONE_INFLUENCERS = 0;
  116488. _this.BonesPerMesh = 0;
  116489. _this.INSTANCES = false;
  116490. _this.SHADOWFLOAT = false;
  116491. _this.rebuild();
  116492. return _this;
  116493. }
  116494. return BackgroundMaterialDefines;
  116495. }(BABYLON.MaterialDefines));
  116496. /**
  116497. * Background material used to create an efficient environement around your scene.
  116498. */
  116499. var BackgroundMaterial = /** @class */ (function (_super) {
  116500. __extends(BackgroundMaterial, _super);
  116501. /**
  116502. * Instantiates a Background Material in the given scene
  116503. * @param name The friendly name of the material
  116504. * @param scene The scene to add the material to
  116505. */
  116506. function BackgroundMaterial(name, scene) {
  116507. var _this = _super.call(this, name, scene) || this;
  116508. /**
  116509. * Key light Color (multiply against the environement texture)
  116510. */
  116511. _this.primaryColor = BABYLON.Color3.White();
  116512. _this._primaryColorShadowLevel = 0;
  116513. _this._primaryColorHighlightLevel = 0;
  116514. /**
  116515. * Reflection Texture used in the material.
  116516. * Should be author in a specific way for the best result (refer to the documentation).
  116517. */
  116518. _this.reflectionTexture = null;
  116519. /**
  116520. * Reflection Texture level of blur.
  116521. *
  116522. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  116523. * texture twice.
  116524. */
  116525. _this.reflectionBlur = 0;
  116526. /**
  116527. * Diffuse Texture used in the material.
  116528. * Should be author in a specific way for the best result (refer to the documentation).
  116529. */
  116530. _this.diffuseTexture = null;
  116531. _this._shadowLights = null;
  116532. /**
  116533. * Specify the list of lights casting shadow on the material.
  116534. * All scene shadow lights will be included if null.
  116535. */
  116536. _this.shadowLights = null;
  116537. /**
  116538. * Helps adjusting the shadow to a softer level if required.
  116539. * 0 means black shadows and 1 means no shadows.
  116540. */
  116541. _this.shadowLevel = 0;
  116542. /**
  116543. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  116544. * It is usually zero but might be interesting to modify according to your setup.
  116545. */
  116546. _this.sceneCenter = BABYLON.Vector3.Zero();
  116547. /**
  116548. * This helps specifying that the material is falling off to the sky box at grazing angle.
  116549. * This helps ensuring a nice transition when the camera goes under the ground.
  116550. */
  116551. _this.opacityFresnel = true;
  116552. /**
  116553. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  116554. * This helps adding a mirror texture on the ground.
  116555. */
  116556. _this.reflectionFresnel = false;
  116557. /**
  116558. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  116559. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  116560. */
  116561. _this.reflectionFalloffDistance = 0.0;
  116562. /**
  116563. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  116564. */
  116565. _this.reflectionAmount = 1.0;
  116566. /**
  116567. * This specifies the weight of the reflection at grazing angle.
  116568. */
  116569. _this.reflectionReflectance0 = 0.05;
  116570. /**
  116571. * This specifies the weight of the reflection at a perpendicular point of view.
  116572. */
  116573. _this.reflectionReflectance90 = 0.5;
  116574. /**
  116575. * Helps to directly use the maps channels instead of their level.
  116576. */
  116577. _this.useRGBColor = true;
  116578. /**
  116579. * This helps reducing the banding effect that could occur on the background.
  116580. */
  116581. _this.enableNoise = false;
  116582. _this._fovMultiplier = 1.0;
  116583. /**
  116584. * Enable the FOV adjustment feature controlled by fovMultiplier.
  116585. */
  116586. _this.useEquirectangularFOV = false;
  116587. _this._maxSimultaneousLights = 4;
  116588. /**
  116589. * Number of Simultaneous lights allowed on the material.
  116590. */
  116591. _this.maxSimultaneousLights = 4;
  116592. /**
  116593. * Keep track of the image processing observer to allow dispose and replace.
  116594. */
  116595. _this._imageProcessingObserver = null;
  116596. /**
  116597. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  116598. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  116599. */
  116600. _this.switchToBGR = false;
  116601. // Temp values kept as cache in the material.
  116602. _this._renderTargets = new BABYLON.SmartArray(16);
  116603. _this._reflectionControls = BABYLON.Vector4.Zero();
  116604. _this._white = BABYLON.Color3.White();
  116605. _this._primaryShadowColor = BABYLON.Color3.Black();
  116606. _this._primaryHighlightColor = BABYLON.Color3.Black();
  116607. // Setup the default processing configuration to the scene.
  116608. _this._attachImageProcessingConfiguration(null);
  116609. _this.getRenderTargetTextures = function () {
  116610. _this._renderTargets.reset();
  116611. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  116612. _this._renderTargets.push(_this._diffuseTexture);
  116613. }
  116614. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  116615. _this._renderTargets.push(_this._reflectionTexture);
  116616. }
  116617. return _this._renderTargets;
  116618. };
  116619. return _this;
  116620. }
  116621. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  116622. /**
  116623. * Experimental Internal Use Only.
  116624. *
  116625. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  116626. * This acts as a helper to set the primary color to a more "human friendly" value.
  116627. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  116628. * output color as close as possible from the chosen value.
  116629. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  116630. * part of lighting setup.)
  116631. */
  116632. get: function () {
  116633. return this.__perceptualColor;
  116634. },
  116635. set: function (value) {
  116636. this.__perceptualColor = value;
  116637. this._computePrimaryColorFromPerceptualColor();
  116638. this._markAllSubMeshesAsLightsDirty();
  116639. },
  116640. enumerable: true,
  116641. configurable: true
  116642. });
  116643. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  116644. /**
  116645. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  116646. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  116647. */
  116648. get: function () {
  116649. return this._primaryColorShadowLevel;
  116650. },
  116651. set: function (value) {
  116652. this._primaryColorShadowLevel = value;
  116653. this._computePrimaryColors();
  116654. this._markAllSubMeshesAsLightsDirty();
  116655. },
  116656. enumerable: true,
  116657. configurable: true
  116658. });
  116659. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  116660. /**
  116661. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  116662. * The primary color is used at the level chosen to define what the white area would look.
  116663. */
  116664. get: function () {
  116665. return this._primaryColorHighlightLevel;
  116666. },
  116667. set: function (value) {
  116668. this._primaryColorHighlightLevel = value;
  116669. this._computePrimaryColors();
  116670. this._markAllSubMeshesAsLightsDirty();
  116671. },
  116672. enumerable: true,
  116673. configurable: true
  116674. });
  116675. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  116676. /**
  116677. * Sets the reflection reflectance fresnel values according to the default standard
  116678. * empirically know to work well :-)
  116679. */
  116680. set: function (value) {
  116681. var reflectionWeight = value;
  116682. if (reflectionWeight < 0.5) {
  116683. reflectionWeight = reflectionWeight * 2.0;
  116684. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  116685. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  116686. }
  116687. else {
  116688. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  116689. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  116690. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  116691. }
  116692. },
  116693. enumerable: true,
  116694. configurable: true
  116695. });
  116696. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  116697. /**
  116698. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116699. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  116700. * Recommended to be keep at 1.0 except for special cases.
  116701. */
  116702. get: function () {
  116703. return this._fovMultiplier;
  116704. },
  116705. set: function (value) {
  116706. if (isNaN(value)) {
  116707. value = 1.0;
  116708. }
  116709. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  116710. },
  116711. enumerable: true,
  116712. configurable: true
  116713. });
  116714. /**
  116715. * Attaches a new image processing configuration to the PBR Material.
  116716. * @param configuration (if null the scene configuration will be use)
  116717. */
  116718. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  116719. var _this = this;
  116720. if (configuration === this._imageProcessingConfiguration) {
  116721. return;
  116722. }
  116723. // Detaches observer.
  116724. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116725. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116726. }
  116727. // Pick the scene configuration if needed.
  116728. if (!configuration) {
  116729. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  116730. }
  116731. else {
  116732. this._imageProcessingConfiguration = configuration;
  116733. }
  116734. // Attaches observer.
  116735. if (this._imageProcessingConfiguration) {
  116736. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  116737. _this._computePrimaryColorFromPerceptualColor();
  116738. _this._markAllSubMeshesAsImageProcessingDirty();
  116739. });
  116740. }
  116741. };
  116742. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  116743. /**
  116744. * Gets the image processing configuration used either in this material.
  116745. */
  116746. get: function () {
  116747. return this._imageProcessingConfiguration;
  116748. },
  116749. /**
  116750. * Sets the Default image processing configuration used either in the this material.
  116751. *
  116752. * If sets to null, the scene one is in use.
  116753. */
  116754. set: function (value) {
  116755. this._attachImageProcessingConfiguration(value);
  116756. // Ensure the effect will be rebuilt.
  116757. this._markAllSubMeshesAsTexturesDirty();
  116758. },
  116759. enumerable: true,
  116760. configurable: true
  116761. });
  116762. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  116763. /**
  116764. * Gets wether the color curves effect is enabled.
  116765. */
  116766. get: function () {
  116767. return this.imageProcessingConfiguration.colorCurvesEnabled;
  116768. },
  116769. /**
  116770. * Sets wether the color curves effect is enabled.
  116771. */
  116772. set: function (value) {
  116773. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  116774. },
  116775. enumerable: true,
  116776. configurable: true
  116777. });
  116778. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  116779. /**
  116780. * Gets wether the color grading effect is enabled.
  116781. */
  116782. get: function () {
  116783. return this.imageProcessingConfiguration.colorGradingEnabled;
  116784. },
  116785. /**
  116786. * Gets wether the color grading effect is enabled.
  116787. */
  116788. set: function (value) {
  116789. this.imageProcessingConfiguration.colorGradingEnabled = value;
  116790. },
  116791. enumerable: true,
  116792. configurable: true
  116793. });
  116794. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  116795. /**
  116796. * Gets wether tonemapping is enabled or not.
  116797. */
  116798. get: function () {
  116799. return this._imageProcessingConfiguration.toneMappingEnabled;
  116800. },
  116801. /**
  116802. * Sets wether tonemapping is enabled or not
  116803. */
  116804. set: function (value) {
  116805. this._imageProcessingConfiguration.toneMappingEnabled = value;
  116806. },
  116807. enumerable: true,
  116808. configurable: true
  116809. });
  116810. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  116811. /**
  116812. * The camera exposure used on this material.
  116813. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116814. * This corresponds to a photographic exposure.
  116815. */
  116816. get: function () {
  116817. return this._imageProcessingConfiguration.exposure;
  116818. },
  116819. /**
  116820. * The camera exposure used on this material.
  116821. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116822. * This corresponds to a photographic exposure.
  116823. */
  116824. set: function (value) {
  116825. this._imageProcessingConfiguration.exposure = value;
  116826. },
  116827. enumerable: true,
  116828. configurable: true
  116829. });
  116830. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  116831. /**
  116832. * Gets The camera contrast used on this material.
  116833. */
  116834. get: function () {
  116835. return this._imageProcessingConfiguration.contrast;
  116836. },
  116837. /**
  116838. * Sets The camera contrast used on this material.
  116839. */
  116840. set: function (value) {
  116841. this._imageProcessingConfiguration.contrast = value;
  116842. },
  116843. enumerable: true,
  116844. configurable: true
  116845. });
  116846. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  116847. /**
  116848. * Gets the Color Grading 2D Lookup Texture.
  116849. */
  116850. get: function () {
  116851. return this._imageProcessingConfiguration.colorGradingTexture;
  116852. },
  116853. /**
  116854. * Sets the Color Grading 2D Lookup Texture.
  116855. */
  116856. set: function (value) {
  116857. this.imageProcessingConfiguration.colorGradingTexture = value;
  116858. },
  116859. enumerable: true,
  116860. configurable: true
  116861. });
  116862. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  116863. /**
  116864. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116865. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116866. * 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;
  116867. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116868. */
  116869. get: function () {
  116870. return this.imageProcessingConfiguration.colorCurves;
  116871. },
  116872. /**
  116873. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116874. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116875. * 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;
  116876. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116877. */
  116878. set: function (value) {
  116879. this.imageProcessingConfiguration.colorCurves = value;
  116880. },
  116881. enumerable: true,
  116882. configurable: true
  116883. });
  116884. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  116885. /**
  116886. * Gets a boolean indicating that current material needs to register RTT
  116887. */
  116888. get: function () {
  116889. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  116890. return true;
  116891. }
  116892. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  116893. return true;
  116894. }
  116895. return false;
  116896. },
  116897. enumerable: true,
  116898. configurable: true
  116899. });
  116900. /**
  116901. * The entire material has been created in order to prevent overdraw.
  116902. * @returns false
  116903. */
  116904. BackgroundMaterial.prototype.needAlphaTesting = function () {
  116905. return true;
  116906. };
  116907. /**
  116908. * The entire material has been created in order to prevent overdraw.
  116909. * @returns true if blending is enable
  116910. */
  116911. BackgroundMaterial.prototype.needAlphaBlending = function () {
  116912. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  116913. };
  116914. /**
  116915. * Checks wether the material is ready to be rendered for a given mesh.
  116916. * @param mesh The mesh to render
  116917. * @param subMesh The submesh to check against
  116918. * @param useInstances Specify wether or not the material is used with instances
  116919. * @returns true if all the dependencies are ready (Textures, Effects...)
  116920. */
  116921. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  116922. var _this = this;
  116923. if (useInstances === void 0) { useInstances = false; }
  116924. if (subMesh.effect && this.isFrozen) {
  116925. if (this._wasPreviouslyReady) {
  116926. return true;
  116927. }
  116928. }
  116929. if (!subMesh._materialDefines) {
  116930. subMesh._materialDefines = new BackgroundMaterialDefines();
  116931. }
  116932. var scene = this.getScene();
  116933. var defines = subMesh._materialDefines;
  116934. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  116935. if (defines._renderId === scene.getRenderId()) {
  116936. return true;
  116937. }
  116938. }
  116939. var engine = scene.getEngine();
  116940. // Lights
  116941. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  116942. defines._needNormals = true;
  116943. // Textures
  116944. if (defines._areTexturesDirty) {
  116945. defines._needUVs = false;
  116946. if (scene.texturesEnabled) {
  116947. if (scene.getEngine().getCaps().textureLOD) {
  116948. defines.TEXTURELODSUPPORT = true;
  116949. }
  116950. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116951. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  116952. return false;
  116953. }
  116954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  116955. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  116956. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  116957. defines.OPACITYFRESNEL = this._opacityFresnel;
  116958. }
  116959. else {
  116960. defines.DIFFUSE = false;
  116961. defines.DIFFUSEHASALPHA = false;
  116962. defines.GAMMADIFFUSE = false;
  116963. defines.OPACITYFRESNEL = false;
  116964. }
  116965. var reflectionTexture = this._reflectionTexture;
  116966. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116967. if (!reflectionTexture.isReadyOrNotBlocking()) {
  116968. return false;
  116969. }
  116970. defines.REFLECTION = true;
  116971. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  116972. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  116973. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  116974. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  116975. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  116976. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  116977. defines.REFLECTIONBGR = this.switchToBGR;
  116978. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  116979. defines.INVERTCUBICMAP = true;
  116980. }
  116981. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  116982. switch (reflectionTexture.coordinatesMode) {
  116983. case BABYLON.Texture.EXPLICIT_MODE:
  116984. defines.REFLECTIONMAP_EXPLICIT = true;
  116985. break;
  116986. case BABYLON.Texture.PLANAR_MODE:
  116987. defines.REFLECTIONMAP_PLANAR = true;
  116988. break;
  116989. case BABYLON.Texture.PROJECTION_MODE:
  116990. defines.REFLECTIONMAP_PROJECTION = true;
  116991. break;
  116992. case BABYLON.Texture.SKYBOX_MODE:
  116993. defines.REFLECTIONMAP_SKYBOX = true;
  116994. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  116995. break;
  116996. case BABYLON.Texture.SPHERICAL_MODE:
  116997. defines.REFLECTIONMAP_SPHERICAL = true;
  116998. break;
  116999. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  117000. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  117001. break;
  117002. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  117003. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  117004. break;
  117005. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  117006. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  117007. break;
  117008. case BABYLON.Texture.CUBIC_MODE:
  117009. case BABYLON.Texture.INVCUBIC_MODE:
  117010. default:
  117011. defines.REFLECTIONMAP_CUBIC = true;
  117012. break;
  117013. }
  117014. if (this.reflectionFresnel) {
  117015. defines.REFLECTIONFRESNEL = true;
  117016. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  117017. this._reflectionControls.x = this.reflectionAmount;
  117018. this._reflectionControls.y = this.reflectionReflectance0;
  117019. this._reflectionControls.z = this.reflectionReflectance90;
  117020. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  117021. }
  117022. else {
  117023. defines.REFLECTIONFRESNEL = false;
  117024. defines.REFLECTIONFALLOFF = false;
  117025. }
  117026. }
  117027. else {
  117028. defines.REFLECTION = false;
  117029. defines.REFLECTIONFRESNEL = false;
  117030. defines.REFLECTIONFALLOFF = false;
  117031. defines.REFLECTIONBLUR = false;
  117032. defines.REFLECTIONMAP_3D = false;
  117033. defines.REFLECTIONMAP_SPHERICAL = false;
  117034. defines.REFLECTIONMAP_PLANAR = false;
  117035. defines.REFLECTIONMAP_CUBIC = false;
  117036. defines.REFLECTIONMAP_PROJECTION = false;
  117037. defines.REFLECTIONMAP_SKYBOX = false;
  117038. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  117039. defines.REFLECTIONMAP_EXPLICIT = false;
  117040. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  117041. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  117042. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  117043. defines.INVERTCUBICMAP = false;
  117044. defines.REFLECTIONMAP_OPPOSITEZ = false;
  117045. defines.LODINREFLECTIONALPHA = false;
  117046. defines.GAMMAREFLECTION = false;
  117047. defines.RGBDREFLECTION = false;
  117048. }
  117049. }
  117050. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  117051. defines.USERGBCOLOR = this._useRGBColor;
  117052. defines.NOISE = this._enableNoise;
  117053. }
  117054. if (defines._areLightsDirty) {
  117055. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  117056. }
  117057. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  117058. if (!this._imageProcessingConfiguration.isReady()) {
  117059. return false;
  117060. }
  117061. this._imageProcessingConfiguration.prepareDefines(defines);
  117062. }
  117063. // Misc.
  117064. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  117065. // Values that need to be evaluated on every frame
  117066. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  117067. // Attribs
  117068. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  117069. if (mesh) {
  117070. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  117071. mesh.createNormals(true);
  117072. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  117073. }
  117074. }
  117075. }
  117076. // Get correct effect
  117077. if (defines.isDirty) {
  117078. defines.markAsProcessed();
  117079. scene.resetCachedMaterial();
  117080. // Fallbacks
  117081. var fallbacks = new BABYLON.EffectFallbacks();
  117082. if (defines.FOG) {
  117083. fallbacks.addFallback(0, "FOG");
  117084. }
  117085. if (defines.POINTSIZE) {
  117086. fallbacks.addFallback(1, "POINTSIZE");
  117087. }
  117088. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  117089. if (defines.NUM_BONE_INFLUENCERS > 0) {
  117090. fallbacks.addCPUSkinningFallback(0, mesh);
  117091. }
  117092. //Attributes
  117093. var attribs = [BABYLON.VertexBuffer.PositionKind];
  117094. if (defines.NORMAL) {
  117095. attribs.push(BABYLON.VertexBuffer.NormalKind);
  117096. }
  117097. if (defines.UV1) {
  117098. attribs.push(BABYLON.VertexBuffer.UVKind);
  117099. }
  117100. if (defines.UV2) {
  117101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  117102. }
  117103. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  117104. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  117105. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  117106. "vFogInfos", "vFogColor", "pointSize",
  117107. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  117108. "vPrimaryColor", "vPrimaryColorShadow",
  117109. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  117110. "shadowLevel", "alpha",
  117111. "vBackgroundCenter", "vReflectionControl",
  117112. "vDiffuseInfos", "diffuseMatrix",
  117113. ];
  117114. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  117115. var uniformBuffers = ["Material", "Scene"];
  117116. if (BABYLON.ImageProcessingConfiguration) {
  117117. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  117118. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  117119. }
  117120. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  117121. uniformsNames: uniforms,
  117122. uniformBuffersNames: uniformBuffers,
  117123. samplers: samplers,
  117124. defines: defines,
  117125. maxSimultaneousLights: this._maxSimultaneousLights
  117126. });
  117127. var onCompiled = function (effect) {
  117128. if (_this.onCompiled) {
  117129. _this.onCompiled(effect);
  117130. }
  117131. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  117132. };
  117133. var join = defines.toString();
  117134. subMesh.setEffect(scene.getEngine().createEffect("background", {
  117135. attributes: attribs,
  117136. uniformsNames: uniforms,
  117137. uniformBuffersNames: uniformBuffers,
  117138. samplers: samplers,
  117139. defines: join,
  117140. fallbacks: fallbacks,
  117141. onCompiled: onCompiled,
  117142. onError: this.onError,
  117143. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  117144. }, engine), defines);
  117145. this.buildUniformLayout();
  117146. }
  117147. if (!subMesh.effect || !subMesh.effect.isReady()) {
  117148. return false;
  117149. }
  117150. defines._renderId = scene.getRenderId();
  117151. this._wasPreviouslyReady = true;
  117152. return true;
  117153. };
  117154. /**
  117155. * Compute the primary color according to the chosen perceptual color.
  117156. */
  117157. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  117158. if (!this.__perceptualColor) {
  117159. return;
  117160. }
  117161. this._primaryColor.copyFrom(this.__perceptualColor);
  117162. // Revert gamma space.
  117163. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  117164. // Revert image processing configuration.
  117165. if (this._imageProcessingConfiguration) {
  117166. // Revert Exposure.
  117167. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  117168. }
  117169. this._computePrimaryColors();
  117170. };
  117171. /**
  117172. * Compute the highlights and shadow colors according to their chosen levels.
  117173. */
  117174. BackgroundMaterial.prototype._computePrimaryColors = function () {
  117175. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  117176. return;
  117177. }
  117178. // Find the highlight color based on the configuration.
  117179. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  117180. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  117181. // Find the shadow color based on the configuration.
  117182. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  117183. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  117184. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  117185. };
  117186. /**
  117187. * Build the uniform buffer used in the material.
  117188. */
  117189. BackgroundMaterial.prototype.buildUniformLayout = function () {
  117190. // Order is important !
  117191. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  117192. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  117193. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  117194. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  117195. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  117196. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  117197. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  117198. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  117199. this._uniformBuffer.addUniform("pointSize", 1);
  117200. this._uniformBuffer.addUniform("shadowLevel", 1);
  117201. this._uniformBuffer.addUniform("alpha", 1);
  117202. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  117203. this._uniformBuffer.addUniform("vReflectionControl", 4);
  117204. this._uniformBuffer.create();
  117205. };
  117206. /**
  117207. * Unbind the material.
  117208. */
  117209. BackgroundMaterial.prototype.unbind = function () {
  117210. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  117211. this._uniformBuffer.setTexture("diffuseSampler", null);
  117212. }
  117213. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  117214. this._uniformBuffer.setTexture("reflectionSampler", null);
  117215. }
  117216. _super.prototype.unbind.call(this);
  117217. };
  117218. /**
  117219. * Bind only the world matrix to the material.
  117220. * @param world The world matrix to bind.
  117221. */
  117222. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  117223. this._activeEffect.setMatrix("world", world);
  117224. };
  117225. /**
  117226. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  117227. * @param world The world matrix to bind.
  117228. * @param subMesh The submesh to bind for.
  117229. */
  117230. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  117231. var scene = this.getScene();
  117232. var defines = subMesh._materialDefines;
  117233. if (!defines) {
  117234. return;
  117235. }
  117236. var effect = subMesh.effect;
  117237. if (!effect) {
  117238. return;
  117239. }
  117240. this._activeEffect = effect;
  117241. // Matrices
  117242. this.bindOnlyWorldMatrix(world);
  117243. // Bones
  117244. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  117245. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  117246. if (mustRebind) {
  117247. this._uniformBuffer.bindToEffect(effect, "Material");
  117248. this.bindViewProjection(effect);
  117249. var reflectionTexture = this._reflectionTexture;
  117250. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  117251. // Texture uniforms
  117252. if (scene.texturesEnabled) {
  117253. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117254. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  117255. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  117256. }
  117257. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117258. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  117259. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  117260. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  117261. }
  117262. }
  117263. if (this.shadowLevel > 0) {
  117264. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  117265. }
  117266. this._uniformBuffer.updateFloat("alpha", this.alpha);
  117267. // Point size
  117268. if (this.pointsCloud) {
  117269. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  117270. }
  117271. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  117272. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  117273. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  117274. }
  117275. else {
  117276. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  117277. }
  117278. }
  117279. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  117280. // Textures
  117281. if (scene.texturesEnabled) {
  117282. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117283. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  117284. }
  117285. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117286. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  117287. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117288. }
  117289. else if (!defines.REFLECTIONBLUR) {
  117290. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117291. }
  117292. else {
  117293. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  117294. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  117295. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  117296. }
  117297. if (defines.REFLECTIONFRESNEL) {
  117298. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  117299. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  117300. }
  117301. }
  117302. }
  117303. // Clip plane
  117304. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  117305. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  117306. }
  117307. if (mustRebind || !this.isFrozen) {
  117308. if (scene.lightsEnabled) {
  117309. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  117310. }
  117311. // View
  117312. this.bindView(effect);
  117313. // Fog
  117314. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  117315. // image processing
  117316. if (this._imageProcessingConfiguration) {
  117317. this._imageProcessingConfiguration.bind(this._activeEffect);
  117318. }
  117319. }
  117320. this._uniformBuffer.update();
  117321. this._afterBind(mesh, this._activeEffect);
  117322. };
  117323. /**
  117324. * Dispose the material.
  117325. * @param forceDisposeEffect Force disposal of the associated effect.
  117326. * @param forceDisposeTextures Force disposal of the associated textures.
  117327. */
  117328. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  117329. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  117330. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  117331. if (forceDisposeTextures) {
  117332. if (this.diffuseTexture) {
  117333. this.diffuseTexture.dispose();
  117334. }
  117335. if (this.reflectionTexture) {
  117336. this.reflectionTexture.dispose();
  117337. }
  117338. }
  117339. this._renderTargets.dispose();
  117340. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  117341. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  117342. }
  117343. _super.prototype.dispose.call(this, forceDisposeEffect);
  117344. };
  117345. /**
  117346. * Clones the material.
  117347. * @param name The cloned name.
  117348. * @returns The cloned material.
  117349. */
  117350. BackgroundMaterial.prototype.clone = function (name) {
  117351. var _this = this;
  117352. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  117353. };
  117354. /**
  117355. * Serializes the current material to its JSON representation.
  117356. * @returns The JSON representation.
  117357. */
  117358. BackgroundMaterial.prototype.serialize = function () {
  117359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  117360. serializationObject.customType = "BABYLON.BackgroundMaterial";
  117361. return serializationObject;
  117362. };
  117363. /**
  117364. * Gets the class name of the material
  117365. * @returns "BackgroundMaterial"
  117366. */
  117367. BackgroundMaterial.prototype.getClassName = function () {
  117368. return "BackgroundMaterial";
  117369. };
  117370. /**
  117371. * Parse a JSON input to create back a background material.
  117372. * @param source The JSON data to parse
  117373. * @param scene The scene to create the parsed material in
  117374. * @param rootUrl The root url of the assets the material depends upon
  117375. * @returns the instantiated BackgroundMaterial.
  117376. */
  117377. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  117378. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  117379. };
  117380. /**
  117381. * Standard reflectance value at parallel view angle.
  117382. */
  117383. BackgroundMaterial.StandardReflectance0 = 0.05;
  117384. /**
  117385. * Standard reflectance value at grazing angle.
  117386. */
  117387. BackgroundMaterial.StandardReflectance90 = 0.5;
  117388. __decorate([
  117389. BABYLON.serializeAsColor3()
  117390. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  117391. __decorate([
  117392. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  117393. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  117394. __decorate([
  117395. BABYLON.serializeAsColor3()
  117396. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  117397. __decorate([
  117398. BABYLON.serialize()
  117399. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  117400. __decorate([
  117401. BABYLON.serialize()
  117402. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  117403. __decorate([
  117404. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  117405. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  117406. __decorate([
  117407. BABYLON.serializeAsTexture()
  117408. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  117409. __decorate([
  117410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117411. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  117412. __decorate([
  117413. BABYLON.serialize()
  117414. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  117415. __decorate([
  117416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117417. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  117418. __decorate([
  117419. BABYLON.serializeAsTexture()
  117420. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  117421. __decorate([
  117422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117423. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  117424. __decorate([
  117425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117426. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  117427. __decorate([
  117428. BABYLON.serialize()
  117429. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  117430. __decorate([
  117431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117432. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  117433. __decorate([
  117434. BABYLON.serializeAsVector3()
  117435. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  117436. __decorate([
  117437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117438. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  117439. __decorate([
  117440. BABYLON.serialize()
  117441. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  117442. __decorate([
  117443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117444. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  117445. __decorate([
  117446. BABYLON.serialize()
  117447. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  117448. __decorate([
  117449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117450. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  117451. __decorate([
  117452. BABYLON.serialize()
  117453. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  117454. __decorate([
  117455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117456. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  117457. __decorate([
  117458. BABYLON.serialize()
  117459. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  117460. __decorate([
  117461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117462. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  117463. __decorate([
  117464. BABYLON.serialize()
  117465. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  117466. __decorate([
  117467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117468. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  117469. __decorate([
  117470. BABYLON.serialize()
  117471. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  117472. __decorate([
  117473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117474. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  117475. __decorate([
  117476. BABYLON.serialize()
  117477. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  117478. __decorate([
  117479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117480. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  117481. __decorate([
  117482. BABYLON.serialize()
  117483. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  117484. __decorate([
  117485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117486. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  117487. __decorate([
  117488. BABYLON.serialize()
  117489. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  117490. __decorate([
  117491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117492. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  117493. __decorate([
  117494. BABYLON.serializeAsImageProcessingConfiguration()
  117495. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  117496. return BackgroundMaterial;
  117497. }(BABYLON.PushMaterial));
  117498. BABYLON.BackgroundMaterial = BackgroundMaterial;
  117499. })(BABYLON || (BABYLON = {}));
  117500. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  117501. var __assign = (this && this.__assign) || function () {
  117502. __assign = Object.assign || function(t) {
  117503. for (var s, i = 1, n = arguments.length; i < n; i++) {
  117504. s = arguments[i];
  117505. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  117506. t[p] = s[p];
  117507. }
  117508. return t;
  117509. };
  117510. return __assign.apply(this, arguments);
  117511. };
  117512. var BABYLON;
  117513. (function (BABYLON) {
  117514. /**
  117515. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  117516. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  117517. * It also helps with the default setup of your imageProcessing configuration.
  117518. */
  117519. var EnvironmentHelper = /** @class */ (function () {
  117520. /**
  117521. * constructor
  117522. * @param options
  117523. * @param scene The scene to add the material to
  117524. */
  117525. function EnvironmentHelper(options, scene) {
  117526. var _this = this;
  117527. this._errorHandler = function (message, exception) {
  117528. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  117529. };
  117530. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  117531. this._scene = scene;
  117532. this.onErrorObservable = new BABYLON.Observable();
  117533. this._setupBackground();
  117534. this._setupImageProcessing();
  117535. }
  117536. /**
  117537. * Creates the default options for the helper.
  117538. */
  117539. EnvironmentHelper._getDefaultOptions = function () {
  117540. return {
  117541. createGround: true,
  117542. groundSize: 15,
  117543. groundTexture: this._groundTextureCDNUrl,
  117544. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117545. groundOpacity: 0.9,
  117546. enableGroundShadow: true,
  117547. groundShadowLevel: 0.5,
  117548. enableGroundMirror: false,
  117549. groundMirrorSizeRatio: 0.3,
  117550. groundMirrorBlurKernel: 64,
  117551. groundMirrorAmount: 1,
  117552. groundMirrorFresnelWeight: 1,
  117553. groundMirrorFallOffDistance: 0,
  117554. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  117555. groundYBias: 0.00001,
  117556. createSkybox: true,
  117557. skyboxSize: 20,
  117558. skyboxTexture: this._skyboxTextureCDNUrl,
  117559. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117560. backgroundYRotation: 0,
  117561. sizeAuto: true,
  117562. rootPosition: BABYLON.Vector3.Zero(),
  117563. setupImageProcessing: true,
  117564. environmentTexture: this._environmentTextureCDNUrl,
  117565. cameraExposure: 0.8,
  117566. cameraContrast: 1.2,
  117567. toneMappingEnabled: true,
  117568. };
  117569. };
  117570. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  117571. /**
  117572. * Gets the root mesh created by the helper.
  117573. */
  117574. get: function () {
  117575. return this._rootMesh;
  117576. },
  117577. enumerable: true,
  117578. configurable: true
  117579. });
  117580. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  117581. /**
  117582. * Gets the skybox created by the helper.
  117583. */
  117584. get: function () {
  117585. return this._skybox;
  117586. },
  117587. enumerable: true,
  117588. configurable: true
  117589. });
  117590. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  117591. /**
  117592. * Gets the skybox texture created by the helper.
  117593. */
  117594. get: function () {
  117595. return this._skyboxTexture;
  117596. },
  117597. enumerable: true,
  117598. configurable: true
  117599. });
  117600. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  117601. /**
  117602. * Gets the skybox material created by the helper.
  117603. */
  117604. get: function () {
  117605. return this._skyboxMaterial;
  117606. },
  117607. enumerable: true,
  117608. configurable: true
  117609. });
  117610. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  117611. /**
  117612. * Gets the ground mesh created by the helper.
  117613. */
  117614. get: function () {
  117615. return this._ground;
  117616. },
  117617. enumerable: true,
  117618. configurable: true
  117619. });
  117620. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  117621. /**
  117622. * Gets the ground texture created by the helper.
  117623. */
  117624. get: function () {
  117625. return this._groundTexture;
  117626. },
  117627. enumerable: true,
  117628. configurable: true
  117629. });
  117630. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  117631. /**
  117632. * Gets the ground mirror created by the helper.
  117633. */
  117634. get: function () {
  117635. return this._groundMirror;
  117636. },
  117637. enumerable: true,
  117638. configurable: true
  117639. });
  117640. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  117641. /**
  117642. * Gets the ground mirror render list to helps pushing the meshes
  117643. * you wish in the ground reflection.
  117644. */
  117645. get: function () {
  117646. if (this._groundMirror) {
  117647. return this._groundMirror.renderList;
  117648. }
  117649. return null;
  117650. },
  117651. enumerable: true,
  117652. configurable: true
  117653. });
  117654. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  117655. /**
  117656. * Gets the ground material created by the helper.
  117657. */
  117658. get: function () {
  117659. return this._groundMaterial;
  117660. },
  117661. enumerable: true,
  117662. configurable: true
  117663. });
  117664. /**
  117665. * Updates the background according to the new options
  117666. * @param options
  117667. */
  117668. EnvironmentHelper.prototype.updateOptions = function (options) {
  117669. var newOptions = __assign({}, this._options, options);
  117670. if (this._ground && !newOptions.createGround) {
  117671. this._ground.dispose();
  117672. this._ground = null;
  117673. }
  117674. if (this._groundMaterial && !newOptions.createGround) {
  117675. this._groundMaterial.dispose();
  117676. this._groundMaterial = null;
  117677. }
  117678. if (this._groundTexture) {
  117679. if (this._options.groundTexture != newOptions.groundTexture) {
  117680. this._groundTexture.dispose();
  117681. this._groundTexture = null;
  117682. }
  117683. }
  117684. if (this._skybox && !newOptions.createSkybox) {
  117685. this._skybox.dispose();
  117686. this._skybox = null;
  117687. }
  117688. if (this._skyboxMaterial && !newOptions.createSkybox) {
  117689. this._skyboxMaterial.dispose();
  117690. this._skyboxMaterial = null;
  117691. }
  117692. if (this._skyboxTexture) {
  117693. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  117694. this._skyboxTexture.dispose();
  117695. this._skyboxTexture = null;
  117696. }
  117697. }
  117698. if (this._groundMirror && !newOptions.enableGroundMirror) {
  117699. this._groundMirror.dispose();
  117700. this._groundMirror = null;
  117701. }
  117702. if (this._scene.environmentTexture) {
  117703. if (this._options.environmentTexture != newOptions.environmentTexture) {
  117704. this._scene.environmentTexture.dispose();
  117705. }
  117706. }
  117707. this._options = newOptions;
  117708. this._setupBackground();
  117709. this._setupImageProcessing();
  117710. };
  117711. /**
  117712. * Sets the primary color of all the available elements.
  117713. * @param color the main color to affect to the ground and the background
  117714. */
  117715. EnvironmentHelper.prototype.setMainColor = function (color) {
  117716. if (this.groundMaterial) {
  117717. this.groundMaterial.primaryColor = color;
  117718. }
  117719. if (this.skyboxMaterial) {
  117720. this.skyboxMaterial.primaryColor = color;
  117721. }
  117722. if (this.groundMirror) {
  117723. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  117724. }
  117725. };
  117726. /**
  117727. * Setup the image processing according to the specified options.
  117728. */
  117729. EnvironmentHelper.prototype._setupImageProcessing = function () {
  117730. if (this._options.setupImageProcessing) {
  117731. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  117732. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  117733. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  117734. this._setupEnvironmentTexture();
  117735. }
  117736. };
  117737. /**
  117738. * Setup the environment texture according to the specified options.
  117739. */
  117740. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  117741. if (this._scene.environmentTexture) {
  117742. return;
  117743. }
  117744. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  117745. this._scene.environmentTexture = this._options.environmentTexture;
  117746. return;
  117747. }
  117748. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  117749. this._scene.environmentTexture = environmentTexture;
  117750. };
  117751. /**
  117752. * Setup the background according to the specified options.
  117753. */
  117754. EnvironmentHelper.prototype._setupBackground = function () {
  117755. if (!this._rootMesh) {
  117756. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  117757. }
  117758. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  117759. var sceneSize = this._getSceneSize();
  117760. if (this._options.createGround) {
  117761. this._setupGround(sceneSize);
  117762. this._setupGroundMaterial();
  117763. this._setupGroundDiffuseTexture();
  117764. if (this._options.enableGroundMirror) {
  117765. this._setupGroundMirrorTexture(sceneSize);
  117766. }
  117767. this._setupMirrorInGroundMaterial();
  117768. }
  117769. if (this._options.createSkybox) {
  117770. this._setupSkybox(sceneSize);
  117771. this._setupSkyboxMaterial();
  117772. this._setupSkyboxReflectionTexture();
  117773. }
  117774. this._rootMesh.position.x = sceneSize.rootPosition.x;
  117775. this._rootMesh.position.z = sceneSize.rootPosition.z;
  117776. this._rootMesh.position.y = sceneSize.rootPosition.y;
  117777. };
  117778. /**
  117779. * Get the scene sizes according to the setup.
  117780. */
  117781. EnvironmentHelper.prototype._getSceneSize = function () {
  117782. var _this = this;
  117783. var groundSize = this._options.groundSize;
  117784. var skyboxSize = this._options.skyboxSize;
  117785. var rootPosition = this._options.rootPosition;
  117786. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  117787. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117788. }
  117789. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  117790. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  117791. });
  117792. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  117793. if (this._options.sizeAuto) {
  117794. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  117795. this._scene.activeCamera.upperRadiusLimit) {
  117796. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  117797. skyboxSize = groundSize;
  117798. }
  117799. var sceneDiagonalLenght = sceneDiagonal.length();
  117800. if (sceneDiagonalLenght > groundSize) {
  117801. groundSize = sceneDiagonalLenght * 2;
  117802. skyboxSize = groundSize;
  117803. }
  117804. // 10 % bigger.
  117805. groundSize *= 1.1;
  117806. skyboxSize *= 1.5;
  117807. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  117808. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  117809. }
  117810. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117811. };
  117812. /**
  117813. * Setup the ground according to the specified options.
  117814. */
  117815. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  117816. var _this = this;
  117817. if (!this._ground || this._ground.isDisposed()) {
  117818. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  117819. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  117820. this._ground.parent = this._rootMesh;
  117821. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  117822. }
  117823. this._ground.receiveShadows = this._options.enableGroundShadow;
  117824. };
  117825. /**
  117826. * Setup the ground material according to the specified options.
  117827. */
  117828. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  117829. if (!this._groundMaterial) {
  117830. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  117831. }
  117832. this._groundMaterial.alpha = this._options.groundOpacity;
  117833. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  117834. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  117835. this._groundMaterial.primaryColor = this._options.groundColor;
  117836. this._groundMaterial.useRGBColor = false;
  117837. this._groundMaterial.enableNoise = true;
  117838. if (this._ground) {
  117839. this._ground.material = this._groundMaterial;
  117840. }
  117841. };
  117842. /**
  117843. * Setup the ground diffuse texture according to the specified options.
  117844. */
  117845. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  117846. if (!this._groundMaterial) {
  117847. return;
  117848. }
  117849. if (this._groundTexture) {
  117850. return;
  117851. }
  117852. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  117853. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  117854. return;
  117855. }
  117856. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117857. diffuseTexture.gammaSpace = false;
  117858. diffuseTexture.hasAlpha = true;
  117859. this._groundMaterial.diffuseTexture = diffuseTexture;
  117860. };
  117861. /**
  117862. * Setup the ground mirror texture according to the specified options.
  117863. */
  117864. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  117865. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117866. if (!this._groundMirror) {
  117867. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  117868. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  117869. this._groundMirror.anisotropicFilteringLevel = 1;
  117870. this._groundMirror.wrapU = wrapping;
  117871. this._groundMirror.wrapV = wrapping;
  117872. this._groundMirror.gammaSpace = false;
  117873. if (this._groundMirror.renderList) {
  117874. for (var i = 0; i < this._scene.meshes.length; i++) {
  117875. var mesh = this._scene.meshes[i];
  117876. if (mesh !== this._ground &&
  117877. mesh !== this._skybox &&
  117878. mesh !== this._rootMesh) {
  117879. this._groundMirror.renderList.push(mesh);
  117880. }
  117881. }
  117882. }
  117883. }
  117884. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  117885. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  117886. };
  117887. /**
  117888. * Setup the ground to receive the mirror texture.
  117889. */
  117890. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  117891. if (this._groundMaterial) {
  117892. this._groundMaterial.reflectionTexture = this._groundMirror;
  117893. this._groundMaterial.reflectionFresnel = true;
  117894. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  117895. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  117896. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  117897. }
  117898. };
  117899. /**
  117900. * Setup the skybox according to the specified options.
  117901. */
  117902. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  117903. var _this = this;
  117904. if (!this._skybox || this._skybox.isDisposed()) {
  117905. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  117906. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  117907. }
  117908. this._skybox.parent = this._rootMesh;
  117909. };
  117910. /**
  117911. * Setup the skybox material according to the specified options.
  117912. */
  117913. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  117914. if (!this._skybox) {
  117915. return;
  117916. }
  117917. if (!this._skyboxMaterial) {
  117918. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  117919. }
  117920. this._skyboxMaterial.useRGBColor = false;
  117921. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  117922. this._skyboxMaterial.enableNoise = true;
  117923. this._skybox.material = this._skyboxMaterial;
  117924. };
  117925. /**
  117926. * Setup the skybox reflection texture according to the specified options.
  117927. */
  117928. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  117929. if (!this._skyboxMaterial) {
  117930. return;
  117931. }
  117932. if (this._skyboxTexture) {
  117933. return;
  117934. }
  117935. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  117936. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  117937. return;
  117938. }
  117939. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117940. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117941. this._skyboxTexture.gammaSpace = false;
  117942. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  117943. };
  117944. /**
  117945. * Dispose all the elements created by the Helper.
  117946. */
  117947. EnvironmentHelper.prototype.dispose = function () {
  117948. if (this._groundMaterial) {
  117949. this._groundMaterial.dispose(true, true);
  117950. }
  117951. if (this._skyboxMaterial) {
  117952. this._skyboxMaterial.dispose(true, true);
  117953. }
  117954. this._rootMesh.dispose(false);
  117955. };
  117956. /**
  117957. * Default ground texture URL.
  117958. */
  117959. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  117960. /**
  117961. * Default skybox texture URL.
  117962. */
  117963. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  117964. /**
  117965. * Default environment texture URL.
  117966. */
  117967. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  117968. return EnvironmentHelper;
  117969. }());
  117970. BABYLON.EnvironmentHelper = EnvironmentHelper;
  117971. })(BABYLON || (BABYLON = {}));
  117972. //# sourceMappingURL=babylon.environmentHelper.js.map
  117973. var BABYLON;
  117974. (function (BABYLON) {
  117975. /** Internal class used to store shapes for emitters */
  117976. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  117977. function ParticleSystemSetEmitterCreationOptions() {
  117978. }
  117979. return ParticleSystemSetEmitterCreationOptions;
  117980. }());
  117981. /**
  117982. * Represents a set of particle systems working together to create a specific effect
  117983. */
  117984. var ParticleSystemSet = /** @class */ (function () {
  117985. function ParticleSystemSet() {
  117986. /**
  117987. * Gets the particle system list
  117988. */
  117989. this.systems = new Array();
  117990. }
  117991. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  117992. /**
  117993. * Gets the emitter node used with this set
  117994. */
  117995. get: function () {
  117996. return this._emitterNode;
  117997. },
  117998. enumerable: true,
  117999. configurable: true
  118000. });
  118001. /**
  118002. * Creates a new emitter mesh as a sphere
  118003. * @param options defines the options used to create the sphere
  118004. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  118005. * @param scene defines the hosting scene
  118006. */
  118007. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  118008. if (this._emitterNode) {
  118009. this._emitterNode.dispose();
  118010. }
  118011. this._emitterCreationOptions = {
  118012. kind: "Sphere",
  118013. options: options,
  118014. renderingGroupId: renderingGroupId
  118015. };
  118016. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  118017. emitterMesh.renderingGroupId = renderingGroupId;
  118018. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  118019. material.emissiveColor = options.color;
  118020. emitterMesh.material = material;
  118021. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118022. var system = _a[_i];
  118023. system.emitter = emitterMesh;
  118024. }
  118025. this._emitterNode = emitterMesh;
  118026. };
  118027. /**
  118028. * Starts all particle systems of the set
  118029. * @param emitter defines an optional mesh to use as emitter for the particle systems
  118030. */
  118031. ParticleSystemSet.prototype.start = function (emitter) {
  118032. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118033. var system = _a[_i];
  118034. if (emitter) {
  118035. system.emitter = emitter;
  118036. }
  118037. system.start();
  118038. }
  118039. };
  118040. /**
  118041. * Release all associated resources
  118042. */
  118043. ParticleSystemSet.prototype.dispose = function () {
  118044. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118045. var system = _a[_i];
  118046. system.dispose();
  118047. }
  118048. this.systems = [];
  118049. if (this._emitterNode) {
  118050. this._emitterNode.dispose();
  118051. this._emitterNode = null;
  118052. }
  118053. };
  118054. /**
  118055. * Serialize the set into a JSON compatible object
  118056. * @returns a JSON compatible representation of the set
  118057. */
  118058. ParticleSystemSet.prototype.serialize = function () {
  118059. var result = {};
  118060. result.systems = [];
  118061. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118062. var system = _a[_i];
  118063. result.systems.push(system.serialize());
  118064. }
  118065. if (this._emitterNode) {
  118066. result.emitter = this._emitterCreationOptions;
  118067. }
  118068. return result;
  118069. };
  118070. /**
  118071. * Parse a new ParticleSystemSet from a serialized source
  118072. * @param data defines a JSON compatible representation of the set
  118073. * @param scene defines the hosting scene
  118074. * @param gpu defines if we want GPU particles or CPU particles
  118075. * @returns a new ParticleSystemSet
  118076. */
  118077. ParticleSystemSet.Parse = function (data, scene, gpu) {
  118078. if (gpu === void 0) { gpu = false; }
  118079. var result = new ParticleSystemSet();
  118080. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  118081. scene = scene || BABYLON.Engine.LastCreatedScene;
  118082. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  118083. var system = _a[_i];
  118084. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  118085. }
  118086. if (data.emitter) {
  118087. var options = data.emitter.options;
  118088. switch (data.emitter.kind) {
  118089. case "Sphere":
  118090. result.setEmitterAsSphere({
  118091. diameter: options.diameter,
  118092. segments: options.segments,
  118093. color: BABYLON.Color3.FromArray(options.color)
  118094. }, data.emitter.renderingGroupId, scene);
  118095. break;
  118096. }
  118097. }
  118098. return result;
  118099. };
  118100. return ParticleSystemSet;
  118101. }());
  118102. BABYLON.ParticleSystemSet = ParticleSystemSet;
  118103. })(BABYLON || (BABYLON = {}));
  118104. //# sourceMappingURL=babylon.particleSystemSet.js.map
  118105. var BABYLON;
  118106. (function (BABYLON) {
  118107. /**
  118108. * This class is made for on one-liner static method to help creating particle system set.
  118109. */
  118110. var ParticleHelper = /** @class */ (function () {
  118111. function ParticleHelper() {
  118112. }
  118113. /**
  118114. * Create a default particle system that you can tweak
  118115. * @param emitter defines the emitter to use
  118116. * @param capacity defines the system capacity (default is 500 particles)
  118117. * @param scene defines the hosting scene
  118118. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  118119. * @returns the new Particle system
  118120. */
  118121. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  118122. if (capacity === void 0) { capacity = 500; }
  118123. if (useGPU === void 0) { useGPU = false; }
  118124. var system;
  118125. if (useGPU) {
  118126. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  118127. }
  118128. else {
  118129. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  118130. }
  118131. system.emitter = emitter;
  118132. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  118133. system.createConeEmitter(0.1, Math.PI / 4);
  118134. // Particle color
  118135. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118136. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118137. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  118138. // Particle Size
  118139. system.minSize = 0.1;
  118140. system.maxSize = 0.1;
  118141. // Emission speed
  118142. system.minEmitPower = 2;
  118143. system.maxEmitPower = 2;
  118144. // Update speed
  118145. system.updateSpeed = 1 / 60;
  118146. system.emitRate = 30;
  118147. return system;
  118148. };
  118149. /**
  118150. * This is the main static method (one-liner) of this helper to create different particle systems
  118151. * @param type This string represents the type to the particle system to create
  118152. * @param scene The scene where the particle system should live
  118153. * @param gpu If the system will use gpu
  118154. * @returns the ParticleSystemSet created
  118155. */
  118156. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  118157. if (gpu === void 0) { gpu = false; }
  118158. if (!scene) {
  118159. scene = BABYLON.Engine.LastCreatedScene;
  118160. }
  118161. var token = {};
  118162. scene._addPendingData(token);
  118163. return new Promise(function (resolve, reject) {
  118164. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  118165. scene._removePendingData(token);
  118166. return reject("Particle system with GPU is not supported.");
  118167. }
  118168. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  118169. scene._removePendingData(token);
  118170. var newData = JSON.parse(data.toString());
  118171. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  118172. }, undefined, undefined, undefined, function (req, exception) {
  118173. scene._removePendingData(token);
  118174. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  118175. });
  118176. });
  118177. };
  118178. /**
  118179. * Static function used to export a particle system to a ParticleSystemSet variable.
  118180. * Please note that the emitter shape is not exported
  118181. * @param systems defines the particle systems to export
  118182. * @returns the created particle system set
  118183. */
  118184. ParticleHelper.ExportSet = function (systems) {
  118185. var set = new BABYLON.ParticleSystemSet();
  118186. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  118187. var system = systems_1[_i];
  118188. set.systems.push(system);
  118189. }
  118190. return set;
  118191. };
  118192. /**
  118193. * Gets or sets base Assets URL
  118194. */
  118195. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  118196. return ParticleHelper;
  118197. }());
  118198. BABYLON.ParticleHelper = ParticleHelper;
  118199. })(BABYLON || (BABYLON = {}));
  118200. //# sourceMappingURL=babylon.particleHelper.js.map
  118201. var BABYLON;
  118202. (function (BABYLON) {
  118203. /**
  118204. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  118205. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  118206. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  118207. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118208. */
  118209. var VideoDome = /** @class */ (function (_super) {
  118210. __extends(VideoDome, _super);
  118211. /**
  118212. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  118213. * @param name Element's name, child elements will append suffixes for their own names.
  118214. * @param urlsOrVideo defines the url(s) or the video element to use
  118215. * @param options An object containing optional or exposed sub element properties
  118216. */
  118217. function VideoDome(name, urlsOrVideo, options, scene) {
  118218. var _this = _super.call(this, name, scene) || this;
  118219. _this._useDirectMapping = false;
  118220. // set defaults and manage values
  118221. name = name || "videoDome";
  118222. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118223. options.clickToPlay = Boolean(options.clickToPlay);
  118224. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  118225. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  118226. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118227. if (options.useDirectMapping === undefined) {
  118228. _this._useDirectMapping = true;
  118229. }
  118230. else {
  118231. _this._useDirectMapping = options.useDirectMapping;
  118232. }
  118233. _this._setReady(false);
  118234. // create
  118235. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  118236. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118237. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  118238. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118239. texture.onLoadObservable.addOnce(function () {
  118240. _this._setReady(true);
  118241. });
  118242. // configure material
  118243. material.useEquirectangularFOV = true;
  118244. material.fovMultiplier = 1.0;
  118245. material.opacityFresnel = false;
  118246. if (_this._useDirectMapping) {
  118247. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118248. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118249. material.diffuseTexture = texture;
  118250. }
  118251. else {
  118252. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118253. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118254. material.reflectionTexture = texture;
  118255. }
  118256. // configure mesh
  118257. _this._mesh.material = material;
  118258. _this._mesh.parent = _this;
  118259. // optional configuration
  118260. if (options.clickToPlay) {
  118261. scene.onPointerUp = function () {
  118262. _this._videoTexture.video.play();
  118263. };
  118264. }
  118265. return _this;
  118266. }
  118267. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  118268. /**
  118269. * Gets the video texture being displayed on the sphere
  118270. */
  118271. get: function () {
  118272. return this._videoTexture;
  118273. },
  118274. enumerable: true,
  118275. configurable: true
  118276. });
  118277. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  118278. /**
  118279. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118280. * Also see the options.resolution property.
  118281. */
  118282. get: function () {
  118283. return this._material.fovMultiplier;
  118284. },
  118285. set: function (value) {
  118286. this._material.fovMultiplier = value;
  118287. },
  118288. enumerable: true,
  118289. configurable: true
  118290. });
  118291. /**
  118292. * Releases resources associated with this node.
  118293. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118294. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118295. */
  118296. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118297. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118298. this._videoTexture.dispose();
  118299. this._mesh.dispose();
  118300. this._material.dispose();
  118301. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118302. };
  118303. return VideoDome;
  118304. }(BABYLON.TransformNode));
  118305. BABYLON.VideoDome = VideoDome;
  118306. })(BABYLON || (BABYLON = {}));
  118307. //# sourceMappingURL=babylon.videoDome.js.map
  118308. var BABYLON;
  118309. (function (BABYLON) {
  118310. /**
  118311. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  118312. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  118313. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  118314. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118315. */
  118316. var PhotoDome = /** @class */ (function (_super) {
  118317. __extends(PhotoDome, _super);
  118318. /**
  118319. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  118320. * @param name Element's name, child elements will append suffixes for their own names.
  118321. * @param urlsOfPhoto defines the url of the photo to display
  118322. * @param options defines an object containing optional or exposed sub element properties
  118323. * @param onError defines a callback called when an error occured while loading the texture
  118324. */
  118325. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  118326. if (onError === void 0) { onError = null; }
  118327. var _this = _super.call(this, name, scene) || this;
  118328. _this._useDirectMapping = false;
  118329. /**
  118330. * Observable raised when an error occured while loading the 360 image
  118331. */
  118332. _this.onLoadErrorObservable = new BABYLON.Observable();
  118333. // set defaults and manage values
  118334. name = name || "photoDome";
  118335. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118336. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118337. if (options.useDirectMapping === undefined) {
  118338. _this._useDirectMapping = true;
  118339. }
  118340. else {
  118341. _this._useDirectMapping = options.useDirectMapping;
  118342. }
  118343. _this._setReady(false);
  118344. // create
  118345. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118346. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118347. // configure material
  118348. material.opacityFresnel = false;
  118349. material.useEquirectangularFOV = true;
  118350. material.fovMultiplier = 1.0;
  118351. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  118352. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  118353. if (onError) {
  118354. onError(message, exception);
  118355. }
  118356. });
  118357. _this.photoTexture.onLoadObservable.addOnce(function () {
  118358. _this._setReady(true);
  118359. });
  118360. // configure mesh
  118361. _this._mesh.material = material;
  118362. _this._mesh.parent = _this;
  118363. return _this;
  118364. }
  118365. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  118366. /**
  118367. * Gets or sets the texture being displayed on the sphere
  118368. */
  118369. get: function () {
  118370. return this._photoTexture;
  118371. },
  118372. set: function (value) {
  118373. if (this._photoTexture === value) {
  118374. return;
  118375. }
  118376. this._photoTexture = value;
  118377. if (this._useDirectMapping) {
  118378. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118379. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118380. this._material.diffuseTexture = this._photoTexture;
  118381. }
  118382. else {
  118383. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118384. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118385. this._material.reflectionTexture = this._photoTexture;
  118386. }
  118387. },
  118388. enumerable: true,
  118389. configurable: true
  118390. });
  118391. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  118392. /**
  118393. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118394. * Also see the options.resolution property.
  118395. */
  118396. get: function () {
  118397. return this._material.fovMultiplier;
  118398. },
  118399. set: function (value) {
  118400. this._material.fovMultiplier = value;
  118401. },
  118402. enumerable: true,
  118403. configurable: true
  118404. });
  118405. /**
  118406. * Releases resources associated with this node.
  118407. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118408. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118409. */
  118410. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118411. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118412. this._photoTexture.dispose();
  118413. this._mesh.dispose();
  118414. this._material.dispose();
  118415. this.onLoadErrorObservable.clear();
  118416. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118417. };
  118418. return PhotoDome;
  118419. }(BABYLON.TransformNode));
  118420. BABYLON.PhotoDome = PhotoDome;
  118421. })(BABYLON || (BABYLON = {}));
  118422. //# sourceMappingURL=babylon.photoDome.js.map
  118423. var BABYLON;
  118424. (function (BABYLON) {
  118425. /** @hidden */
  118426. var _OcclusionDataStorage = /** @class */ (function () {
  118427. function _OcclusionDataStorage() {
  118428. /** @hidden */
  118429. this.occlusionInternalRetryCounter = 0;
  118430. /** @hidden */
  118431. this.isOcclusionQueryInProgress = false;
  118432. /** @hidden */
  118433. this.isOccluded = false;
  118434. /** @hidden */
  118435. this.occlusionRetryCount = -1;
  118436. /** @hidden */
  118437. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  118438. /** @hidden */
  118439. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  118440. }
  118441. return _OcclusionDataStorage;
  118442. }());
  118443. BABYLON.Engine.prototype.createQuery = function () {
  118444. return this._gl.createQuery();
  118445. };
  118446. BABYLON.Engine.prototype.deleteQuery = function (query) {
  118447. this._gl.deleteQuery(query);
  118448. return this;
  118449. };
  118450. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  118451. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  118452. };
  118453. BABYLON.Engine.prototype.getQueryResult = function (query) {
  118454. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  118455. };
  118456. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  118457. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118458. this._gl.beginQuery(glAlgorithm, query);
  118459. return this;
  118460. };
  118461. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  118462. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118463. this._gl.endQuery(glAlgorithm);
  118464. return this;
  118465. };
  118466. BABYLON.Engine.prototype._createTimeQuery = function () {
  118467. var timerQuery = this.getCaps().timerQuery;
  118468. if (timerQuery.createQueryEXT) {
  118469. return timerQuery.createQueryEXT();
  118470. }
  118471. return this.createQuery();
  118472. };
  118473. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  118474. var timerQuery = this.getCaps().timerQuery;
  118475. if (timerQuery.deleteQueryEXT) {
  118476. timerQuery.deleteQueryEXT(query);
  118477. return;
  118478. }
  118479. this.deleteQuery(query);
  118480. };
  118481. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  118482. var timerQuery = this.getCaps().timerQuery;
  118483. if (timerQuery.getQueryObjectEXT) {
  118484. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  118485. }
  118486. return this.getQueryResult(query);
  118487. };
  118488. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  118489. var timerQuery = this.getCaps().timerQuery;
  118490. if (timerQuery.getQueryObjectEXT) {
  118491. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  118492. }
  118493. return this.isQueryResultAvailable(query);
  118494. };
  118495. BABYLON.Engine.prototype.startTimeQuery = function () {
  118496. var caps = this.getCaps();
  118497. var timerQuery = caps.timerQuery;
  118498. if (!timerQuery) {
  118499. return null;
  118500. }
  118501. var token = new BABYLON._TimeToken();
  118502. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118503. if (caps.canUseTimestampForTimerQuery) {
  118504. token._startTimeQuery = this._createTimeQuery();
  118505. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  118506. }
  118507. else {
  118508. if (this._currentNonTimestampToken) {
  118509. return this._currentNonTimestampToken;
  118510. }
  118511. token._timeElapsedQuery = this._createTimeQuery();
  118512. if (timerQuery.beginQueryEXT) {
  118513. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118514. }
  118515. else {
  118516. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118517. }
  118518. this._currentNonTimestampToken = token;
  118519. }
  118520. return token;
  118521. };
  118522. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  118523. var caps = this.getCaps();
  118524. var timerQuery = caps.timerQuery;
  118525. if (!timerQuery || !token) {
  118526. return -1;
  118527. }
  118528. if (caps.canUseTimestampForTimerQuery) {
  118529. if (!token._startTimeQuery) {
  118530. return -1;
  118531. }
  118532. if (!token._endTimeQuery) {
  118533. token._endTimeQuery = this._createTimeQuery();
  118534. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  118535. }
  118536. }
  118537. else if (!token._timeElapsedQueryEnded) {
  118538. if (!token._timeElapsedQuery) {
  118539. return -1;
  118540. }
  118541. if (timerQuery.endQueryEXT) {
  118542. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  118543. }
  118544. else {
  118545. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  118546. }
  118547. token._timeElapsedQueryEnded = true;
  118548. }
  118549. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118550. var available = false;
  118551. if (token._endTimeQuery) {
  118552. available = this._getTimeQueryAvailability(token._endTimeQuery);
  118553. }
  118554. else if (token._timeElapsedQuery) {
  118555. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  118556. }
  118557. if (available && !disjoint) {
  118558. var result = 0;
  118559. if (caps.canUseTimestampForTimerQuery) {
  118560. if (!token._startTimeQuery || !token._endTimeQuery) {
  118561. return -1;
  118562. }
  118563. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  118564. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  118565. result = timeEnd - timeStart;
  118566. this._deleteTimeQuery(token._startTimeQuery);
  118567. this._deleteTimeQuery(token._endTimeQuery);
  118568. token._startTimeQuery = null;
  118569. token._endTimeQuery = null;
  118570. }
  118571. else {
  118572. if (!token._timeElapsedQuery) {
  118573. return -1;
  118574. }
  118575. result = this._getTimeQueryResult(token._timeElapsedQuery);
  118576. this._deleteTimeQuery(token._timeElapsedQuery);
  118577. token._timeElapsedQuery = null;
  118578. token._timeElapsedQueryEnded = false;
  118579. this._currentNonTimestampToken = null;
  118580. }
  118581. return result;
  118582. }
  118583. return -1;
  118584. };
  118585. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  118586. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  118587. };
  118588. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  118589. get: function () {
  118590. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  118591. },
  118592. enumerable: false,
  118593. configurable: true
  118594. });
  118595. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  118596. get: function () {
  118597. if (!this.__occlusionDataStorage) {
  118598. this.__occlusionDataStorage = new _OcclusionDataStorage();
  118599. }
  118600. return this.__occlusionDataStorage;
  118601. },
  118602. enumerable: false,
  118603. configurable: true
  118604. });
  118605. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  118606. get: function () {
  118607. return this._occlusionDataStorage.isOccluded;
  118608. },
  118609. set: function (value) {
  118610. this._occlusionDataStorage.isOccluded = value;
  118611. },
  118612. enumerable: true,
  118613. configurable: true
  118614. });
  118615. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  118616. get: function () {
  118617. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  118618. },
  118619. set: function (value) {
  118620. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  118621. },
  118622. enumerable: true,
  118623. configurable: true
  118624. });
  118625. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  118626. get: function () {
  118627. return this._occlusionDataStorage.occlusionType;
  118628. },
  118629. set: function (value) {
  118630. this._occlusionDataStorage.occlusionType = value;
  118631. },
  118632. enumerable: true,
  118633. configurable: true
  118634. });
  118635. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  118636. get: function () {
  118637. return this._occlusionDataStorage.occlusionRetryCount;
  118638. },
  118639. set: function (value) {
  118640. this._occlusionDataStorage.occlusionRetryCount = value;
  118641. },
  118642. enumerable: true,
  118643. configurable: true
  118644. });
  118645. // We also need to update AbstractMesh as there is a portion of the code there
  118646. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  118647. var dataStorage = this._occlusionDataStorage;
  118648. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  118649. dataStorage.isOccluded = false;
  118650. return false;
  118651. }
  118652. var engine = this.getEngine();
  118653. if (engine.webGLVersion < 2) {
  118654. dataStorage.isOccluded = false;
  118655. return false;
  118656. }
  118657. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  118658. dataStorage.isOccluded = false;
  118659. return false;
  118660. }
  118661. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  118662. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  118663. if (isOcclusionQueryAvailable) {
  118664. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  118665. dataStorage.isOcclusionQueryInProgress = false;
  118666. dataStorage.occlusionInternalRetryCounter = 0;
  118667. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  118668. }
  118669. else {
  118670. dataStorage.occlusionInternalRetryCounter++;
  118671. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  118672. dataStorage.isOcclusionQueryInProgress = false;
  118673. dataStorage.occlusionInternalRetryCounter = 0;
  118674. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  118675. // if strict continue the last state of the object.
  118676. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  118677. }
  118678. else {
  118679. return false;
  118680. }
  118681. }
  118682. }
  118683. var scene = this.getScene();
  118684. if (scene.getBoundingBoxRenderer) {
  118685. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  118686. if (!this._occlusionQuery) {
  118687. this._occlusionQuery = engine.createQuery();
  118688. }
  118689. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  118690. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  118691. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  118692. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  118693. }
  118694. return dataStorage.isOccluded;
  118695. };
  118696. })(BABYLON || (BABYLON = {}));
  118697. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  118698. var BABYLON;
  118699. (function (BABYLON) {
  118700. /**
  118701. * Class used to generate noise procedural textures
  118702. */
  118703. var NoiseProceduralTexture = /** @class */ (function (_super) {
  118704. __extends(NoiseProceduralTexture, _super);
  118705. /**
  118706. * Creates a new NoiseProceduralTexture
  118707. * @param name defines the name fo the texture
  118708. * @param size defines the size of the texture (default is 256)
  118709. * @param scene defines the hosting scene
  118710. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  118711. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  118712. */
  118713. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  118714. if (size === void 0) { size = 256; }
  118715. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  118716. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  118717. _this._time = 0;
  118718. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  118719. _this.brightness = 0.2;
  118720. /** Defines the number of octaves to process */
  118721. _this.octaves = 3;
  118722. /** Defines the level of persistence (0.8 by default) */
  118723. _this.persistence = 0.8;
  118724. /** Gets or sets animation speed factor (default is 1) */
  118725. _this.animationSpeedFactor = 1;
  118726. _this.autoClear = false;
  118727. _this._updateShaderUniforms();
  118728. return _this;
  118729. }
  118730. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  118731. var scene = this.getScene();
  118732. if (!scene) {
  118733. return;
  118734. }
  118735. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  118736. this.setFloat("brightness", this.brightness);
  118737. this.setFloat("persistence", this.persistence);
  118738. this.setFloat("timeScale", this._time);
  118739. };
  118740. NoiseProceduralTexture.prototype._getDefines = function () {
  118741. return "#define OCTAVES " + (this.octaves | 0);
  118742. };
  118743. /** Generate the current state of the procedural texture */
  118744. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  118745. this._updateShaderUniforms();
  118746. _super.prototype.render.call(this, useCameraPostProcess);
  118747. };
  118748. /**
  118749. * Serializes this noise procedural texture
  118750. * @returns a serialized noise procedural texture object
  118751. */
  118752. NoiseProceduralTexture.prototype.serialize = function () {
  118753. var serializationObject = {};
  118754. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  118755. serializationObject.brightness = this.brightness;
  118756. serializationObject.octaves = this.octaves;
  118757. serializationObject.persistence = this.persistence;
  118758. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  118759. serializationObject.size = this.getSize().width;
  118760. serializationObject.generateMipMaps = this._generateMipMaps;
  118761. return serializationObject;
  118762. };
  118763. /**
  118764. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  118765. * @param parsedTexture defines parsed texture data
  118766. * @param scene defines the current scene
  118767. * @param rootUrl defines the root URL containing noise procedural texture information
  118768. * @returns a parsed NoiseProceduralTexture
  118769. */
  118770. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  118771. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  118772. texture.brightness = parsedTexture.brightness;
  118773. texture.octaves = parsedTexture.octaves;
  118774. texture.persistence = parsedTexture.persistence;
  118775. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  118776. return texture;
  118777. };
  118778. return NoiseProceduralTexture;
  118779. }(BABYLON.ProceduralTexture));
  118780. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  118781. })(BABYLON || (BABYLON = {}));
  118782. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  118783. var __assign = (this && this.__assign) || function () {
  118784. __assign = Object.assign || function(t) {
  118785. for (var s, i = 1, n = arguments.length; i < n; i++) {
  118786. s = arguments[i];
  118787. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  118788. t[p] = s[p];
  118789. }
  118790. return t;
  118791. };
  118792. return __assign.apply(this, arguments);
  118793. };
  118794. var BABYLON;
  118795. (function (BABYLON) {
  118796. /**
  118797. * This can helps recording videos from BabylonJS.
  118798. * This is based on the available WebRTC functionalities of the browser.
  118799. *
  118800. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  118801. */
  118802. var VideoRecorder = /** @class */ (function () {
  118803. /**
  118804. * Create a new VideoCapture object which can help converting what you see in Babylon to
  118805. * a video file.
  118806. * @param engine Defines the BabylonJS Engine you wish to record
  118807. * @param options Defines options that can be used to customized the capture
  118808. */
  118809. function VideoRecorder(engine, options) {
  118810. if (options === void 0) { options = null; }
  118811. if (!VideoRecorder.IsSupported(engine)) {
  118812. throw "Your browser does not support recording so far.";
  118813. }
  118814. var canvas = engine.getRenderingCanvas();
  118815. if (!canvas) {
  118816. throw "The babylon engine must have a canvas to be recorded";
  118817. }
  118818. this._canvas = canvas;
  118819. this._canvas.isRecording = false;
  118820. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  118821. var stream = this._canvas.captureStream(this._options.fps);
  118822. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  118823. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  118824. this._mediaRecorder.onerror = this._handleError.bind(this);
  118825. this._mediaRecorder.onstop = this._handleStop.bind(this);
  118826. }
  118827. /**
  118828. * Returns wehther or not the VideoRecorder is available in your browser.
  118829. * @param engine Defines the Babylon Engine to check the support for
  118830. * @returns true if supported otherwise false
  118831. */
  118832. VideoRecorder.IsSupported = function (engine) {
  118833. var canvas = engine.getRenderingCanvas();
  118834. return (!!canvas && typeof canvas.captureStream === "function");
  118835. };
  118836. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  118837. /**
  118838. * True wether a recording is already in progress.
  118839. */
  118840. get: function () {
  118841. return !!this._canvas && this._canvas.isRecording;
  118842. },
  118843. enumerable: true,
  118844. configurable: true
  118845. });
  118846. /**
  118847. * Stops the current recording before the default capture timeout passed in the startRecording
  118848. * functions.
  118849. */
  118850. VideoRecorder.prototype.stopRecording = function () {
  118851. if (!this._canvas || !this._mediaRecorder) {
  118852. return;
  118853. }
  118854. if (!this.isRecording) {
  118855. return;
  118856. }
  118857. this._canvas.isRecording = false;
  118858. this._mediaRecorder.stop();
  118859. };
  118860. /**
  118861. * Starts recording the canvas for a max duration specified in parameters.
  118862. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  118863. * @param maxDuration Defines the maximum recording time in seconds.
  118864. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  118865. * @return a promise callback at the end of the recording with the video data in Blob.
  118866. */
  118867. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  118868. var _this = this;
  118869. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  118870. if (maxDuration === void 0) { maxDuration = 7; }
  118871. if (!this._canvas || !this._mediaRecorder) {
  118872. throw "Recorder has already been disposed";
  118873. }
  118874. if (this.isRecording) {
  118875. throw "Recording already in progress";
  118876. }
  118877. if (maxDuration > 0) {
  118878. setTimeout(function () {
  118879. _this.stopRecording();
  118880. }, maxDuration * 1000);
  118881. }
  118882. this._fileName = fileName;
  118883. this._recordedChunks = [];
  118884. this._resolve = null;
  118885. this._reject = null;
  118886. this._canvas.isRecording = true;
  118887. this._mediaRecorder.start(this._options.recordChunckSize);
  118888. return new Promise(function (resolve, reject) {
  118889. _this._resolve = resolve;
  118890. _this._reject = reject;
  118891. });
  118892. };
  118893. /**
  118894. * Releases internal resources used during the recording.
  118895. */
  118896. VideoRecorder.prototype.dispose = function () {
  118897. this._canvas = null;
  118898. this._mediaRecorder = null;
  118899. this._recordedChunks = [];
  118900. this._fileName = null;
  118901. this._resolve = null;
  118902. this._reject = null;
  118903. };
  118904. VideoRecorder.prototype._handleDataAvailable = function (event) {
  118905. if (event.data.size > 0) {
  118906. this._recordedChunks.push(event.data);
  118907. }
  118908. };
  118909. VideoRecorder.prototype._handleError = function (event) {
  118910. this.stopRecording();
  118911. if (this._reject) {
  118912. this._reject(event.error);
  118913. }
  118914. else {
  118915. throw new event.error();
  118916. }
  118917. };
  118918. VideoRecorder.prototype._handleStop = function () {
  118919. this.stopRecording();
  118920. var superBuffer = new Blob(this._recordedChunks);
  118921. if (this._resolve) {
  118922. this._resolve(superBuffer);
  118923. }
  118924. window.URL.createObjectURL(superBuffer);
  118925. if (this._fileName) {
  118926. BABYLON.Tools.Download(superBuffer, this._fileName);
  118927. }
  118928. };
  118929. VideoRecorder._defaultOptions = {
  118930. mimeType: "video/webm",
  118931. fps: 25,
  118932. recordChunckSize: 3000
  118933. };
  118934. return VideoRecorder;
  118935. }());
  118936. BABYLON.VideoRecorder = VideoRecorder;
  118937. })(BABYLON || (BABYLON = {}));
  118938. //# sourceMappingURL=babylon.videoRecorder.js.map
  118939. var BABYLON;
  118940. (function (BABYLON) {
  118941. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  118942. if (replace === void 0) { replace = false; }
  118943. // Dispose existing light in replace mode.
  118944. if (replace) {
  118945. if (this.lights) {
  118946. for (var i = 0; i < this.lights.length; i++) {
  118947. this.lights[i].dispose();
  118948. }
  118949. }
  118950. }
  118951. // Light
  118952. if (this.lights.length === 0) {
  118953. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  118954. }
  118955. };
  118956. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  118957. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118958. if (replace === void 0) { replace = false; }
  118959. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118960. // Dispose existing camera in replace mode.
  118961. if (replace) {
  118962. if (this.activeCamera) {
  118963. this.activeCamera.dispose();
  118964. this.activeCamera = null;
  118965. }
  118966. }
  118967. // Camera
  118968. if (!this.activeCamera) {
  118969. var worldExtends = this.getWorldExtends();
  118970. var worldSize = worldExtends.max.subtract(worldExtends.min);
  118971. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  118972. var camera;
  118973. var radius = worldSize.length() * 1.5;
  118974. // empty scene scenario!
  118975. if (!isFinite(radius)) {
  118976. radius = 1;
  118977. worldCenter.copyFromFloats(0, 0, 0);
  118978. }
  118979. if (createArcRotateCamera) {
  118980. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  118981. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  118982. arcRotateCamera.wheelPrecision = 100 / radius;
  118983. camera = arcRotateCamera;
  118984. }
  118985. else {
  118986. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  118987. freeCamera.setTarget(worldCenter);
  118988. camera = freeCamera;
  118989. }
  118990. camera.minZ = radius * 0.01;
  118991. camera.maxZ = radius * 1000;
  118992. camera.speed = radius * 0.2;
  118993. this.activeCamera = camera;
  118994. var canvas = this.getEngine().getRenderingCanvas();
  118995. if (attachCameraControls && canvas) {
  118996. camera.attachControl(canvas);
  118997. }
  118998. }
  118999. };
  119000. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  119001. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  119002. if (replace === void 0) { replace = false; }
  119003. if (attachCameraControls === void 0) { attachCameraControls = false; }
  119004. this.createDefaultLight(replace);
  119005. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  119006. };
  119007. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  119008. if (pbr === void 0) { pbr = false; }
  119009. if (scale === void 0) { scale = 1000; }
  119010. if (blur === void 0) { blur = 0; }
  119011. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  119012. if (!environmentTexture) {
  119013. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  119014. return null;
  119015. }
  119016. if (setGlobalEnvTexture) {
  119017. if (environmentTexture) {
  119018. this.environmentTexture = environmentTexture;
  119019. }
  119020. }
  119021. // Skybox
  119022. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  119023. if (pbr) {
  119024. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  119025. hdrSkyboxMaterial.backFaceCulling = false;
  119026. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  119027. if (hdrSkyboxMaterial.reflectionTexture) {
  119028. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  119029. }
  119030. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  119031. hdrSkyboxMaterial.disableLighting = true;
  119032. hdrSkyboxMaterial.twoSidedLighting = true;
  119033. hdrSkybox.infiniteDistance = true;
  119034. hdrSkybox.material = hdrSkyboxMaterial;
  119035. }
  119036. else {
  119037. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  119038. skyboxMaterial.backFaceCulling = false;
  119039. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  119040. if (skyboxMaterial.reflectionTexture) {
  119041. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  119042. }
  119043. skyboxMaterial.disableLighting = true;
  119044. hdrSkybox.infiniteDistance = true;
  119045. hdrSkybox.material = skyboxMaterial;
  119046. }
  119047. return hdrSkybox;
  119048. };
  119049. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  119050. if (BABYLON.EnvironmentHelper) {
  119051. return new BABYLON.EnvironmentHelper(options, this);
  119052. }
  119053. return null;
  119054. };
  119055. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  119056. if (webVROptions === void 0) { webVROptions = {}; }
  119057. return new BABYLON.VRExperienceHelper(this, webVROptions);
  119058. };
  119059. BABYLON.Scene.prototype.createDefaultXRExperienceAsync = function () {
  119060. var _this = this;
  119061. return BABYLON.WebXRExperienceHelper.CreateAsync(this).then(function (helper) {
  119062. var outputCanvas = new BABYLON.WebXRManagedOutputCanvas(helper);
  119063. return BABYLON.WebXREnterExitUI.CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext })
  119064. .then(function (ui) {
  119065. new BABYLON.WebXRInput(helper);
  119066. return helper;
  119067. });
  119068. });
  119069. };
  119070. })(BABYLON || (BABYLON = {}));
  119071. //# sourceMappingURL=babylon.sceneHelpers.js.map
  119072. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\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 RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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#ifdef RAMPGRADIENT\nremapRanges=remapData;\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\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}","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\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\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 POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\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 CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\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#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\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#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\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 LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\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() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\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 POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\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,abs(randY),randZ);\ndirection=position+directionRandomizer*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\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(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\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\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \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 offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*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","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}","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\n#ifdef VELOCITY\nuniform mat4 previousWorldViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\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\n#ifdef VELOCITY\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousWorldViewProjection*vec4(position,1.0);\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 VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\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[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=(a-b)*0.5+0.5;\nvelocity*=0.5+0.5;\nvelocity=vec2(pow(velocity.x,3.0),pow(velocity.y,3.0));\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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}","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}","motionBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg;\nvec2 velocity=vec2(pow(velocityColor.r,1.0/3.0),pow(velocityColor.g,1.0/3.0))*2.0-1.0;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\ngl_FragColor=result/float(samplesCount);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  119073. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\nuniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));\nreturn mat4(m0,m1,m2,m3);\n}\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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif \n#else \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 \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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nmat4 result;\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nresult[0]=texture(smp,vec2(dx*(offset+0.5),0.));\nresult[1]=texture(smp,vec2(dx*(offset+1.5),0.));\nresult[2]=texture(smp,vec2(dx*(offset+2.5),0.));\nresult[3]=texture(smp,vec2(dx*(offset+3.5),0.));\nreturn result;\n}\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","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};","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};"};